Improve Logic.
1 file changed, 40 insertions(+), 16 deletions(-)
@@ -1,7 +1,7 @@
use std::ops::Add;
use rand::Rng;
use std::ops::Add;
use crate::{renderer::Renderer};
use crate::renderer::Renderer;
#[derive(Copy, Clone, PartialEq)]
pub enum GameState {
@@ -10,7 +10,7 @@
Over,
}
#[derive(Copy, Clone, PartialEq)] // أضف هذي السطور
#[derive(Copy, Clone, PartialEq)]
pub enum PlayerDirection {
Up,
Down,
@@ -25,8 +25,8 @@
pub fn random() -> Self {
let mut rng = rand::rng();
Point(
rng.random_range(0..Renderer::GRID_X_SIZE as i32),
rng.random_range(0..Renderer::GRID_X_SIZE as i32)
rng.random_range(0..Renderer::GRID_X_SIZE as i32),
rng.random_range(0..Renderer::GRID_X_SIZE as i32),
)
}
}
@@ -57,14 +57,17 @@
}
pub fn next_tick(&mut self) {
if let GameState::Paused = self.state {
if self.state != GameState::Playing {
return;
}
let back_position = *self.player_position.last().unwrap();
let next_head_position = self.next_head_position(self.player_direction);
if self.player_position.contains(&next_head_position) {
self.state = GameState::Over;
return;
}
self.player_position.insert(0, next_head_position);
if self.food.contains(&next_head_position) {
@@ -80,13 +83,13 @@
// Food
fn generate_food(&mut self) {
loop {
let new_food = Point::random();
if !self.player_position.contains(&new_food) {
self.food.push(new_food);
break;
}
}
let empty_points: Vec<Point> = (0..Renderer::GRID_Y_SIZE)
.flat_map(|y| (0..Renderer::GRID_X_SIZE).map(move |x| Point(x as i32, y as i32)))
.filter(|p| !self.player_position.contains(p) && !self.food.contains(p))
.collect();
let mut rng = rand::rng();
if empty_points.is_empty() { return };
self.food.push(empty_points[rng.random_range(0..empty_points.len() - 1)])
}
// Player
@@ -128,14 +131,35 @@
pub fn next_head_position(&mut self, direction: PlayerDirection) -> Point {
let head_position = self.player_position.first().unwrap();
match direction {
let next_head_position = match direction {
PlayerDirection::Up => *head_position + Point(0, -1),
PlayerDirection::Down => *head_position + Point(0, 1),
PlayerDirection::Right => *head_position + Point(1, 0),
PlayerDirection::Left => *head_position + Point(-1, 0),
};
match next_head_position {
mut head if head.0.is_negative() => {
head.0 = Renderer::GRID_X_SIZE as i32 - 1;
head
}
mut head if head.0 > Renderer::GRID_X_SIZE as i32 => {
head.0 = 0;
head
}
mut head if head.1.is_negative() => {
head.1 = Renderer::GRID_Y_SIZE as i32 - 1;
head
}
mut head if head.1 > Renderer::GRID_Y_SIZE as i32 => {
head.1 = 0;
head
}
_ => next_head_position,
}
}
// Game State
pub fn toggle_pause(&mut self) {