snake/src/main.rs

83 lines
2.3 KiB
Rust
Raw Normal View History

2022-04-29 11:10:54 -05:00
use cat_box::{get_keyboard_state, Game, Sprite, SpriteCollection};
2022-04-30 11:08:08 -05:00
use rand::thread_rng;
use rand::Rng;
2022-04-29 11:10:54 -05:00
use sdl2::keyboard::Scancode;
2022-04-30 10:10:44 -05:00
use std::time::Duration;
#[derive(Copy, Clone, Debug)]
enum Direction {
Up,
Down,
Left,
Right,
}
2022-04-29 11:10:54 -05:00
2022-04-29 10:58:56 -05:00
fn main() {
2022-04-29 11:10:54 -05:00
let game = Game::new("Snake", 1000, 1000);
2022-04-29 11:30:14 -05:00
let snake_boxes: Vec<(i32, i32)> = vec![(13, 13), (14, 13)];
let mut snake = SpriteCollection::with_capacity(snake_boxes.len());
for (x, y) in snake_boxes {
let s = Sprite::new("snakecell.png", x * 37, y * 37).unwrap();
snake.push(s);
}
2022-04-29 11:10:54 -05:00
2022-04-30 11:08:08 -05:00
let mut apple = {
let x = thread_rng().gen_range(0..=27);
let y = thread_rng().gen_range(0..=27);
Sprite::new("apple.png", x * 37, y * 37).unwrap()
};
2022-04-30 10:10:44 -05:00
let mut dir = Direction::Left;
2022-04-29 11:10:54 -05:00
game.run(|ctx| {
let keys = get_keyboard_state(ctx).keys;
for key in keys {
2022-04-30 10:10:44 -05:00
match key {
Scancode::Q => game.terminate(),
2022-04-30 10:50:48 -05:00
Scancode::W | Scancode::Up => dir = Direction::Up,
Scancode::A | Scancode::Left => dir = Direction::Left,
Scancode::S | Scancode::Down => dir = Direction::Down,
Scancode::D | Scancode::Right => dir = Direction::Right,
2022-04-30 10:10:44 -05:00
_ => (),
};
}
2022-04-30 10:50:48 -05:00
{
let mut last_part = snake[0].position();
for s in snake.iter().skip(1) {
let (lastx, lasty) = last_part;
let (x, y) = s.position();
let (xdiff, ydiff) = (lastx - x, y - lasty);
s.translate((xdiff, ydiff));
last_part = s.position();
}
}
// The snake head needs to be moved after the body or else the body will just collapse into the head
2022-04-30 10:10:44 -05:00
match dir {
Direction::Up => {
snake[0].translate((0, 37));
}
Direction::Left => {
snake[0].translate((-37, 0));
}
Direction::Down => {
snake[0].translate((0, -37));
}
Direction::Right => {
snake[0].translate((37, 0));
}
};
2022-04-30 10:50:48 -05:00
// So that the snake doesn't move at super speed
2022-04-30 10:10:44 -05:00
std::thread::sleep(Duration::from_millis(125));
2022-04-30 11:08:08 -05:00
apple.draw(ctx).unwrap();
2022-04-29 11:30:14 -05:00
snake.draw(ctx).unwrap();
2022-04-29 11:10:54 -05:00
})
.unwrap();
2022-04-29 10:58:56 -05:00
}