summaryrefslogtreecommitdiff
path: root/src/move_snake.rs
blob: 4439be5728a7f47a138dd14d4834c07fcd6ab922 (plain)
use core::time::Duration;

use rand::RngExt;
use tortuise_script::{random::TortuiseRng, time::Instant, ScriptContext, TortuiseScript};

use crate::{
    Position, APPLE_LOCATION, DIRECTION, GRID_SIZE, IS_PAUSED, NEXT_MOVE_TIME, SNAKE_CELLS,
};

pub const MOVE_SNAKE: TortuiseScript = TortuiseScript {
    update: |context: ScriptContext| {
        let mut apple_location = APPLE_LOCATION.get_mut(&context);
        let mut snake_cells = SNAKE_CELLS.get_mut(&context);
        let mut next_move = NEXT_MOVE_TIME.get_mut(&context);
        let direction = DIRECTION.get(&context);
        let is_paused = IS_PAUSED.get(&context);

        let mut rng = TortuiseRng::new();
        let time = Instant::now(&context);
        if time > *next_move && !*is_paused {
            if snake_cells[0] == *apple_location {
                *apple_location = Position {
                    x: rng.random_range(0..GRID_SIZE as i16),
                    y: rng.random_range(0..GRID_SIZE as i16),
                };
                let new_head = Position {
                    x: snake_cells[0].x + direction.x,
                    y: snake_cells[0].y + direction.y,
                };
                snake_cells.insert(0, new_head);
            }
            *next_move += Duration::from_millis(200);
            for i in (1..snake_cells.len()).rev() {
                snake_cells[i] = snake_cells[i - 1];
            }
            snake_cells[0].x += direction.x;
            snake_cells[0].y += direction.y;
        }
        if time > *next_move {
            *next_move += Duration::from_millis(200);
        }
    },
    ..TortuiseScript::empty()
};