From 47519bea20abd0a9cad679ce8c4e856dba690133 Mon Sep 17 00:00:00 2001 From: someone Date: Sat, 9 Mar 2024 19:31:37 +0100 Subject: [PATCH] solit path_handler in pathfinder, improved wesps --- src/components.rs | 40 +++++++---- src/main.rs | 23 +++--- src/part_handler.rs | 165 +------------------------------------------- src/pathfinder.rs | 143 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 187 insertions(+), 184 deletions(-) create mode 100644 src/pathfinder.rs diff --git a/src/components.rs b/src/components.rs index 8497790..627673d 100644 --- a/src/components.rs +++ b/src/components.rs @@ -46,7 +46,11 @@ pub fn directions_to_check(current_dir: &(DirectionX, DirectionY), fov: isize) - // index = (index +1) % array.len(); loop through the array avoiding out of bounds //% operator is the remainder operator, not the modulo operator let index_circle = (((current_index + i)%circle_len) + circle_len)%circle_len; + if i == 0 { + directions_to_check.insert(0, circle[index_circle as usize]) + } else { directions_to_check.push(circle[index_circle as usize]); + } } directions_to_check } @@ -83,6 +87,8 @@ pub enum Element { BodyPartRightLean, Food, BodyPartHead, + WespHead, + WespBody, } #[derive(Copy, Clone)] @@ -112,16 +118,20 @@ impl Creature { if new_position.0 > TERM_SIZE.0 || new_position.0 <= 0 || new_position.1 > TERM_SIZE.1 || new_position.1 <= 0 || colision { self.killed = true; } - let part_to_append = match moved_in_direction { - (DirectionX::None, DirectionY::Up) => Element::BodyPartVert, - (DirectionX::Right,DirectionY::Up) => Element::BodyPartLeftLean, - (DirectionX::Left, DirectionY::Up) => Element::BodyPartRightLean, - (DirectionX::None, DirectionY::Down) =>Element::BodyPartVert, - (DirectionX::Right,DirectionY::Down) =>Element::BodyPartRightLean, - (DirectionX::Left, DirectionY::Down) =>Element::BodyPartLeftLean, - (DirectionX::Right,DirectionY::None) =>Element::BodyPartHori, - (DirectionX::Left, DirectionY::None) =>Element::BodyPartHori, - _ => Element::BodyPartHori, + let part_to_append = if self.species == Species::Wesp { + Element::WespBody + } else { + match moved_in_direction { + (DirectionX::None, DirectionY::Up) => Element::BodyPartVert, + (DirectionX::Right,DirectionY::Up) => Element::BodyPartLeftLean, + (DirectionX::Left, DirectionY::Up) => Element::BodyPartRightLean, + (DirectionX::None, DirectionY::Down) =>Element::BodyPartVert, + (DirectionX::Right,DirectionY::Down) =>Element::BodyPartRightLean, + (DirectionX::Left, DirectionY::Down) =>Element::BodyPartLeftLean, + (DirectionX::Right,DirectionY::None) =>Element::BodyPartHori, + (DirectionX::Left, DirectionY::None) =>Element::BodyPartHori, + _ => Element::BodyPartHori, + } }; self.parts.append(&mut vec![Part { element: part_to_append, position: old_position, color: self.color }]); @@ -145,7 +155,7 @@ impl CanvasParts{ 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 => { + Element::BodyPartVert | Element::BodyPartHori | Element::BodyPartLeftLean | Element::BodyPartRightLean | Element::WespBody => { if let Some(index) = creature_index { let color = self.alive[index].color; self.alive[index].parts.push(Part { element: new_element, position, color: color }); @@ -153,10 +163,16 @@ impl CanvasParts{ panic!("No creature index provided"); } } + _ => panic!("Creature heads may not be added with this function. Use add_creature instead."), } } pub(crate) fn add_creature(&mut self, position: (u16, u16), color: Color, curent_direction: (DirectionX, DirectionY), species: Species, spawner_at: (u16, u16)) { - self.alive.push(Creature {parts: vec![Part { element: Element::BodyPartHead, position: position, color: color }], + let head = match species { + Species::Wesp => Element::WespHead, + _ => Element::BodyPartHead, + }; + + self.alive.push(Creature {parts: vec![Part { element: head, position: position, color: color }], color: color, curent_direction: curent_direction, killed: false, species: species, spawner_at: spawner_at}); } diff --git a/src/main.rs b/src/main.rs index 89f6381..46edd8d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ pub use std; // for documentation purposes use std::io::{self, Write}; use components::CanvasParts; -use crossterm::{cursor::MoveTo, execute, queue, style::{Color, PrintStyledContent, Stylize}, terminal::{enable_raw_mode, EnableLineWrap}, QueueableCommand}; +use crossterm::{cursor::MoveTo, execute, queue, style::{Color, PrintStyledContent, Stylize}, terminal::EnableLineWrap, QueueableCommand}; use lazy_static::lazy_static; //lazy_static is ok, mutability not needed use rand::{thread_rng, Rng}; @@ -13,6 +13,7 @@ use std::collections::HashMap; mod part_handler; mod components; +mod pathfinder; const SPAWNERS:u16 = 3; @@ -30,6 +31,8 @@ lazy_static!{ (components::Element::BodyPartLeftLean, '/'), (components::Element::Food, '#'), (components::Element::BodyPartHead, '█'), + (components::Element::WespHead, '0'), + (components::Element::WespBody, '•'), ]); } @@ -78,29 +81,31 @@ fn draw_canvas(canvas: &CanvasParts, cleared_coords: &mut Vec<(u16, u16)>) { fn main() { // Prepare the terminal - //let _ = enable_raw_mode(); execute!(io::stdout(), EnableLineWrap).unwrap(); let mut stdout = io::stdout(); stdout.queue(crossterm::cursor::Hide).unwrap(); stdout.queue(crossterm::terminal::Clear(crossterm::terminal::ClearType::All)).unwrap(); stdout.flush().unwrap(); + // Create the canvas let mut canvas: CanvasParts = create_canvas(); let mut state = components::CanvasState { iterations: 0, cleared_coords: Vec::new() }; //food_rate: 0 draw_canvas(&canvas, &mut state.cleared_coords); loop { - //let mut now = Instant::now(); - part_handler::head_handle(&mut canvas); + let now = Instant::now(); + pathfinder::head_handle(&mut canvas); part_handler::spawner_handle(&mut canvas); part_handler::handle_killed(&mut canvas.alive, &mut state.cleared_coords); part_handler::spawn_food(&mut canvas); - //let elapsed_calc = now.elapsed(); - //now = Instant::now(); + draw_canvas(&canvas, &mut state.cleared_coords); - //let elapsed = now.elapsed(); - //println!("Print Elapsed: {:.2?}, Calc Elapsed: {:.2?}", elapsed, elapsed_calc); state.iterations += 1; - sleep(Duration::from_millis(8)); + + let elapsed = now.elapsed(); + if elapsed < Duration::from_millis(50) { + sleep(Duration::from_millis(50) - elapsed); + } + } } \ No newline at end of file diff --git a/src/part_handler.rs b/src/part_handler.rs index 7483e3d..7e7ece7 100644 --- a/src/part_handler.rs +++ b/src/part_handler.rs @@ -1,21 +1,7 @@ -use std::thread; -use std::sync::mpsc; use crossterm::style::Color; -use lazy_static::lazy_static; use rand::Rng; -use crate::HashMap; -use crate::components::{self, directions_to_check, pos_alteration_by_direction, CanvasParts, Creature, DirectionX, DirectionY, Element, Part, Species}; -const SIGHT_RADIUS: u16 = 4; - - -lazy_static!{ - static ref ITERATION_TIMES: HashMap = HashMap::from([ - (Species::DetachedSnake, 1), - (Species::NormalSnake, 1), - (Species::Wesp, 2), - ]); -} +use crate::components::{CanvasParts, Creature, DirectionX, DirectionY, Element, Part, Species}; fn check_collision(canvas: &Vec, position: (u16, u16)) -> bool { @@ -80,153 +66,6 @@ pub fn spawner_handle(canvas: &mut CanvasParts) { } -fn snake_path_match(elem:Element) -> i64 { - match elem { - Element::Wall | Element::Spawn => -100, - Element::BodyPartHori | Element::BodyPartVert | - Element::BodyPartLeftLean | Element::BodyPartRightLean | Element::BodyPartHead => -100, - Element::Food => 10, - _ => 0, - } -} - -fn wesp_path_match(elem:Element) -> i64 { - match elem { - Element::Wall | Element::Spawn | Element::Food => -100, - Element::BodyPartHead => 30, - _ => 0, - } -} - -fn recursive_colision_check(path_to_match: fn(Element) -> i64, parts_in_sight: &Vec, fov: isize, position: &(u16, u16), - direction: &(DirectionX, DirectionY), iterations_left: u8, ) -> (i32, i32, (DirectionX, DirectionY), i64){ - // Position to check x, Position to check y, Direction to walk, Vale of Direction - let mut dyn_pos_res: Vec<(i32, i32, (DirectionX, DirectionY), i64)> = Vec::new(); - - - // Create a vector of tuples with the possible positions and their values(liklihood of beeing chosen) - for direction_to_check in directions_to_check(&direction, fov).iter() { - let (dir_x, dir_y): (DirectionX, DirectionY) = ((*direction_to_check).0, (*direction_to_check).1); - let (x, y): (i32, i32) = pos_alteration_by_direction(Some(&dir_x), Some(&dir_y), position); - dyn_pos_res.push((x, y, (dir_x, dir_y), 0)); - } - - let (sender, receiver) = mpsc::channel(); - let mut threads: Vec> = Vec::new(); - // 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, mut val): (i32, i32, (DirectionX, DirectionY), i64) = dyn_pos_res[index].clone(); - for part in parts_in_sight { - if part.position == (x as u16, y as u16) { - //When element in sight, part is element in sight - val = path_to_match(part.element) - } - } - dyn_pos_res[index].3 = val; - - if iterations_left > 0 { - let sender = sender.clone(); - let parts_in_sight = parts_in_sight.clone(); - threads.push(thread::spawn(move || { - let t_val = recursive_colision_check(path_to_match, &parts_in_sight, fov, &(x as u16, y as u16), &v_direction, iterations_left - 1).3; - sender.send((t_val, index)).unwrap(); - })); - } - } - - - for _ in 0..(threads.len()) { - let thread_res = receiver.recv().unwrap(); - dyn_pos_res[thread_res.1].3 += thread_res.0; - } - - - dyn_pos_res.sort_by(|a, b| b.3.cmp(&a.3)); - dyn_pos_res[0] - /*In this example, the sort_by method is used to sort the vector data. - The closure provided to sort_by compares tuples (i32, i32, u32) based on the third element (u32). - 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 CanvasParts) { - //Todo: Reomve or improve threading in this function!! - // Find all elements that head can see - let (sender, receiver) = mpsc::channel(); - let mut wesp_kills: Vec = Vec::new(); - - let cloned_canvas = canvas.clone(); - for creature in canvas.alive.iter_mut() { - let fov = match creature.species { - Species::DetachedSnake => 2, - _ => 1, - }; - for _ in 0..ITERATION_TIMES[&creature.species] { - let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead).next(); - if head.is_none() { - continue; - } - let head = head.unwrap().clone(); // Clone the head to avoid borrowing issues - - - // Concartination of all parts in sight - let parts_in_sight: Vec = cloned_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 matcher: fn(Element) -> i64 = match creature.species { - Species::DetachedSnake | Species::NormalSnake => snake_path_match, - Species::Wesp => wesp_path_match, - }; - - - let parts_in_sight_thread = parts_in_sight.clone(); - let dir_thread = creature.curent_direction.clone(); - let sender = sender.clone(); - - let thread = thread::spawn(move || { - let result = recursive_colision_check(matcher, &parts_in_sight_thread, fov, - &head.position, &dir_thread , SIGHT_RADIUS as u8); - sender.send(result).unwrap(); - }); - - let res: (i32, i32, (DirectionX, DirectionY), i64) = receiver.recv().unwrap(); - thread.join().unwrap(); - - // Check colisions of new position - let mut colision = false; - if creature.species == Species::Wesp { - for part in parts_in_sight.iter() { - if part.position == (res.0 as u16, res.1 as u16) && part.element == Element::BodyPartHead{ - wesp_kills.push(cloned_canvas.alive.iter().position(|x| x.parts[0].position == (res.0 as u16, res.1 as u16)).unwrap()); - } else if part.position == (res.0 as u16, res.1 as u16) && part.element == Element::Food { - colision = true; - } - } - } else { - colision = parts_in_sight.iter().any(|elem| elem.position == (res.0 as u16, res.1 as u16) && elem.element != Element::Food); - } - // 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); - } - } - - // Remove elements from the canvas vector based on the condition - to_remove.iter().for_each(|x| {canvas.interactable.remove(*x);}); - } - } - wesp_kills.iter().for_each(|x| {canvas.alive[*x].killed = true;}); -} - pub fn handle_killed(creatures: &mut Vec, cleared_coords: &mut Vec<(u16, u16)>) { //let killed_creatures: Vec = creatures.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect::>(); @@ -238,7 +77,7 @@ pub fn handle_killed(creatures: &mut Vec, cleared_coords: &mut Vec<(u1 if creature.species == Species::DetachedSnake && creature.parts.len() > 20 { cleared_coords.push(creature.parts[1].position); //0 Is head, 1 is oldes part creature.parts.remove(1); - } else if creature.species == Species::Wesp && creature.parts.len() > 3 { + } else if creature.species == Species::Wesp && creature.parts.len() > 8 { cleared_coords.push(creature.parts[1].position); // cleared_coords.push(creature.parts[2].position); creature.parts.remove(1); //0 Is head, 1 is oldes part, tow parts are removed diff --git a/src/pathfinder.rs b/src/pathfinder.rs new file mode 100644 index 0000000..b72fc76 --- /dev/null +++ b/src/pathfinder.rs @@ -0,0 +1,143 @@ + +use crate::components::{DirectionX, DirectionY, Element, Part, Species, directions_to_check, pos_alteration_by_direction}; +use crate::CanvasParts; +use std::thread; +use std::sync::mpsc; + +fn snake_path_match(elem:Element) -> i64 { + match elem { + Element::Wall | Element::Spawn => -100, + Element::BodyPartHori | Element::BodyPartVert | Element::WespBody | Element::WespHead | + Element::BodyPartLeftLean | Element::BodyPartRightLean | Element::BodyPartHead => -100, + Element::Food => 10, + } +} + +fn wesp_path_match(elem:Element) -> i64 { + match elem { + Element::Wall | Element::Spawn | Element::Food => -100, + Element::WespBody => -20, + Element::BodyPartHead => 30, + _ => 1, + } +} + +fn recursive_colision_check(path_to_match: fn(Element) -> i64, parts_in_sight: &Vec, fov: isize, position: &(u16, u16), + direction: &(DirectionX, DirectionY), iterations_left: u8) -> (i32, i32, (DirectionX, DirectionY), i64){ + // Position to check x, Position to check y, Direction to walk, Vale of Direction + let mut dyn_pos_res: Vec<(i32, i32, (DirectionX, DirectionY), i64)> = Vec::new(); + + + // Create a vector of tuples with the possible positions and their values(liklihood of beeing chosen) + for direction_to_check in directions_to_check(&direction, fov).iter() { + let (dir_x, dir_y): (DirectionX, DirectionY) = ((*direction_to_check).0, (*direction_to_check).1); + let (x, y): (i32, i32) = pos_alteration_by_direction(Some(&dir_x), Some(&dir_y), position); + dyn_pos_res.push((x, y, (dir_x, dir_y), 0)); + } + + let (sender, receiver) = mpsc::channel(); + let mut threads: Vec> = Vec::new(); + // 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, mut val): (i32, i32, (DirectionX, DirectionY), i64) = dyn_pos_res[index].clone(); + for part in parts_in_sight { + if part.position == (x as u16, y as u16) { + //When element in sight, part is element in sight + val = path_to_match(part.element) + } + } + dyn_pos_res[index].3 = val; + + if iterations_left > 0 { + let sender = sender.clone(); + let parts_in_sight = parts_in_sight.clone(); + threads.push(thread::spawn(move || { + let t_val = recursive_colision_check(path_to_match, &parts_in_sight, fov, &(x as u16, y as u16), &v_direction, iterations_left - 1).3; + sender.send((t_val, index)).unwrap(); + })); + } + } + + + for _ in 0..(threads.len()) { + let thread_res = receiver.recv().unwrap(); + dyn_pos_res[thread_res.1].3 += thread_res.0; + } + + + dyn_pos_res.sort_by(|a, b| b.3.cmp(&a.3)); + dyn_pos_res[0] + /*In this example, the sort_by method is used to sort the vector data. + The closure provided to sort_by compares tuples (i32, i32, u32) based on the third element (u32). + 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 CanvasParts) { + //Todo: Reomve or improve threading in this function!! + // Find all elements that head can see + let mut wesp_kills: Vec = Vec::new(); + + let cloned_canvas = canvas.clone(); + for creature in canvas.alive.iter_mut() { + + let (fov, speed, sight_radius): (isize, u8, i32) = match creature.species { + Species::DetachedSnake => (2, 1, 4), + Species::Wesp => (1, 2, 4), + _ => (1, 1, 4), + }; + + for _ in 0..speed { + let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead || elem.element == Element::WespHead).next(); + if head.is_none() { + continue; + } + let head = head.unwrap().clone(); // Clone the head to avoid borrowing issues + + + // Concartination of all parts in sight + let parts_in_sight: Vec = cloned_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 matcher: fn(Element) -> i64 = match creature.species { + Species::DetachedSnake | Species::NormalSnake => snake_path_match, + Species::Wesp => wesp_path_match, + }; + + let res = recursive_colision_check(matcher, &parts_in_sight, fov, + &head.position, &creature.curent_direction , sight_radius as u8); + + // Check colisions of new position + let mut colision = false; + if creature.species == Species::Wesp { + for part in parts_in_sight.iter() { + if part.position == (res.0 as u16, res.1 as u16) && part.element == Element::BodyPartHead{ + wesp_kills.push(cloned_canvas.alive.iter().position(|x| x.parts[0].position == (res.0 as u16, res.1 as u16)).unwrap()); + } else if part.position == (res.0 as u16, res.1 as u16) && part.element == Element::Food { + colision = true; + } + } + } else { + colision = parts_in_sight.iter().any(|elem| elem.position == (res.0 as u16, res.1 as u16) && elem.element != Element::Food); + } + // 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); + } + } + + // Remove elements from the canvas vector based on the condition + to_remove.iter().for_each(|x| {canvas.interactable.remove(*x);}); + } + } + wesp_kills.iter().for_each(|x| {canvas.alive[*x].killed = true;}); +}