Made MAX_THREADS a static, reduced spawnrate of floating snakes, leanup head handler

This commit is contained in:
someone 2024-03-09 23:07:04 +01:00
parent c10941b102
commit a184fcc532
3 changed files with 61 additions and 32 deletions

View File

@ -2,7 +2,7 @@
pub use std; // for documentation purposes pub use std; // for documentation purposes
use std::io::{self, Write}; use std::io::{self, Write};
use components::CanvasParts; 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; use lazy_static::lazy_static;
//lazy_static is ok, mutability not needed //lazy_static is ok, mutability not needed
use rand::{thread_rng, Rng}; 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() { 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), queue!(stdout, MoveTo(part.position.0, part.position.1),
PrintStyledContent(ELEMENT_VISUALS[&part.element].to_string().with(part.color))).unwrap(); 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 canvas: CanvasParts = create_canvas();
let mut state = components::CanvasState { iterations: 0, cleared_coords: Vec::new() }; //food_rate: 0 let mut state = components::CanvasState { iterations: 0, cleared_coords: Vec::new() }; //food_rate: 0
draw_canvas(&canvas, &mut state.cleared_coords); draw_canvas(&canvas, &mut state.cleared_coords);
let mut last_refresh = Instant::now();
loop { loop {
let now = Instant::now(); let now = Instant::now();
pathfinder::head_handle(&mut canvas); pathfinder::head_handle(&mut canvas);
@ -103,10 +107,14 @@ fn main() {
state.iterations += 1; state.iterations += 1;
let elapsed = now.elapsed(); let elapsed = now.elapsed();
if elapsed < Duration::from_millis(50) { if elapsed < Duration::from_millis(0) {
sleep(Duration::from_millis(50) - elapsed); 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();
} }
} }
} }

View File

@ -47,8 +47,8 @@ pub fn spawner_handle(canvas: &mut CanvasParts) {
if !check_collision(&canvas.environment, (pos.0, pos.1)) { if !check_collision(&canvas.environment, (pos.0, pos.1)) {
let color = get_unused_color(&canvas.alive); let color = get_unused_color(&canvas.alive);
match x % 10 { match x % 10 {
0 | 1 => canvas.add_creature((pos.0, pos.1), color, pos.2, Species::DetachedSnake, canvas.interactable[index].position), 0 => 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), 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.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 }; canvas.interactable[index].color = Color::Rgb { r: 10, g: 100, b: 10 };

View File

@ -3,8 +3,11 @@ use crate::components::{DirectionX, DirectionY, Element, Part, Species, directio
use crate::CanvasParts; use crate::CanvasParts;
use std::thread; use std::thread;
use std::sync::mpsc; 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 { 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<Part>, position: &(u16, u16), canvas: &CanvasParts) -> (bool, Option<Vec<usize>>) {
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<Part>, position: &(u16, u16), canvas: &CanvasParts) -> (bool, Option<Vec<usize>>) {
let mut wesp_kills: Vec<usize> = 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<Part>, fov: isize, position: &(u16, u16), fn recursive_colision_check(path_to_match: fn(Element) -> i64, parts_in_sight: &Vec<Part>, fov: isize, position: &(u16, u16),
direction: &(DirectionX, DirectionY), iterations_left: u8, iterations_passed: u32) -> (i32, i32, (DirectionX, DirectionY), i64){ 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 // 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 { if iterations_left > 0 {
let sender = sender.clone(); let sender = sender.clone();
let parts_in_sight = parts_in_sight.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 || { 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; 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(); 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) { pub fn head_handle(canvas: &mut CanvasParts) {
//Todo: Reomve or improve threading in this function!! //Todo: Reomve or improve threading in this function!!
// Find all elements that head can see // Find all elements that head can see
let mut wesp_kills: Vec<usize> = Vec::new(); let mut foreign_changes: Vec<usize> = Vec::new();
let cloned_canvas = canvas.clone(); let mut cloned_canvas = canvas.clone();
for creature in canvas.alive.iter_mut() { for (index, creature) in canvas.alive.iter_mut().enumerate() {
let (fov, speed, sight_radius): (isize, u8, i32) = match creature.species { let (fov, speed, sight_radius): (isize, u8, i32) = match creature.species {
Species::DetachedSnake => (2, 1, 4), Species::DetachedSnake => (2, 1, 4),
Species::Wesp => (1, 2, 4), Species::Wesp => (1, 2, 4),
_ => (1, 1, 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<Part>, &(u16, u16), &CanvasParts) -> (bool, Option<_>)
),
Species::Wesp => (
wesp_path_match as fn(Element) -> i64,
wesp_colision_matcher as fn(&Vec<Part>, &(u16, u16), &CanvasParts) -> (bool, Option<_>)
),
};
for _ in 0..speed { for _ in 0..speed {
let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead || elem.element == Element::WespHead).next(); 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; continue;
} }
let head = head.unwrap().clone(); // Clone the head to avoid borrowing issues let head = head.unwrap().clone(); // Clone the head to avoid borrowing issues
// Concartination of all parts in sight // Concartination of all parts in sight
let parts_in_sight: Vec<Part> = cloned_canvas.unify_elements().iter() let parts_in_sight: Vec<Part> = cloned_canvas.unify_elements().iter()
.filter(|elem| .filter(|elem|
@ -109,35 +139,26 @@ pub fn head_handle(canvas: &mut CanvasParts) {
.map(|elem| **elem) .map(|elem| **elem)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
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); &head.position, &creature.curent_direction , sight_radius as u8, 0);
// Check colisions of new position // Check colisions of new position
let mut colision = false; let (colision, opt_foreign_changes) = colision_fn(&parts_in_sight, &(path_data.0 as u16, path_data.1 as u16), &cloned_canvas);
if creature.species == Species::Wesp { match opt_foreign_changes {
for part in parts_in_sight.iter() { Some(mut x) => foreign_changes.append(&mut x),
if part.position == (res.0 as u16, res.1 as u16) && part.element == Element::BodyPartHead{ None => (),
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 // 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 // Clean up food
let mut to_remove: Vec<usize> = Vec::new(); let mut to_remove: Vec<usize> = Vec::new();
// Iterate over a mutable reference to the canvas vector // Iterate over a mutable reference to the canvas vector
for (index, element) in canvas.interactable.iter_mut().enumerate() { 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); 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);}); 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;});
} }