From a184fcc5327da6954eb66ee8910e8494c381015b Mon Sep 17 00:00:00 2001 From: someone Date: Sat, 9 Mar 2024 23:07:04 +0100 Subject: [PATCH] Made MAX_THREADS a static, reduced spawnrate of floating snakes, leanup head handler --- src/main.rs | 16 +++++++--- src/part_handler.rs | 4 +-- src/pathfinder.rs | 73 +++++++++++++++++++++++++++++---------------- 3 files changed, 61 insertions(+), 32 deletions(-) diff --git a/src/main.rs b/src/main.rs index 138803e..5afbb28 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::EnableLineWrap, QueueableCommand}; +use crossterm::{cursor::{self, 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}; @@ -72,6 +72,9 @@ fn draw_canvas(canvas: &CanvasParts, cleared_coords: &mut Vec<(u16, u16)>) { } for part in unified_elements.iter() { + if true && part.position.1 == TERM_SIZE.1 - 1 { + continue; + } queue!(stdout, MoveTo(part.position.0, part.position.1), PrintStyledContent(ELEMENT_VISUALS[&part.element].to_string().with(part.color))).unwrap(); @@ -92,6 +95,7 @@ fn main() { 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); + let mut last_refresh = Instant::now(); loop { let now = Instant::now(); pathfinder::head_handle(&mut canvas); @@ -103,10 +107,14 @@ fn main() { state.iterations += 1; let elapsed = now.elapsed(); - if elapsed < Duration::from_millis(50) { - sleep(Duration::from_millis(50) - elapsed); + if elapsed < Duration::from_millis(0) { + sleep(Duration::from_millis(0) - elapsed); + } + if true && last_refresh.elapsed() > Duration::from_secs_f64(0.5) { + queue!(stdout, MoveTo(0, TERM_SIZE.1), PrintStyledContent(format!("Iterations: {} FPS: {:?}", state.iterations, 1000.0 / (elapsed.as_secs_f64() + 0.00)).with(Color::Reset))).unwrap(); + stdout.flush().unwrap(); + last_refresh = Instant::now(); } - } } \ No newline at end of file diff --git a/src/part_handler.rs b/src/part_handler.rs index 213ed15..00dd9d0 100644 --- a/src/part_handler.rs +++ b/src/part_handler.rs @@ -47,8 +47,8 @@ pub fn spawner_handle(canvas: &mut CanvasParts) { if !check_collision(&canvas.environment, (pos.0, pos.1)) { let color = get_unused_color(&canvas.alive); match x % 10 { - 0 | 1 => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::DetachedSnake, canvas.interactable[index].position), - 2 => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::Wesp, canvas.interactable[index].position), + 0 => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::DetachedSnake, canvas.interactable[index].position), + 1 => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::Wesp, canvas.interactable[index].position), _ => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::NormalSnake, canvas.interactable[index].position), } canvas.interactable[index].color = Color::Rgb { r: 10, g: 100, b: 10 }; diff --git a/src/pathfinder.rs b/src/pathfinder.rs index c373692..6179a6d 100644 --- a/src/pathfinder.rs +++ b/src/pathfinder.rs @@ -3,8 +3,11 @@ use crate::components::{DirectionX, DirectionY, Element, Part, Species, directio use crate::CanvasParts; use std::thread; use std::sync::mpsc; +use lazy_static::lazy_static; -const MAX_THREADS: u32 = 24; +lazy_static!{ + static ref MAX_THREADS: u32 = 0; // Make the variable +} fn snake_path_match(elem:Element) -> i64 { @@ -25,6 +28,25 @@ fn wesp_path_match(elem:Element) -> i64 { } } + +fn snake_colision_matcher(parts_in_sight: &Vec, position: &(u16, u16), canvas: &CanvasParts) -> (bool, Option>) { + let colision = parts_in_sight.iter().any(|elem| elem.position == (position.0 as u16, position.1 as u16) && elem.element != Element::Food); + (colision, None) +} + +fn wesp_colision_matcher(parts_in_sight: &Vec, position: &(u16, u16), canvas: &CanvasParts) -> (bool, Option>) { + let mut wesp_kills: Vec = Vec::new(); + let mut colision = false; + for part in parts_in_sight.iter() { + if part.position == (position.0 as u16, position.1 as u16) && part.element == Element::BodyPartHead{ + wesp_kills.push(canvas.alive.iter().position(|x| x.parts[0].position == (position.0 as u16, position.1 as u16)).unwrap()); + } else if part.position == (position.0 as u16, position.1 as u16) && part.element == Element::Food { + colision = true; + } + }; + (colision, Some(wesp_kills)) +} + 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, iterations_passed: u32) -> (i32, i32, (DirectionX, DirectionY), i64){ // Position to check x, Position to check y, Direction to walk, Vale of Direction @@ -54,7 +76,7 @@ fn recursive_colision_check(path_to_match: fn(Element) -> i64, parts_in_sight: & if iterations_left > 0 { let sender = sender.clone(); let parts_in_sight = parts_in_sight.clone(); - if ((dyn_pos_res.len() as i32).pow(iterations_passed) as u32) < MAX_THREADS { + if *MAX_THREADS != 0 && ((dyn_pos_res.len() as i32).pow(iterations_passed) as u32) < *MAX_THREADS { // Test for 0 to avoid calculation time 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, iterations_passed +1).3; sender.send((t_val, index)).unwrap(); @@ -82,16 +104,26 @@ fn recursive_colision_check(path_to_match: fn(Element) -> i64, parts_in_sight: & 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 mut foreign_changes: Vec = Vec::new(); - let cloned_canvas = canvas.clone(); - for creature in canvas.alive.iter_mut() { + let mut cloned_canvas = canvas.clone(); + for (index, creature) in canvas.alive.iter_mut().enumerate() { let (fov, speed, sight_radius): (isize, u8, i32) = match creature.species { Species::DetachedSnake => (2, 1, 4), Species::Wesp => (1, 2, 4), _ => (1, 1, 4), }; + let (eveluation_fn, colision_fn) = match creature.species { + Species::DetachedSnake | Species::NormalSnake => ( + snake_path_match as fn(Element) -> i64, + snake_colision_matcher as fn(&Vec, &(u16, u16), &CanvasParts) -> (bool, Option<_>) + ), + Species::Wesp => ( + wesp_path_match as fn(Element) -> i64, + wesp_colision_matcher as fn(&Vec, &(u16, u16), &CanvasParts) -> (bool, Option<_>) + ), + }; for _ in 0..speed { let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead || elem.element == Element::WespHead).next(); @@ -99,8 +131,6 @@ pub fn head_handle(canvas: &mut CanvasParts) { 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| @@ -109,35 +139,26 @@ pub fn head_handle(canvas: &mut CanvasParts) { .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, + let path_data = recursive_colision_check(eveluation_fn, &parts_in_sight, fov, &head.position, &creature.curent_direction , sight_radius as u8, 0); // 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); + let (colision, opt_foreign_changes) = colision_fn(&parts_in_sight, &(path_data.0 as u16, path_data.1 as u16), &cloned_canvas); + match opt_foreign_changes { + Some(mut x) => foreign_changes.append(&mut x), + None => (), } + // 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); + creature.move_to((path_data.0 as u16, path_data.1 as u16), path_data.2, colision); + cloned_canvas.alive[index] = creature.clone(); // Update cloned canvass // 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 { + if element.position == (path_data.0 as u16, path_data.1 as u16) && element.element == Element::Food { to_remove.push(index); } } @@ -146,5 +167,5 @@ pub fn head_handle(canvas: &mut CanvasParts) { to_remove.iter().for_each(|x| {canvas.interactable.remove(*x);}); } } - wesp_kills.iter().for_each(|x| {canvas.alive[*x].killed = true;}); + foreign_changes.iter().for_each(|x| {canvas.alive[*x].killed = true;}); }