From 54b555fb8d7ccdac5bdd7587647b236649f3c7c4 Mon Sep 17 00:00:00 2001 From: someone Date: Wed, 6 Mar 2024 00:33:07 +0100 Subject: [PATCH] reorganised internal data structure of canvas elements --- .rustc_info.json | 1 + src/components.rs | 153 ++++++++++++++++-------------- src/main.rs | 61 ++++++++---- src/part_handler.rs | 226 ++++++++++++++++++++++---------------------- 4 files changed, 237 insertions(+), 204 deletions(-) create mode 100644 .rustc_info.json diff --git a/.rustc_info.json b/.rustc_info.json new file mode 100644 index 0000000..7c55134 --- /dev/null +++ b/.rustc_info.json @@ -0,0 +1 @@ +{"rustc_fingerprint":4779126909798716430,"outputs":{"15729799797837862367":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.so\nlib___.so\nlib___.a\nlib___.so\n/usr\noff\npacked\nunpacked\n___\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"gnu\"\ntarget_family=\"unix\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"linux\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"unknown\"\nunix\n","stderr":""},"4614504638168534921":{"success":true,"status":"","code":0,"stdout":"rustc 1.76.0 (07dca489a 2024-02-04) (Arch Linux rust 1:1.76.0-1)\nbinary: rustc\ncommit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce\ncommit-date: 2024-02-04\nhost: x86_64-unknown-linux-gnu\nrelease: 1.76.0\nLLVM version: 16.0.6\n","stderr":""}},"successes":{}} \ No newline at end of file diff --git a/src/components.rs b/src/components.rs index 019a75f..fbab77f 100644 --- a/src/components.rs +++ b/src/components.rs @@ -1,91 +1,106 @@ use crossterm::style::Color; + + use crate::TERM_SIZE; -use rand::Error; +use crate::part_handler; -pub(crate) struct Element { - pub(crate) visual: char, - pub(crate) e_type: &'static str, +#[derive(PartialEq, Eq, Hash, Copy, Clone)] +pub enum Direction { + Up, + Down, + Left, + Right, + None, } -impl Element { - pub(crate) fn new(name: &str) -> Result { - match name { - "wall" => Ok(Element { visual: '∩', e_type: "wall" }), - "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" }), - "food" => Ok(Element { visual: '#', e_type: "food" }), - "body_part_head" => Ok(Element { visual: '█', e_type: "alive" }), - _ => Err(Error::new("Invalid element")), - } - } - pub(crate) fn copy(&self) -> Element { - Element { - visual: self.visual, - e_type: self.e_type, - } - } +#[derive(PartialEq, Eq, Hash, Copy, Clone)] + +pub enum Element { + Wall, + Spawn, + BodyPartVert, + BodyPartHori, + BodyPartLeftLean, + BodyPartRightLean, + Food, + BodyPartHead, } +#[derive(Copy, Clone)] pub struct Part { pub(crate) element: Element, pub(crate) position: (u16, u16), - pub(crate) color: Color, + pub(crate) color: Color, +} + + +#[derive(Clone)] + +pub(crate) struct Creature { + pub(crate) parts: Vec, + pub(crate) color: Color, + pub(crate) curent_direction: (Direction, Direction), + pub(crate) spawner_at: (u16, u16), pub(crate) killed: bool, - pub(crate) direction: std::string::String, //"t/b/_ l/r/_" } -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 - in_invalide = true; - } - Ok(Part { - element: Element::new(element)?, - position, - color: color, - direction: String::from("_ _"), - killed: in_invalide, - }) - } - pub(crate) fn copy(&self) -> Part { - Part { - element: self.element.copy(), - position: self.position, - color: self.color, - killed: self.killed, - 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 { +impl Creature { + pub(crate) fn move_to(&mut self, new_position: (u16, u16), moved_in_direction: (Direction, Direction), colision: bool) { + let old_position = self.parts[0].position; // 0 Allways the head + self.parts[0].position = new_position; + self.curent_direction = moved_in_direction; + if new_position.0 > TERM_SIZE.0 || new_position.1 > TERM_SIZE.1 || colision { self.killed = true; - } - self.position = new_position; + } + self.parts.append(&mut vec![Part { element: part_handler::CHECK_DIRECTIONS[&self.curent_direction].1, + position: old_position, color: self.color }]); + +} +} +#[derive(Clone)] +pub(crate) struct CanvasParts { + pub(crate) alive: Vec, + pub(crate) environment: Vec, + pub(crate) interactable: Vec, +} + +impl CanvasParts{ + pub(crate) fn add_element(&mut self, new_element: Element, position: (u16, u16), color: Option, + creature_index: Option){ + if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 { + return; + } + + match new_element { + Element::Wall => self.environment.push(Part { element: new_element, position, color: color.unwrap() }), + Element::Spawn | Element::Food => self.interactable.push(Part { element: new_element, position, color: color.unwrap() }), + Element::BodyPartHead | Element::BodyPartVert | Element::BodyPartHori | Element::BodyPartLeftLean | Element::BodyPartRightLean => { + if let Some(index) = creature_index { + let color = self.alive[index].color; + self.alive[index].parts.push(Part { element: new_element, position, color: color }); + } else { + panic!("No creature index provided"); + } + } + } +} + pub(crate) fn add_creature(&mut self, position: (u16, u16), color: Color, curent_direction: (Direction, Direction), spawner_at: (u16, u16)) { + self.alive.push(Creature {parts: vec![Part { element: Element::BodyPartHead, position: position, color: color }], + color: color, curent_direction: curent_direction, killed: false, spawner_at: spawner_at}); + } + + pub(crate) fn unify_elements(&self) -> Vec<&Part> { + let unified_elements = Vec::from_iter(self.environment.iter() + .chain(self.interactable.iter()) + .chain(self.alive.iter().flat_map(|creature| creature.parts.iter()))); + unified_elements } } -pub(crate) struct CanvasState { - pub(crate) canvas: Vec, +pub struct CanvasState { pub(crate) colors: i32, pub(crate) iterations: u128, - pub(crate) food_rate: u8, + //pub(crate) food_rate: u8, } - -impl CanvasState { - pub(crate) fn new(canvas: Vec) -> CanvasState { - CanvasState { - canvas: canvas, - colors: 0, - iterations: 0, - food_rate: 10, - } - } -} - diff --git a/src/main.rs b/src/main.rs index 8aede09..adb22f9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,14 @@ #[doc(inline)] pub use std; // for documentation purposes use std::io::{self, Write}; +use components::CanvasParts; use crossterm::{cursor::MoveTo, queue, QueueableCommand, style::{PrintStyledContent, Stylize, Color}, terminal::enable_raw_mode}; use lazy_static::lazy_static; //lazy_static is ok, mutability not needed use rand::{thread_rng, Rng}; use std::time::Duration; use std::thread::sleep; +use std::collections::HashMap; mod part_handler; mod components; @@ -15,55 +17,74 @@ lazy_static! { static ref TERM_SIZE: (u16, u16) = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size")); } +lazy_static!{ + static ref ELEMENT_VISUALS: HashMap = HashMap::from([ + (components::Element::Wall, 'H'), + (components::Element::Spawn, '@'), + (components::Element::BodyPartVert, '|'), + (components::Element::BodyPartHori, '-'), + (components::Element::BodyPartRightLean, '\\'), + (components::Element::BodyPartLeftLean, '/'), + (components::Element::Food, '#'), + (components::Element::BodyPartHead, '█'), + ]); + } -fn create_canvas() -> Vec{ + +fn create_canvas() -> CanvasParts{ let mut rng = thread_rng(); - let mut canvas: Vec = Vec::new(); // Create an empty vector to store the parts + let mut canvas = CanvasParts {alive: Vec::new(), environment: Vec::new(), interactable: Vec::new()}; // Create an empty vector to store the parts let wall_color = Color::Rgb { r: 255, g: 60, b: 70 }; // Create a new color for the walls for y in 0..TERM_SIZE.1 { if y == 0 || y == TERM_SIZE.1 - 1 { for x in 0..TERM_SIZE.0 { - let part = components::Part::new("wall", (x, y), wall_color).unwrap(); // Use array indexing instead of tuple indexing - canvas.push(part); - + canvas.add_element(components::Element::Wall, (x, y), Some(wall_color), None); } } else { - canvas.push(components::Part::new("wall", (0, y), wall_color).unwrap()); // Use array indexing instead of tuple indexing - canvas.push(components::Part::new("wall", (TERM_SIZE.0 - 1, y), wall_color).unwrap()); // Use array indexing instead of tuple indexing + canvas.add_element(components::Element::Wall, (TERM_SIZE.0 - 1, y), Some(wall_color), None); // Use array indexing instead of tuple indexing + canvas.add_element(components::Element::Wall, (0, y), Some(wall_color), None); // Use array indexing instead of tuple indexing } } - for i in 0..3{ - canvas.push(components::Part::new("spawn", (rng.gen_range(1..TERM_SIZE.0-1), rng.gen_range(1..TERM_SIZE.1-1)), Color::Rgb { r: 10, g: 255, b: 10 }).unwrap()); // Use array indexing instead of tuple indexing + for _ in 0..3{ + // Use array indexing instead of tuple indexing + canvas.add_element(components::Element::Spawn, (rng.gen_range(1..TERM_SIZE.0-1), rng.gen_range(1..TERM_SIZE.1-1)), Some(Color::Rgb { r: 10, g: 255, b: 10 }), None); } canvas // Return the canvas vector } -fn draw_canvas(canvas: &Vec) { +fn draw_canvas(canvas: &CanvasParts) { let mut stdout = io::stdout(); stdout.queue(crossterm::terminal::Clear(crossterm::terminal::ClearType::All)).unwrap(); - for part in canvas { + let mut unified_elements = canvas.unify_elements(); + unified_elements.sort_by_key(|part| (part.position.1, part.position.0)); + + for part in unified_elements.iter() { queue!(stdout, MoveTo(part.position.0, part.position.1), - PrintStyledContent(part.element.visual.to_string().with(part.color))).unwrap(); + PrintStyledContent(ELEMENT_VISUALS[&part.element].to_string().with(part.color))).unwrap(); } stdout.flush().unwrap(); } fn main() { + // Prepare the terminal 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); + + // Create the canvas + let mut canvas: CanvasParts = create_canvas(); + let mut state = components::CanvasState {colors: 0, iterations: 0, }; //food_rate: 0 + draw_canvas(&canvas); loop { - 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); + part_handler::head_handle(&mut canvas, &mut state.colors); + part_handler::spawner_handle(&mut canvas, &mut state.colors); + part_handler::handle_killed(&mut canvas.alive); + part_handler::spawn_food(&mut canvas); + + draw_canvas(&canvas); state.iterations += 1; sleep(Duration::from_millis(32)); } diff --git a/src/part_handler.rs b/src/part_handler.rs index 68d89a7..95cbb94 100644 --- a/src/part_handler.rs +++ b/src/part_handler.rs @@ -2,118 +2,117 @@ use crossterm::style::Color; use lazy_static::lazy_static; use rand::Rng; -use std::collections::HashMap; +use crate::HashMap; -use crate::components::{self, Part}; +use crate::components::{self, CanvasParts, Creature, Direction, Element, Part}; const SIGHT_RADIUS: u16 = 5; lazy_static! { - static ref CHECK_DIRECTIONS: HashMap<&'static str, ([&'static str; 3], &'static str ), > = HashMap::from([ - ("t _", (["t _", "t r", "t l"], "body_part_h")), - ("t r", (["t r", "t _", "_ r"], "body_part_l")), - ("t l", (["t l", "t _", "_ l"], "body_part_r")), - ("b _", (["b _", "b r", "b l"], "body_part_h")), - ("b r", (["b r", "b _", "_ r"], "body_part_r")), - ("b l", (["b l", "b _", "_ l"], "body_part_l")), - ("_ r", (["_ r", "t r", "b r"], "body_part_v")), - ("_ l", (["_ l", "t l", "b l"], "body_part_v")), + pub static ref CHECK_DIRECTIONS: HashMap<(Direction, Direction), (Vec>, Element)> = HashMap::from([ + ((Direction::Up, Direction::None), (vec![vec![Direction::Up, Direction::None], vec![Direction::Up, Direction::Right], vec![Direction::Up, Direction::Left]], Element::BodyPartHori)), + ((Direction::Up, Direction::Right), (vec![vec![Direction::Up, Direction::Right], vec![Direction::Up, Direction::None], vec![Direction::None, Direction::Right]], Element::BodyPartLeftLean)), + ((Direction::Up, Direction::Left), (vec![vec![Direction::Up, Direction::Left], vec![Direction::Up, Direction::None], vec![Direction::None, Direction::Left]], Element::BodyPartRightLean)), + ((Direction::Down, Direction::None), (vec![vec![Direction::Down, Direction::None], vec![Direction::Down, Direction::Right], vec![Direction::Down, Direction::Left]], Element::BodyPartHori)), + ((Direction::Down, Direction::Right), (vec![vec![Direction::Down, Direction::Right], vec![Direction::Down, Direction::None], vec![Direction::None, Direction::Right]], Element::BodyPartRightLean)), + ((Direction::Down, Direction::Left), (vec![vec![Direction::Down, Direction::Left], vec![Direction::Down, Direction::None], vec![Direction::None, Direction::Left]], Element::BodyPartLeftLean)), + ((Direction::None, Direction::Right), (vec![vec![Direction::None, Direction::Right], vec![Direction::Up, Direction::Right], vec![Direction::Down, Direction::Right]], Element::BodyPartVert)), + ((Direction::None, Direction::Left), (vec![vec![Direction::None, Direction::Left], vec![Direction::Up, Direction::Left], vec![Direction::Down, Direction::Left]], Element::BodyPartVert)), ]); } lazy_static!{ - static ref DIRECTIONS: HashMap<&'static str, i32> = HashMap::from([ - ("t", -1), - ("b", 1), - ("r", 1), - ("l", -1), - ("_", 0) + static ref DIRECTIONS: HashMap = HashMap::from([ + (Direction::Up, -1), + (Direction::Down, 1), + (Direction::Right, 1), + (Direction::Left, -1), + (Direction::None, 0) ]); } -fn check_collision(canvas: &Vec, position: (u16, u16)) -> bool { +fn check_collision(canvas: &Vec, position: (u16, u16)) -> bool { canvas.iter().filter(|elem| elem.position == position).count() > 0 } -fn get_unused_color(canvas: &Vec) -> Color { +fn get_unused_color(creatures: &Vec) -> Color { let mut color: Color = Color::Rgb { r: 0, g: 0, b: 0 }; let mut color_used: bool = true; let mut rand_gen = rand::thread_rng(); while color_used { color = Color::Rgb { r: rand_gen.gen_range(0..255), g: rand_gen.gen_range(0..255), b: rand_gen.gen_range(0..255) }; - color_used = canvas.iter().filter(|elem| elem.color == color).count() > 0; + color_used = creatures.iter().filter(|cret| cret.color == color).count() > 0; } color } -pub fn spawner_handle(canvas: &mut Vec, heads: &i32) { - let inactive_spawns: Vec = canvas.iter() +pub fn spawner_handle(canvas: &mut CanvasParts, heads: &i32) { + let inactive_spawns: Vec = canvas.interactable.iter() .enumerate() - .filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 100, b: 10 } && elem.element.e_type == "spawner") + .filter(|(_, elem)| elem.element == Element::Spawn && canvas.alive.iter().filter(|creature| creature.spawner_at == elem.position).count() == 0) .map(|(index, _)| index) .collect(); if *heads < inactive_spawns.len() as i32{ - canvas[inactive_spawns[0]].color = Color::Rgb { r: 10, g: 255, b: 10 }; + canvas.interactable[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() + let active_spawn_indices: Vec = canvas.interactable.iter_mut() .enumerate() - .filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 255, b: 10 } && elem.element.e_type == "spawner") + .filter(|(_, elem)| elem.element == Element::Spawn && canvas.alive.iter().filter(|creature| creature.spawner_at == elem.position).count() == 0) .map(|(index, _)| index) .collect(); let mut rand_gen = rand::thread_rng(); - + //let enviorment = canvas.environment.clone(); for &index in &active_spawn_indices { let x: u8 = rand_gen.gen_range(0..100); if rand_gen.gen_range(0..100) < 10 { - let pos: (u16, u16, &str) = match x % 4 { + let pos: (u16, u16, (Direction, Direction)) = match x % 4 { // 0: up 1: right 2: down 3: left - 0 => (canvas[index].position.0, canvas[index].position.1 - 1, "t _"), - 1 => (canvas[index].position.0 + 1, canvas[index].position.1, "_ r"), - 2 => (canvas[index].position.0, canvas[index].position.1 + 1, "b _"), - 3 => (canvas[index].position.0 - 1, canvas[index].position.1, "_ l"), - _ => (1, 1, "b _"), + 0 => (canvas.interactable[index].position.0, canvas.interactable[index].position.1 - 1, (Direction::Up, Direction::None)), + 1 => (canvas.interactable[index].position.0 + 1, canvas.interactable[index].position.1, (Direction::None, Direction::Right)), + 2 => (canvas.interactable[index].position.0, canvas.interactable[index].position.1 + 1, (Direction::Down, Direction::None)), + 3 => (canvas.interactable[index].position.0 - 1, canvas.interactable[index].position.1, (Direction::None, Direction::Left)), + _ => (1, 1, (Direction::Down, Direction::None)), }; - if !check_collision(canvas, (pos.0, pos.1)) { - canvas.push(components::Part::new("body_part_head", (pos.0, pos.1), get_unused_color(canvas)).unwrap()); - canvas.last_mut().unwrap().direction = pos.2.to_string(); - canvas[index].color = Color::Rgb { r: 10, g: 100, b: 10 }; + + if !check_collision(&canvas.environment, (pos.0, pos.1)) { + canvas.add_creature((pos.0, pos.1), get_unused_color(&canvas.alive), pos.2, canvas.interactable[index].position); + canvas.interactable[index].color = Color::Rgb { r: 10, g: 100, b: 10 }; } } } } -fn recursive_colision_check(color: &Color, parts_in_sight: &Vec, position: &(u16, u16), direction: &str, iterations_left: u8) -> (i32, i32, &'static str , i64){ - let mut dyn_pos_res: Vec<(i32, i32, &str , i64)> = Vec::new(); +fn recursive_colision_check(color: &Color, parts_in_sight: &Vec, position: &(u16, u16), + direction: &(Direction, Direction), iterations_left: u8) -> (i32, i32, (Direction, Direction), i64) { + // Position to check x, Position to check y, Direction to walk, Vale of Direction + let mut dyn_pos_res: Vec<(i32, i32, (Direction, Direction) , i64)> = Vec::new(); // Create a vector of tuples with the possible positions and their values(liklihood of beeing chosen) - for direction_to_check in CHECK_DIRECTIONS[direction].0.into_iter() { - let x = direction_to_check.split_whitespace().take(2).collect::>(); - dyn_pos_res.push((i32::from(position.0) + DIRECTIONS[x[0]], i32::from(position.1) + DIRECTIONS[x[1]], direction_to_check , 0)); + for direction_to_check in CHECK_DIRECTIONS[&direction].0.iter() { + let (dir_x, dir_y): (Direction, Direction) = (direction_to_check[0], direction_to_check[1]); + dyn_pos_res.push((i32::from(position.0) + DIRECTIONS[&dir_x], i32::from(position.1) + DIRECTIONS[&dir_y], (dir_x, dir_y), 0)); } // Iterate over the vector and check if the position is in sight, what value the sight has for index in 0..dyn_pos_res.len() { - let (x, y, v_direction, val): &mut (i32, i32, &str, i64) = &mut dyn_pos_res[index]; + let (x, y, v_direction, val): &mut (i32, i32, (Direction, Direction), i64) = &mut dyn_pos_res[index]; for part in parts_in_sight { if part.position == (*x as u16, *y as u16) { //When element in sight, part is element in sight - if part.element.e_type == "alive" {//&& part.color != *color - *val -= 100; - } - else if part.element.e_type == "food" { - *val += 100; - } - else if part.element.e_type == "wall" { - *val -= 10000; - } + *val = match part.element { + Element::Wall => -1000, + Element::BodyPartHori | Element::BodyPartVert | + Element::BodyPartLeftLean | Element::BodyPartRightLean | Element::BodyPartHead => *val -1000, + Element::Food => 100, + _ => 0, + } } } if iterations_left > 0 { @@ -129,80 +128,77 @@ 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, head_count: &mut i32) { +pub fn head_handle(canvas: &mut CanvasParts, 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)| - (elem.position.0 as i64 - canvas[head_index].position.0 as i64).pow(2) + - (elem.position.1 as i64 - canvas[head_index].position.1 as i64).pow(2) <= SIGHT_RADIUS.pow(2) as i64 - ) - .map(|(_, elem)| elem.copy()) - .collect(); - - 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].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 = canvas.alive.len() as i32; + let unified_canvas = canvas.clone(); + for creature in canvas.alive.iter_mut() { + let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead).next(); + if head.is_none() { + continue; } - } - *head_count = heads; -} + let head = head.unwrap(); + -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); - } + // Concartination of all parts in sight + let parts_in_sight: Vec = unified_canvas.unify_elements().iter() + .filter(|elem| + (elem.position.0 as i64 - head.position.0 as i64).pow(2) + + (elem.position.1 as i64 - head.position.1 as i64).pow(2) <= SIGHT_RADIUS.pow(2) as i64) + .map(|elem| **elem) + .collect::>(); + let res: (i32, i32, (Direction, Direction), i64) = recursive_colision_check(&head.color, &parts_in_sight, + &head.position, &creature.curent_direction , 3); + + // Check colisions of new position + let colision = parts_in_sight.iter().filter(|elem| elem.position == (res.0 as u16, res.1 as u16)) + .filter(|elem| elem.element != Element::Food).count() > 0; + + // Move the head to the new position, spawn a new body part and update the direction + creature.move_to((res.0 as u16, res.1 as u16), res.2, colision); + + // Clean up food + let mut to_remove: Vec = Vec::new(); + // Iterate over a mutable reference to the canvas vector + for (index, element) in canvas.interactable.iter_mut().enumerate() { + if element.position == (res.0 as u16, res.1 as u16) && element.element == Element::Food { + to_remove.push(index); + } } - } - // Must be hear else the indices will be wrong - for index in to_remove.iter().rev() { - canvas.remove(*index); + + // Remove elements from the canvas vector based on the condition + to_remove.iter().for_each(|x| {canvas.interactable.remove(*x);}); } } -pub fn spawn_food(canvas: &mut Vec) { + +pub fn handle_killed(creatures: &mut Vec) { + let killed_creatures: Vec = creatures.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect::>(); + for index in &killed_creatures { + //let len_creature = creatures[index].parts.len(); + for _ in 0..=3 { + if creatures[*index].parts.len() == 0 { + break; + } + creatures[*index].parts.remove(0); + } + } + for index in killed_creatures.iter().rev() { + if creatures[*index].parts.len() == 0 { + creatures.remove(*index); + } +} +} + + +pub fn spawn_food(canvas: &mut CanvasParts) { 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) { + while check_collision(&canvas.unify_elements().iter().map(|part| **part).collect(), 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()); + canvas.add_element(Element::Food, pos, Some(get_unused_color(&canvas.alive)), None); } } \ No newline at end of file