reorganised internal data structure of canvas elements

This commit is contained in:
someone 2024-03-06 00:33:07 +01:00
parent 5b86d43bfe
commit 54b555fb8d
4 changed files with 237 additions and 204 deletions

1
.rustc_info.json Normal file
View File

@ -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":{}}

View File

@ -1,91 +1,106 @@
use crossterm::style::Color; use crossterm::style::Color;
use crate::TERM_SIZE; use crate::TERM_SIZE;
use rand::Error; use crate::part_handler;
pub(crate) struct Element { #[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub(crate) visual: char, pub enum Direction {
pub(crate) e_type: &'static str, Up,
Down,
Left,
Right,
None,
} }
impl Element { #[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub(crate) fn new(name: &str) -> Result<Element, Error> {
match name { pub enum Element {
"wall" => Ok(Element { visual: '∩', e_type: "wall" }), Wall,
"spawn" => Ok(Element { visual: '@', e_type: "spawner" }), Spawn,
"body_part_v" => Ok(Element { visual: '|', e_type: "alive" }), BodyPartVert,
"body_part_h" => Ok(Element { visual: '-', e_type: "alive" }), BodyPartHori,
"body_part_l" => Ok(Element { visual: '/', e_type: "alive" }), BodyPartLeftLean,
"body_part_r" => Ok(Element { visual: '\\', e_type: "alive" }), BodyPartRightLean,
"food" => Ok(Element { visual: '#', e_type: "food" }), Food,
"body_part_head" => Ok(Element { visual: '█', e_type: "alive" }), BodyPartHead,
_ => Err(Error::new("Invalid element")),
}
}
pub(crate) fn copy(&self) -> Element {
Element {
visual: self.visual,
e_type: self.e_type,
}
}
} }
#[derive(Copy, Clone)]
pub struct Part { pub struct Part {
pub(crate) element: Element, pub(crate) element: Element,
pub(crate) position: (u16, u16), pub(crate) position: (u16, u16),
pub(crate) color: Color, pub(crate) color: Color,
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<Part,Error> { #[derive(Clone)]
let mut in_invalide:bool = false;
if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 { pub(crate) struct Creature {
// < 0 not needet because u16 is always positive pub(crate) parts: Vec<Part>,
in_invalide = true; pub(crate) color: Color,
} pub(crate) curent_direction: (Direction, Direction),
Ok(Part { pub(crate) spawner_at: (u16, u16),
element: Element::new(element)?, pub(crate) killed: bool,
position, }
color: color,
direction: String::from("_ _"), impl Creature {
killed: in_invalide, 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;
pub(crate) fn copy(&self) -> Part { self.curent_direction = moved_in_direction;
Part { if new_position.0 > TERM_SIZE.0 || new_position.1 > TERM_SIZE.1 || colision {
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 {
self.killed = true; 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<Creature>,
pub(crate) environment: Vec<Part>,
pub(crate) interactable: Vec<Part>,
}
impl CanvasParts{
pub(crate) fn add_element(&mut self, new_element: Element, position: (u16, u16), color: Option<Color>,
creature_index: Option<usize>){
if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 {
return;
} }
}
pub(crate) struct CanvasState { match new_element {
pub(crate) canvas: Vec<Part>, Element::Wall => self.environment.push(Part { element: new_element, position, color: color.unwrap() }),
pub(crate) colors: i32, Element::Spawn | Element::Food => self.interactable.push(Part { element: new_element, position, color: color.unwrap() }),
pub(crate) iterations: u128, Element::BodyPartHead | Element::BodyPartVert | Element::BodyPartHori | Element::BodyPartLeftLean | Element::BodyPartRightLean => {
pub(crate) food_rate: u8, if let Some(index) = creature_index {
} let color = self.alive[index].color;
self.alive[index].parts.push(Part { element: new_element, position, color: color });
impl CanvasState { } else {
pub(crate) fn new(canvas: Vec<Part>) -> CanvasState { panic!("No creature index provided");
CanvasState { }
canvas: canvas,
colors: 0,
iterations: 0,
food_rate: 10,
} }
} }
} }
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 struct CanvasState {
pub(crate) colors: i32,
pub(crate) iterations: u128,
//pub(crate) food_rate: u8,
}

View File

@ -1,12 +1,14 @@
#[doc(inline)] #[doc(inline)]
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 crossterm::{cursor::MoveTo, queue, QueueableCommand, style::{PrintStyledContent, Stylize, Color}, terminal::enable_raw_mode}; use crossterm::{cursor::MoveTo, queue, QueueableCommand, style::{PrintStyledContent, Stylize, Color}, terminal::enable_raw_mode};
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};
use std::time::Duration; use std::time::Duration;
use std::thread::sleep; use std::thread::sleep;
use std::collections::HashMap;
mod part_handler; mod part_handler;
mod components; 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")); static ref TERM_SIZE: (u16, u16) = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size"));
} }
lazy_static!{
static ref ELEMENT_VISUALS: HashMap<components::Element, char> = 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<components::Part>{
fn create_canvas() -> CanvasParts{
let mut rng = thread_rng(); let mut rng = thread_rng();
let mut canvas: Vec<components::Part> = 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 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 { for y in 0..TERM_SIZE.1 {
if y == 0 || y == TERM_SIZE.1 - 1 { if y == 0 || y == TERM_SIZE.1 - 1 {
for x in 0..TERM_SIZE.0 { 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.add_element(components::Element::Wall, (x, y), Some(wall_color), None);
canvas.push(part);
} }
} else { } else {
canvas.push(components::Part::new("wall", (0, 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.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, (0, y), Some(wall_color), None); // Use array indexing instead of tuple indexing
} }
} }
for i in 0..3{ for _ 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 // 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 canvas // Return the canvas vector
} }
fn draw_canvas(canvas: &Vec<components::Part>) { fn draw_canvas(canvas: &CanvasParts) {
let mut stdout = io::stdout(); let mut stdout = io::stdout();
stdout.queue(crossterm::terminal::Clear(crossterm::terminal::ClearType::All)).unwrap(); 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), 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(); stdout.flush().unwrap();
} }
fn main() { fn main() {
// Prepare the terminal
let _ = enable_raw_mode(); let _ = enable_raw_mode();
let mut stdout = io::stdout(); let mut stdout = io::stdout();
stdout.queue(crossterm::cursor::Hide).unwrap(); stdout.queue(crossterm::cursor::Hide).unwrap();
stdout.flush().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 { loop {
part_handler::head_handle(&mut state.canvas, &mut state.colors); part_handler::head_handle(&mut canvas, &mut state.colors);
part_handler::spawner_handle(&mut state.canvas, &mut state.colors); part_handler::spawner_handle(&mut canvas, &mut state.colors);
part_handler::handle_killed(&mut state.canvas); part_handler::handle_killed(&mut canvas.alive);
part_handler::spawn_food(&mut state.canvas); part_handler::spawn_food(&mut canvas);
state.canvas.sort_by_key(|part| (part.position.1, part.position.0));
draw_canvas(&state.canvas); draw_canvas(&canvas);
state.iterations += 1; state.iterations += 1;
sleep(Duration::from_millis(32)); sleep(Duration::from_millis(32));
} }

View File

@ -2,118 +2,117 @@
use crossterm::style::Color; use crossterm::style::Color;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use rand::Rng; 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; const SIGHT_RADIUS: u16 = 5;
lazy_static! { lazy_static! {
static ref CHECK_DIRECTIONS: HashMap<&'static str, ([&'static str; 3], &'static str ), > = HashMap::from([ pub static ref CHECK_DIRECTIONS: HashMap<(Direction, Direction), (Vec<Vec<Direction>>, Element)> = HashMap::from([
("t _", (["t _", "t r", "t l"], "body_part_h")), ((Direction::Up, Direction::None), (vec![vec![Direction::Up, Direction::None], vec![Direction::Up, Direction::Right], vec![Direction::Up, Direction::Left]], Element::BodyPartHori)),
("t r", (["t r", "t _", "_ r"], "body_part_l")), ((Direction::Up, Direction::Right), (vec![vec![Direction::Up, Direction::Right], vec![Direction::Up, Direction::None], vec![Direction::None, Direction::Right]], Element::BodyPartLeftLean)),
("t l", (["t l", "t _", "_ l"], "body_part_r")), ((Direction::Up, Direction::Left), (vec![vec![Direction::Up, Direction::Left], vec![Direction::Up, Direction::None], vec![Direction::None, Direction::Left]], Element::BodyPartRightLean)),
("b _", (["b _", "b r", "b l"], "body_part_h")), ((Direction::Down, Direction::None), (vec![vec![Direction::Down, Direction::None], vec![Direction::Down, Direction::Right], vec![Direction::Down, Direction::Left]], Element::BodyPartHori)),
("b r", (["b r", "b _", "_ r"], "body_part_r")), ((Direction::Down, Direction::Right), (vec![vec![Direction::Down, Direction::Right], vec![Direction::Down, Direction::None], vec![Direction::None, Direction::Right]], Element::BodyPartRightLean)),
("b l", (["b l", "b _", "_ l"], "body_part_l")), ((Direction::Down, Direction::Left), (vec![vec![Direction::Down, Direction::Left], vec![Direction::Down, Direction::None], vec![Direction::None, Direction::Left]], Element::BodyPartLeftLean)),
("_ r", (["_ r", "t r", "b r"], "body_part_v")), ((Direction::None, Direction::Right), (vec![vec![Direction::None, Direction::Right], vec![Direction::Up, Direction::Right], vec![Direction::Down, Direction::Right]], Element::BodyPartVert)),
("_ l", (["_ l", "t l", "b l"], "body_part_v")), ((Direction::None, Direction::Left), (vec![vec![Direction::None, Direction::Left], vec![Direction::Up, Direction::Left], vec![Direction::Down, Direction::Left]], Element::BodyPartVert)),
]); ]);
} }
lazy_static!{ lazy_static!{
static ref DIRECTIONS: HashMap<&'static str, i32> = HashMap::from([ static ref DIRECTIONS: HashMap<components::Direction, i32> = HashMap::from([
("t", -1), (Direction::Up, -1),
("b", 1), (Direction::Down, 1),
("r", 1), (Direction::Right, 1),
("l", -1), (Direction::Left, -1),
("_", 0) (Direction::None, 0)
]); ]);
} }
fn check_collision(canvas: &Vec<components::Part>, position: (u16, u16)) -> bool { fn check_collision(canvas: &Vec<Part>, position: (u16, u16)) -> bool {
canvas.iter().filter(|elem| elem.position == position).count() > 0 canvas.iter().filter(|elem| elem.position == position).count() > 0
} }
fn get_unused_color(canvas: &Vec<components::Part>) -> Color { fn get_unused_color(creatures: &Vec<Creature>) -> Color {
let mut color: Color = Color::Rgb { r: 0, g: 0, b: 0 }; let mut color: Color = Color::Rgb { r: 0, g: 0, b: 0 };
let mut color_used: bool = true; let mut color_used: bool = true;
let mut rand_gen = rand::thread_rng(); let mut rand_gen = rand::thread_rng();
while color_used { 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 = 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 color
} }
pub fn spawner_handle(canvas: &mut Vec<components::Part>, heads: &i32) { pub fn spawner_handle(canvas: &mut CanvasParts, heads: &i32) {
let inactive_spawns: Vec<usize> = canvas.iter() let inactive_spawns: Vec<usize> = canvas.interactable.iter()
.enumerate() .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) .map(|(index, _)| index)
.collect(); .collect();
if *heads < inactive_spawns.len() as i32{ 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 // Collect the indices of active spawns
let active_spawn_indices: Vec<usize> = canvas let active_spawn_indices: Vec<usize> = canvas.interactable.iter_mut()
.iter_mut()
.enumerate() .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) .map(|(index, _)| index)
.collect(); .collect();
let mut rand_gen = rand::thread_rng(); let mut rand_gen = rand::thread_rng();
//let enviorment = canvas.environment.clone();
for &index in &active_spawn_indices { for &index in &active_spawn_indices {
let x: u8 = rand_gen.gen_range(0..100); let x: u8 = rand_gen.gen_range(0..100);
if rand_gen.gen_range(0..100) < 10 { 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: up 1: right 2: down 3: left
0 => (canvas[index].position.0, canvas[index].position.1 - 1, "t _"), 0 => (canvas.interactable[index].position.0, canvas.interactable[index].position.1 - 1, (Direction::Up, Direction::None)),
1 => (canvas[index].position.0 + 1, canvas[index].position.1, "_ r"), 1 => (canvas.interactable[index].position.0 + 1, canvas.interactable[index].position.1, (Direction::None, Direction::Right)),
2 => (canvas[index].position.0, canvas[index].position.1 + 1, "b _"), 2 => (canvas.interactable[index].position.0, canvas.interactable[index].position.1 + 1, (Direction::Down, Direction::None)),
3 => (canvas[index].position.0 - 1, canvas[index].position.1, "_ l"), 3 => (canvas.interactable[index].position.0 - 1, canvas.interactable[index].position.1, (Direction::None, Direction::Left)),
_ => (1, 1, "b _"), _ => (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()); if !check_collision(&canvas.environment, (pos.0, pos.1)) {
canvas.last_mut().unwrap().direction = pos.2.to_string(); canvas.add_creature((pos.0, pos.1), get_unused_color(&canvas.alive), pos.2, canvas.interactable[index].position);
canvas[index].color = Color::Rgb { r: 10, g: 100, b: 10 }; canvas.interactable[index].color = Color::Rgb { r: 10, g: 100, b: 10 };
} }
} }
} }
} }
fn recursive_colision_check(color: &Color, parts_in_sight: &Vec<Part>, position: &(u16, u16), direction: &str, iterations_left: u8) -> (i32, i32, &'static str , i64){ fn recursive_colision_check(color: &Color, parts_in_sight: &Vec<Part>, position: &(u16, u16),
let mut dyn_pos_res: Vec<(i32, i32, &str , i64)> = Vec::new(); 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) // 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() { for direction_to_check in CHECK_DIRECTIONS[&direction].0.iter() {
let x = direction_to_check.split_whitespace().take(2).collect::<Vec<&str>>(); let (dir_x, dir_y): (Direction, Direction) = (direction_to_check[0], direction_to_check[1]);
dyn_pos_res.push((i32::from(position.0) + DIRECTIONS[x[0]], i32::from(position.1) + DIRECTIONS[x[1]], direction_to_check , 0)); 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 // 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() { 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 { for part in parts_in_sight {
if part.position == (*x as u16, *y as u16) { if part.position == (*x as u16, *y as u16) {
//When element in sight, part is element in sight //When element in sight, part is element in sight
if part.element.e_type == "alive" {//&& part.color != *color *val = match part.element {
*val -= 100; Element::Wall => -1000,
} Element::BodyPartHori | Element::BodyPartVert |
else if part.element.e_type == "food" { Element::BodyPartLeftLean | Element::BodyPartRightLean | Element::BodyPartHead => *val -1000,
*val += 100; Element::Food => 100,
} _ => 0,
else if part.element.e_type == "wall" { }
*val -= 10000;
}
} }
} }
if iterations_left > 0 { if iterations_left > 0 {
@ -129,80 +128,77 @@ fn recursive_colision_check(color: &Color, parts_in_sight: &Vec<Part>, position:
b.2.cmp(&a.2) compares the third element of b and a (in reverse order because we want the highest element first). */ 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<components::Part>, head_count: &mut i32) { pub fn head_handle(canvas: &mut CanvasParts, head_count: &mut i32) {
// Find all elements that head can see // Find all elements that head can see
let mut heads = 0; *head_count = canvas.alive.len() as i32;
for head_index in 0..canvas.len() { let unified_canvas = canvas.clone();
if canvas[head_index].element.visual == '█' { for creature in canvas.alive.iter_mut() {
// Keep track on how many heads are there let head = creature.parts.iter().filter(|elem| elem.element == Element::BodyPartHead).next();
heads += 1; if head.is_none() {
continue;
let parts_in_sight: Vec<components::Part> = 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<usize> = 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);});
} }
} let head = head.unwrap();
*head_count = heads;
}
pub fn handle_killed(canvas: &mut Vec<components::Part>) {
let to_remove: Vec<usize> = canvas.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect(); // Concartination of all parts in sight
for index in &to_remove { let parts_in_sight: Vec<Part> = unified_canvas.unify_elements().iter()
for mod_y in -1..=1i32 { .filter(|elem|
for mod_x in -1..=1i32 { (elem.position.0 as i64 - head.position.0 as i64).pow(2) +
canvas.iter() (elem.position.1 as i64 - head.position.1 as i64).pow(2) <= SIGHT_RADIUS.pow(2) as i64)
.enumerate() .map(|elem| **elem)
.filter(|(_, elem)| elem.color == canvas[*index].color) .collect::<Vec<_>>();
.filter(|(_, elem)| elem.position == ((canvas[*index].position.0.try_into().unwrap_or_else(|_| 2) + mod_x).try_into().unwrap_or_else(|_| 0), let res: (i32, i32, (Direction, Direction), i64) = recursive_colision_check(&head.color, &parts_in_sight,
(canvas[*index].position.1.try_into().unwrap_or_else(|_| 2) + mod_y).try_into().unwrap_or_else(|_| 0))) &head.position, &creature.curent_direction , 3);
.map(|(index, _)| index)
.collect::<Vec<usize>>().iter().for_each(|x| canvas[*x].killed = true); // 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<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);
} }
} }
}
// Must be hear else the indices will be wrong // Remove elements from the canvas vector based on the condition
for index in to_remove.iter().rev() { to_remove.iter().for_each(|x| {canvas.interactable.remove(*x);});
canvas.remove(*index);
} }
} }
pub fn spawn_food(canvas: &mut Vec<components::Part>) {
pub fn handle_killed(creatures: &mut Vec<Creature>) {
let killed_creatures: Vec<usize> = creatures.iter().enumerate().filter(|(_, elem)| elem.killed).map(|(index, _)| index).collect::<Vec<_>>();
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(); let mut rng = rand::thread_rng();
if rng.gen_bool(0.2){ 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)); 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)); 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);
} }
} }