Added cl-args, exit fn, key handeling

This commit is contained in:
someone 2024-03-10 18:20:18 +01:00
parent 9fa6848aed
commit 7b608125ea
4 changed files with 139 additions and 54 deletions

View File

@ -2,7 +2,6 @@
use crossterm::style::Color; use crossterm::style::Color;
use crate::TERM_SIZE; use crate::TERM_SIZE;
#[derive(PartialEq, Clone, Hash, Eq, Copy)] #[derive(PartialEq, Clone, Hash, Eq, Copy)]
@ -112,7 +111,7 @@ pub(crate) struct Creature {
impl Creature { impl Creature {
pub(crate) fn move_to(&mut self, new_position: (u16, u16), moved_in_direction: (DirectionX, DirectionY), colision: bool) { pub(crate) fn move_to(&mut self, new_position: (u16, u16), moved_in_direction: (DirectionX, DirectionY), colision: bool) {
if new_position.0 > TERM_SIZE.0 || new_position.0 <= 0 || new_position.1 > TERM_SIZE.1 || new_position.1 <= 0 || colision { if new_position.0 > TERM_SIZE.read().unwrap().0 || new_position.0 <= 0 || new_position.1 > TERM_SIZE.read().unwrap().1 || new_position.1 <= 0 || colision {
self.killed = true; self.killed = true;
return; return;
} }
@ -150,7 +149,7 @@ pub(crate) struct CanvasParts {
impl CanvasParts{ impl CanvasParts{
pub(crate) fn add_element(&mut self, new_element: Element, position: (u16, u16), color: Option<Color>, pub(crate) fn add_element(&mut self, new_element: Element, position: (u16, u16), color: Option<Color>,
creature_index: Option<usize>){ creature_index: Option<usize>){
if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 { if position.0 > TERM_SIZE.read().unwrap().0 || position.1 > TERM_SIZE.read().unwrap().1 {
return; return;
} }

View File

@ -1,8 +1,8 @@
#[doc(inline)] #[doc(inline)]
pub use std; // for documentation purposes pub use std; // for documentation purposes
use std::io::{self, Write}; use std::{char, f32::consts::E, io::{self, Chain, Write}};
use components::CanvasParts; use components::CanvasParts;
use crossterm::{cursor::{self, MoveTo}, execute, queue, style::{Color, PrintStyledContent, Stylize}, terminal::EnableLineWrap, QueueableCommand}; use crossterm::{cursor::MoveTo, event::{poll, read, Event, KeyCode, KeyEvent, KeyModifiers}, execute, queue, style::{Color, PrintStyledContent, Stylize}, terminal::{disable_raw_mode, enable_raw_mode, DisableLineWrap, 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};
@ -10,16 +10,27 @@ use std::time::Duration;
use std::thread::sleep; use std::thread::sleep;
use std::time::Instant; use std::time::Instant;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::RwLock; // RwLock is ok, mutability not needed
use std::env::args;
use std::process::exit;
mod part_handler; mod part_handler;
mod components; mod components;
mod pathfinder; mod pathfinder;
const SPAWNERS:u16 = 3;
lazy_static!{static ref MAX_THREADS: RwLock<u32> = RwLock::new(0);}
lazy_static!{static ref SPAWNERS: RwLock<u16> = RwLock::new(0);}
lazy_static!{static ref RESTART: RwLock<bool> = RwLock::new(false);}
lazy_static!{static ref SHOW_STATS: RwLock<bool> = RwLock::new(false);}
lazy_static!{static ref MIN_DELAY: RwLock<u64> = RwLock::new(17);}
lazy_static! { lazy_static! {
static ref TERM_SIZE: (u16, u16) = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size")); static ref TERM_SIZE: RwLock<(u16, u16)> = RwLock::new((0, 0));
} }
lazy_static!{ lazy_static!{
@ -36,6 +47,69 @@ lazy_static!{
(components::Element::WespBody, '•'), (components::Element::WespBody, '•'),
]); ]);
} }
fn help_message() {
println!("Usage: dance_of_lines [options]
-i: Show stats
-s <int>: Set spawner count
-d <int>: Set minimum delay between frames in milliseconds
-t <int> <int>: Set terminal size in columns and rows
-p <int>: Set maximum thread count
-h, --help: Show this message
");
exit(0);
}
fn set_runtime_constants(cl_args: std::env::Args) {
let mut args = cl_args.skip(1);
let mut stats = false;
let mut min_delay = 17;
let mut max_term_size = (0, 0);
let mut spawners = 4;
let mut max_threads = 0;
while let Some(arg) = args.next() {
match arg.as_str() {
"-i" => stats = true,
"-s" => spawners = args.next().unwrap().parse().unwrap_or_else(|_| panic!("Invalid spawner count")),
"-d" => min_delay = args.next().unwrap().parse().unwrap_or_else(|_| panic!("Invalid delay")),
"-t" => max_term_size = (args.next().unwrap().parse().unwrap_or_else(|_| panic!("Invalid terminal size")), args.next().unwrap().parse().unwrap_or_else(|_| panic!("Invalid terminal size"))),
"-p" => max_threads = args.next().unwrap().parse().unwrap_or_else(|_| panic!("Invalid thread count")),
"-h" | "--help" => help_message(),
_ => panic!("Invalid argument --help for help"),
}
}
if max_term_size.0 > TERM_SIZE.read().unwrap().0 || max_term_size.1 > TERM_SIZE.read().unwrap().1 {
panic!("Terminal size too large");
} else if max_term_size == (0, 0) {
max_term_size = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size"));
}
*MAX_THREADS.write().unwrap() = max_threads;
*SPAWNERS.write().unwrap() = spawners;
*SHOW_STATS.write().unwrap() = stats;
*MIN_DELAY.write().unwrap() = min_delay;
*TERM_SIZE.write().unwrap() = max_term_size;
}
fn exit_handler() {
let _ = disable_raw_mode();
let mut stdout = io::stdout();
stdout.queue(crossterm::cursor::Show).unwrap();
stdout.queue(DisableLineWrap).unwrap();
stdout.flush().unwrap();
exit(0);
}
fn handle_kb_input() {
if poll(Duration::from_millis(0)).unwrap() {
match read().unwrap() {
Event::Key(KeyEvent{code: KeyCode::Char('c'), modifiers: KeyModifiers::CONTROL, kind: _, state: _}) => exit_handler(),
Event::Key(KeyEvent{code: KeyCode::Char('s'), modifiers: _, kind: _, state: _}) => {let curent_state = *SHOW_STATS.read().unwrap(); *SHOW_STATS.write().unwrap() = !curent_state;},
Event::Key(KeyEvent{code: KeyCode::Char('r'), modifiers: _, kind: _, state: _}) => {*RESTART.write().unwrap() = true;},
Event::Resize(_,_) => {*RESTART.write().unwrap() = true;},
_ => (),
}
}
}
fn create_canvas() -> CanvasParts{ fn create_canvas() -> CanvasParts{
@ -43,24 +117,25 @@ fn create_canvas() -> CanvasParts{
let mut canvas = CanvasParts {alive: Vec::new(), environment: Vec::new(), interactable: 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.read().unwrap().1 {
if y == 0 || y == TERM_SIZE.1 - 1 { if y == 0 || y == TERM_SIZE.read().unwrap().1 - 1 {
for x in 0..TERM_SIZE.0 { for x in 0..TERM_SIZE.read().unwrap().0 {
canvas.add_element(components::Element::Wall, (x, y), Some(wall_color), None); canvas.add_element(components::Element::Wall, (x, y), Some(wall_color), None);
} }
} else { } else {
canvas.add_element(components::Element::Wall, (TERM_SIZE.0 - 1, y), Some(wall_color), None); // Use array indexing instead of tuple indexing canvas.add_element(components::Element::Wall, (TERM_SIZE.read().unwrap().0 - 1, y), Some(wall_color), None); // 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 canvas.add_element(components::Element::Wall, (0, y), Some(wall_color), None); // Use array indexing instead of tuple indexing
} }
} }
let spawner_ranges = (TERM_SIZE.0-1) / SPAWNERS as u16; let spawner_ranges = (TERM_SIZE.read().unwrap().0-1) / *SPAWNERS.read().unwrap() as u16;
for i in 0..SPAWNERS{ for i in 0..*SPAWNERS.read().unwrap(){
// Use array indexing instead of tuple indexing // Use array indexing instead of tuple indexing
canvas.add_element(components::Element::Spawn, (rng.gen_range((spawner_ranges*i)..spawner_ranges*(i+1)), rng.gen_range(1..TERM_SIZE.1-1)), Some(Color::Rgb { r: 10, g: 255, b: 10 }), None); canvas.add_element(components::Element::Spawn, (rng.gen_range((spawner_ranges*i)..spawner_ranges*(i+1)), rng.gen_range(1..TERM_SIZE.read().unwrap().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: &CanvasParts, cleared_coords: &mut Vec<(u16, u16)>) { fn draw_canvas(canvas: &CanvasParts, cleared_coords: &mut Vec<(u16, u16)>) {
let mut stdout = io::stdout(); let mut stdout = io::stdout();
@ -72,7 +147,7 @@ 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 { if *SHOW_STATS.read().unwrap() && part.position.1 == TERM_SIZE.read().unwrap().1 - 1 {
continue; continue;
} }
queue!(stdout, MoveTo(part.position.0, part.position.1), queue!(stdout, MoveTo(part.position.0, part.position.1),
@ -84,7 +159,13 @@ fn draw_canvas(canvas: &CanvasParts, cleared_coords: &mut Vec<(u16, u16)>) {
} }
fn main() { fn main() {
set_runtime_constants(args());
loop {
if !args().any(|arg| arg == "-t"){
*TERM_SIZE.write().unwrap() = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size"));
}
// Prepare the terminal // Prepare the terminal
let _ = enable_raw_mode();
execute!(io::stdout(), EnableLineWrap).unwrap(); execute!(io::stdout(), EnableLineWrap).unwrap();
let mut stdout = io::stdout(); let mut stdout = io::stdout();
stdout.queue(crossterm::cursor::Hide).unwrap(); stdout.queue(crossterm::cursor::Hide).unwrap();
@ -96,7 +177,10 @@ fn main() {
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(); let mut last_refresh = Instant::now();
loop {
*RESTART.write().unwrap() = false;
while !*RESTART.read().unwrap() {
let now = Instant::now(); let now = Instant::now();
pathfinder::head_handle(&mut canvas); pathfinder::head_handle(&mut canvas);
part_handler::spawner_handle(&mut canvas); part_handler::spawner_handle(&mut canvas);
@ -106,15 +190,23 @@ fn main() {
draw_canvas(&canvas, &mut state.cleared_coords); draw_canvas(&canvas, &mut state.cleared_coords);
state.iterations += 1; state.iterations += 1;
handle_kb_input();
let elapsed = now.elapsed(); let elapsed = now.elapsed();
if elapsed < Duration::from_millis(0) { if elapsed < Duration::from_millis(*MIN_DELAY.read().unwrap()) {
sleep(Duration::from_millis(0) - elapsed); sleep(Duration::from_millis(*MIN_DELAY.read().unwrap()) - elapsed);
} }
if true && last_refresh.elapsed() > Duration::from_secs_f64(0.5) { if *SHOW_STATS.read().unwrap() && 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(); let mut stats_string = format!("Iterations:{}|FPS:{:.2?}|Creatures:{}|<S>:stats|<R>:restart|<C-^>:exit",
state.iterations, 1000.0 / (elapsed.as_secs_f64() + *MIN_DELAY.read().unwrap() as f64), canvas.alive.len());
stats_string.truncate(TERM_SIZE.read().unwrap().0 as usize - 1);
stats_string = format!("{}{}", &stats_string, ELEMENT_VISUALS[&components::Element::Wall].to_string().repeat((TERM_SIZE.read().unwrap().0 - stats_string.len() as u16) as usize));
queue!(stdout, MoveTo(0, TERM_SIZE.read().unwrap().1), PrintStyledContent(stats_string.with(Color::Rgb { r: 255, g: 60, b: 70 }))).unwrap();
stdout.flush().unwrap(); stdout.flush().unwrap();
last_refresh = Instant::now(); last_refresh = Instant::now();
} }
} }
}
} }

View File

@ -103,9 +103,9 @@ pub fn spawn_food(canvas: &mut CanvasParts) {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
if rng.gen_bool(0.30){ if rng.gen_bool(0.30){
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.read().unwrap().0 - 1), rng.gen_range(1..crate::TERM_SIZE.read().unwrap().1 - 1));
while check_collision(&canvas.unify_elements().iter().map(|part| **part).collect(), 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.read().unwrap().0 - 1), rng.gen_range(1..crate::TERM_SIZE.read().unwrap().1 - 1));
} }
canvas.add_element(Element::Food, pos, Some(get_unused_color(&canvas.alive)), None); canvas.add_element(Element::Food, pos, Some(get_unused_color(&canvas.alive)), None);
} }

View File

@ -3,12 +3,6 @@ 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;
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 {
match elem { match elem {
@ -29,7 +23,7 @@ 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>>) { fn snake_colision_matcher(parts_in_sight: &Vec<Part>, position: &(u16, u16), _: &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); let colision = parts_in_sight.iter().any(|elem| elem.position == (position.0 as u16, position.1 as u16) && elem.element != Element::Food);
(colision, None) (colision, None)
} }
@ -76,7 +70,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 *MAX_THREADS != 0 && ((dyn_pos_res.len() as i32).pow(iterations_passed) as u32) < *MAX_THREADS { // Test for 0 to avoid calculation time if *crate::MAX_THREADS.read().unwrap() != 0 && ((dyn_pos_res.len() as i32).pow(iterations_passed) as u32) < *crate::MAX_THREADS.read().unwrap() { // 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();