diff --git a/.vscode/launch.json b/.vscode/launch.json index f3e821d..3578dad 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -14,6 +14,9 @@ ], }, + "env": { + "RUST_BACKTRACE": "1" + }, "args": [ ], "cwd": "${workspaceFolder}" diff --git a/src/components.rs b/src/components.rs index 4273428..019a75f 100644 --- a/src/components.rs +++ b/src/components.rs @@ -13,13 +13,11 @@ impl Element { pub(crate) fn new(name: &str) -> Result { match name { "wall" => Ok(Element { visual: '∩', e_type: "wall" }), - "spawn" => Ok(Element { visual: '@', e_type: "spawn" }), + "spawn" => Ok(Element { visual: '@', e_type: "spawner" }), "body_part_v" => Ok(Element { visual: '|', e_type: "alive" }), "body_part_h" => Ok(Element { visual: '-', e_type: "alive" }), "body_part_l" => Ok(Element { visual: '/', e_type: "alive" }), "body_part_r" => Ok(Element { visual: '\\', e_type: "alive" }), - "body_part_m+" => Ok(Element { visual: '+', e_type: "alive" }), - "body_part_mx" => Ok(Element { visual: 'X', e_type: "alive" }), "food" => Ok(Element { visual: '#', e_type: "food" }), "body_part_head" => Ok(Element { visual: '█', e_type: "alive" }), _ => Err(Error::new("Invalid element")), @@ -43,16 +41,17 @@ pub struct Part { impl Part { pub(crate) fn new(element: &str, position: (u16, u16), color: Color) -> Result { + let mut in_invalide:bool = false; if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 { // < 0 not needet because u16 is always positive - return Err(Error::new("Invalid position")); + in_invalide = true; } Ok(Part { element: Element::new(element)?, position, color: color, direction: String::from("_ _"), - killed: false, + killed: in_invalide, }) } pub(crate) fn copy(&self) -> Part { @@ -64,11 +63,17 @@ impl Part { direction: self.direction.clone(), } } + pub(crate) fn move_to(&mut self, new_position: (u16, u16), killed: bool) { + if new_position.0 > TERM_SIZE.0 || new_position.1 > TERM_SIZE.1 || killed { + self.killed = true; + } + self.position = new_position; + } } pub(crate) struct CanvasState { pub(crate) canvas: Vec, - pub(crate) prev_canvas: Vec, + pub(crate) colors: i32, pub(crate) iterations: u128, pub(crate) food_rate: u8, } @@ -77,18 +82,10 @@ impl CanvasState { pub(crate) fn new(canvas: Vec) -> CanvasState { CanvasState { canvas: canvas, - prev_canvas: Vec::new(), + colors: 0, iterations: 0, food_rate: 10, } } - pub(crate) fn update(self, new_canvas: Vec) -> CanvasState { - CanvasState { - canvas: new_canvas, - prev_canvas: self.canvas, - food_rate: self.food_rate, - iterations: self.iterations + 1, - } - } } diff --git a/src/main.rs b/src/main.rs index be7d187..88af587 100644 --- a/src/main.rs +++ b/src/main.rs @@ -49,16 +49,20 @@ fn draw_canvas(canvas: &Vec) { fn main() { let _ = enable_raw_mode(); + let mut stdout = io::stdout(); + stdout.queue(crossterm::cursor::Hide).unwrap(); + stdout.flush().unwrap(); let mut state: components::CanvasState = components::CanvasState::new(create_canvas()); draw_canvas(&state.canvas); loop { - - part_handler::head_handle(&mut state.canvas); - part_handler::spawner_handle(&mut state.canvas); + part_handler::head_handle(&mut state.canvas, &mut state.colors); + part_handler::spawner_handle(&mut state.canvas, &mut state.colors); + part_handler::handle_killed(&mut state.canvas); + //part_handler::spawn_food(&mut state.canvas); state.canvas.sort_by_key(|part| (part.position.1, part.position.0)); draw_canvas(&state.canvas); state.iterations += 1; - sleep(Duration::from_millis(17)); + sleep(Duration::from_millis(32)); } } \ No newline at end of file diff --git a/src/part_handler.rs b/src/part_handler.rs index 60d6339..68d89a7 100644 --- a/src/part_handler.rs +++ b/src/part_handler.rs @@ -5,7 +5,7 @@ use rand::Rng; use std::collections::HashMap; use crate::components::{self, Part}; -const SIGHT_RADIUS: u16 = 3; +const SIGHT_RADIUS: u16 = 5; lazy_static! { static ref CHECK_DIRECTIONS: HashMap<&'static str, ([&'static str; 3], &'static str ), > = HashMap::from([ @@ -30,15 +30,7 @@ lazy_static!{ ]); } -lazy_static!{ - static ref Direction_Part: HashMap<&'static str, &'static str> = HashMap::from([ - ("t", "body_part_v"), - ("b", "body_part_v"), - ("r", "body_part_h"), - ("l", "body_part_h"), - ("_", "body_part_head") - ]); -} + fn check_collision(canvas: &Vec, position: (u16, u16)) -> bool { canvas.iter().filter(|elem| elem.position == position).count() > 0 @@ -55,12 +47,23 @@ fn get_unused_color(canvas: &Vec) -> Color { color } -pub fn spawner_handle(canvas: &mut Vec) { +pub fn spawner_handle(canvas: &mut Vec, heads: &i32) { + let inactive_spawns: Vec = canvas.iter() + .enumerate() + .filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 100, b: 10 } && elem.element.e_type == "spawner") + .map(|(index, _)| index) + .collect(); + + if *heads < inactive_spawns.len() as i32{ + canvas[inactive_spawns[0]].color = Color::Rgb { r: 10, g: 255, b: 10 }; + } + + // Collect the indices of active spawns let active_spawn_indices: Vec = canvas .iter_mut() .enumerate() - .filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 255, b: 10 }) + .filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 255, b: 10 } && elem.element.e_type == "spawner") .map(|(index, _)| index) .collect(); @@ -84,6 +87,7 @@ pub fn spawner_handle(canvas: &mut Vec) { } } } + } fn recursive_colision_check(color: &Color, parts_in_sight: &Vec, position: &(u16, u16), direction: &str, iterations_left: u8) -> (i32, i32, &'static str , i64){ @@ -125,12 +129,14 @@ fn recursive_colision_check(color: &Color, parts_in_sight: &Vec, position: b.2.cmp(&a.2) compares the third element of b and a (in reverse order because we want the highest element first). */ } - -pub fn head_handle(canvas: &mut Vec) { - // Find all elements that head can see +pub fn head_handle(canvas: &mut Vec, head_count: &mut i32) { // Find all elements that head can see + let mut heads = 0; for head_index in 0..canvas.len() { if canvas[head_index].element.visual == '█' { + // Keep track on how many heads are there + heads += 1; + let parts_in_sight: Vec = canvas.iter() .enumerate() .filter(|(_, elem)| @@ -142,9 +148,61 @@ pub fn head_handle(canvas: &mut Vec) { let res = recursive_colision_check(&canvas[head_index].color, &parts_in_sight, &canvas[head_index].position , &canvas[head_index].direction.to_string() , 3); let old_pos: (u16, u16) = canvas[head_index].position; + + // Check colisions of new position + let colision = canvas.iter().filter(|elem| elem.position == (res.0 as u16, res.1 as u16)) + .filter(|elem| elem.element.e_type != "food").count() > 0; + + // Move the head to the new position, spawn a new body part and update the direction canvas[head_index].direction = res.2.to_string(); - canvas[head_index].position = (res.0 as u16, res.1 as u16); + canvas[head_index].move_to((res.0 as u16, res.1 as u16), colision); canvas.push(components::Part::new(CHECK_DIRECTIONS[res.2].1, old_pos, canvas[head_index].color).unwrap()); + + // Clean up food + let mut to_remove: Vec = Vec::new(); + // Iterate over a mutable reference to the canvas vector + for (index, element) in canvas.iter_mut().enumerate() { + if element.position == (res.0 as u16, res.1 as u16) && element.element.e_type == "food" { + to_remove.push(index); + } + } + + // Remove elements from the canvas vector based on the condition + to_remove.iter().for_each(|x| {canvas.remove(*x);}); + } + } + *head_count = heads; +} + +pub fn handle_killed(canvas: &mut Vec) { + let to_remove: Vec = canvas.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect(); + for index in &to_remove { + for mod_y in -1..=1i32 { + for mod_x in -1..=1i32 { + canvas.iter() + .enumerate() + .filter(|(_, elem)| elem.color == canvas[*index].color) + .filter(|(_, elem)| elem.position == ((canvas[*index].position.0.try_into().unwrap_or_else(|_| 2) + mod_x).try_into().unwrap_or_else(|_| 0), + (canvas[*index].position.1.try_into().unwrap_or_else(|_| 2) + mod_y).try_into().unwrap_or_else(|_| 0))) + .map(|(index, _)| index) + .collect::>().iter().for_each(|x| canvas[*x].killed = true); + } + } + } + // Must be hear else the indices will be wrong + for index in to_remove.iter().rev() { + canvas.remove(*index); } } + +pub fn spawn_food(canvas: &mut Vec) { + let mut rng = rand::thread_rng(); + + if rng.gen_bool(0.2){ + let mut pos: (u16, u16) = (rng.gen_range(1..crate::TERM_SIZE.0 - 1), rng.gen_range(1..crate::TERM_SIZE.1 - 1)); + while check_collision(canvas, pos) { + pos = (rng.gen_range(1..crate::TERM_SIZE.0 - 1), rng.gen_range(1..crate::TERM_SIZE.1 - 1)); + } + canvas.push(components::Part::new("food", pos, get_unused_color(canvas)).unwrap()); + } } \ No newline at end of file