solit path_handler in pathfinder, improved wesps

This commit is contained in:
someone 2024-03-09 19:31:37 +01:00
parent 9c2206c5d4
commit 47519bea20
4 changed files with 187 additions and 184 deletions

View File

@ -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});
}

View File

@ -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);
}
}
}

View File

@ -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<components::Species, u8> = 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<Part>, 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<Part>, 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<thread::JoinHandle<()>> = 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<usize> = 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<Part> = 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::<Vec<_>>();
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<usize> = 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<Creature>, cleared_coords: &mut Vec<(u16, u16)>) {
//let killed_creatures: Vec<usize> = creatures.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect::<Vec<_>>();
@ -238,7 +77,7 @@ pub fn handle_killed(creatures: &mut Vec<Creature>, 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

143
src/pathfinder.rs Normal file
View File

@ -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<Part>, 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<thread::JoinHandle<()>> = 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<usize> = 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<Part> = 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::<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,
&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<usize> = 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;});
}