added spawner, todo: finish recursive_colision_check

This commit is contained in:
someone 2024-03-04 00:52:32 +01:00
parent e4c3586dca
commit 57102ee34e
7 changed files with 567 additions and 43 deletions

23
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,23 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable",
"cargo": {
"args": [
"build",
],
},
"args": [
],
"cwd": "${workspaceFolder}"
},
]
}

282
Cargo.lock generated
View File

@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
@ -14,13 +20,63 @@ version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crossterm"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df"
dependencies = [
"bitflags 2.4.2",
"crossterm_winapi",
"libc",
"mio",
"parking_lot",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "dance-of-lines" name = "dance-of-lines"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"termion", "crossterm",
"lazy_static",
"rand",
] ]
[[package]]
name = "getrandom"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.153" version = "0.2.153"
@ -28,21 +84,91 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]] [[package]]
name = "libredox" name = "lock_api"
version = "0.0.2" version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3af92c55d7d839293953fcd0fda5ecfe93297cfde6ffbdec13b41d99c0ba6607" checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45"
dependencies = [ dependencies = [
"bitflags 2.4.2", "autocfg",
"libc", "scopeguard",
"redox_syscall",
] ]
[[package]] [[package]]
name = "numtoa" name = "log"
version = "0.1.0" version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "mio"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys",
]
[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
@ -54,19 +180,137 @@ dependencies = [
] ]
[[package]] [[package]]
name = "redox_termios" name = "scopeguard"
version = "0.1.3" version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20145670ba436b55d91fc92d25e71160fbfbdd57831631c8d7d36377a476f1cb" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]] [[package]]
name = "termion" name = "signal-hook"
version = "3.0.0" version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "417813675a504dfbbf21bfde32c03e5bf9f2413999962b479023c02848c1c7a5" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
dependencies = [ dependencies = [
"libc", "libc",
"libredox", "signal-hook-registry",
"numtoa",
"redox_termios",
] ]
[[package]]
name = "signal-hook-mio"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
dependencies = [
"libc",
]
[[package]]
name = "smallvec"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"

View File

@ -6,4 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
termion = "3.0.0" crossterm = "0.27.0"
lazy_static = "1.4.0"
rand = "0.8.5"

Binary file not shown.

94
src/components.rs Normal file
View File

@ -0,0 +1,94 @@
use crossterm::style::Color;
use crate::TERM_SIZE;
use rand::Error;
pub(crate) struct Element {
pub(crate) visual: char,
pub(crate) e_type: &'static str,
}
impl Element {
pub(crate) fn new(name: &str) -> Result<Element, Error> {
match name {
"wall" => Ok(Element { visual: '∩', e_type: "blob" }),
"spawn" => Ok(Element { visual: '@', e_type: "changing" }),
"body_part_v" => Ok(Element { visual: '|', e_type: "alive" }),
"body_part_h" => Ok(Element { visual: '-', e_type: "alive" }),
"body_part_l" => Ok(Element { visual: '/', e_type: "alive" }),
"body_part_r" => Ok(Element { visual: '\\', e_type: "alive" }),
"body_part_m+" => Ok(Element { visual: '+', e_type: "alive" }),
"body_part_mx" => Ok(Element { visual: 'X', e_type: "alive" }),
"food" => Ok(Element { visual: '#', e_type: "changing" }),
"body_part_head" => Ok(Element { visual: '█', e_type: "alive" }),
_ => Err(Error::new("Invalid element")),
}
}
pub(crate) fn copy(&self) -> Element {
Element {
visual: self.visual,
e_type: self.e_type,
}
}
}
pub struct Part {
pub(crate) element: Element,
pub(crate) position: (u16, u16),
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> {
if position.0 > TERM_SIZE.0 || position.1 > TERM_SIZE.1 {
// < 0 not needet because u16 is always positive
return Err(Error::new("Invalid position"));
}
Ok(Part {
element: Element::new(element)?,
position,
color: color,
direction: String::from("_ _"),
killed: false,
})
}
pub(crate) fn copy(&self) -> Part {
Part {
element: self.element.copy(),
position: self.position,
color: self.color,
killed: self.killed,
direction: self.direction.clone(),
}
}
}
pub(crate) struct CanvasState {
pub(crate) canvas: Vec<Part>,
pub(crate) prev_canvas: Vec<Part>,
pub(crate) iterations: u128,
pub(crate) food_rate: u8,
}
impl CanvasState {
pub(crate) fn new(canvas: Vec<Part>) -> CanvasState {
CanvasState {
canvas: canvas,
prev_canvas: Vec::new(),
iterations: 0,
food_rate: 10,
}
}
pub(crate) fn update(self, new_canvas: Vec<Part>) -> CanvasState {
CanvasState {
canvas: new_canvas,
prev_canvas: self.canvas,
food_rate: self.food_rate,
iterations: self.iterations + 1,
}
}
}

View File

@ -1,27 +1,64 @@
use termion::{screen, color, terminal_size}; #[doc(inline)]
pub use std; // for documentation purposes
use std::io::{self, Write};
use crossterm::{cursor::MoveTo, queue, QueueableCommand, style::{PrintStyledContent, Stylize, Color}, terminal::enable_raw_mode};
use lazy_static::lazy_static;
//lazy_static is ok, mutability not needed
use rand::{thread_rng, Rng};
use std::time::Duration;
use std::thread::sleep;
mod part_handler;
mod components;
lazy_static! {
static ref TERM_SIZE: (u16, u16) = crossterm::terminal::size().unwrap_or_else(|_| panic!("Cannot get terminal size"));
}
fn create_canvas() -> Vec<components::Part>{
let mut rng = thread_rng();
let mut canvas: Vec<components::Part> = 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
for y in 0..TERM_SIZE.1 {
if y == 0 || y == TERM_SIZE.1 - 1 {
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.push(part);
}
} else {
canvas.push(components::Part::new("wall", (0, y), wall_color).unwrap()); // 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.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
canvas // Return the canvas vector
}
fn draw_canvas(canvas: &Vec<components::Part>) {
let mut stdout = io::stdout();
stdout.queue(crossterm::terminal::Clear(crossterm::terminal::ClearType::All)).unwrap();
for part in canvas {
queue!(stdout, MoveTo(part.position.0, part.position.1),
PrintStyledContent(part.element.visual.to_string().with(part.color))).unwrap();
}
stdout.flush().unwrap();
}
fn main() { fn main() {
let terminal_size = terminal_size().expect("Cannot get terminal size"); let _ = enable_raw_mode();
let mut state: components::CanvasState = components::CanvasState::new(create_canvas());
draw_canvas(&state.canvas);
loop {
/* part_handler::head_handle(&mut state.canvas);
Equivalent to: part_handler::spawner_handle(&mut state.canvas);
let terminal_size: (u16, u16) = terminal_size().unwrap_or_else(|_| panic!("Cannot get terminal size"); state.canvas.sort_by_key(|part| (part.position.1, part.position.0));
draw_canvas(&state.canvas);
state.iterations += 1;
sleep(Duration::from_millis(17));
}
(unwrap would just panic if the result is Err, and expect would panic with the message provided.)
Equivalent to:
let terminal_size: (u16, u16) = match terminal_size() {
Ok(size) => size,
Err(_) => panic!("Cannot get erminal Size")
};
*/
println!("Terminal Size: {} by {} px", terminal_size.0, terminal_size.1);
} }
/*
Struckt: eigenes Datentypen
enum: Aufzählungstypen, können je nach Standartwert unterschiedliche Werte annehmen
impl: Implementierung von Methoden für Struckts
trait: Schnittstelle, die von Struckts implementiert werden kann, impl für mehrere Struckts
*/

124
src/part_handler.rs Normal file
View File

@ -0,0 +1,124 @@
use crossterm::style::Color;
use lazy_static::lazy_static;
use rand::Rng;
use std::collections::HashMap;
use crate::components::{self, Part};
const SIGHT_RADIUS: u16 = 3;
lazy_static! {
static ref CHECK_DIRECTIONS: HashMap<&'static str, [&'static str; 2]> = HashMap::from([
("t _", ["t r", "t l"]),
("t r", ["t _", "_ r"]),
("t l", ["t _", "_ l"]),
("b _", ["b r", "b l"]),
("b r", ["b _", "_ r"]),
("b l", ["b _", "_ l"]),
("_ r", ["t r", "b r"]),
("_ l", ["t r", "t l"]),
]);
}
lazy_static!{
static ref DIRECTIONS: HashMap<&'static str, i32> = HashMap::from([
("t", -1),
("b", 1),
("r", 1),
("l", -1),
("_", 0)
]);
}
fn check_collision(canvas: &Vec<components::Part>, position: (u16, u16)) -> bool {
canvas.iter().filter(|elem| elem.position == position).count() > 0
}
fn get_unused_color(canvas: &Vec<components::Part>) -> Color {
let mut color: Color = Color::Rgb { r: 0, g: 0, b: 0 };
let mut color_used: bool = true;
let mut rand_gen = rand::thread_rng();
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_used = canvas.iter().filter(|elem| elem.color == color).count() > 0;
}
color
}
pub fn spawner_handle(canvas: &mut Vec<components::Part>) {
// Collect the indices of active spawns
let active_spawn_indices: Vec<usize> = canvas
.iter_mut()
.enumerate()
.filter(|(_, elem)| elem.color == Color::Rgb { r: 10, g: 255, b: 10 })
.map(|(index, _)| index)
.collect();
let mut rand_gen = rand::thread_rng();
for &index in &active_spawn_indices {
let x: u8 = rand_gen.gen_range(0..100);
if rand_gen.gen_range(0..100) < 10 {
let pos: (u16, u16, &str) = match x % 4 {
// 0: up 1: right 2: down 3: left
0 => (canvas[index].position.0, canvas[index].position.1 - 1, "t _"),
1 => (canvas[index].position.0 + 1, canvas[index].position.1, "_ r"),
2 => (canvas[index].position.0, canvas[index].position.1 + 1, "b _"),
3 => (canvas[index].position.0 - 1, canvas[index].position.1, "_ l"),
_ => (1, 1, "b _"),
};
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());
canvas.last_mut().unwrap().direction = pos.2.to_string();
canvas[index].color = Color::Rgb { r: 10, g: 100, b: 10 };
}
}
}
}
fn recursive_colision_check(parts_in_sight: &Vec<Part>, position: &(u16, u16), direction: &str, iterations_left: u8) -> u32{
let x = direction.split_whitespace().take(2).collect::<Vec<&str>>();
let dir_x:&str = x[0];
let dir_y:&str = x[1];
let mut dyn_pos_res: Vec<(i32, i32, u32)> = Vec::new();
dyn_pos_res.push((i32::from(position.0) + DIRECTIONS[dir_x], i32::from(position.1) + DIRECTIONS[dir_y], 1));
for dynamic_pos in CHECK_DIRECTIONS[direction].into_iter() {
let x = dynamic_pos.split_whitespace().take(2).collect::<Vec<&str>>();
dyn_pos_res.push((i32::from(position.0) + DIRECTIONS[x[0]], i32::from(position.1) + DIRECTIONS[x[1]], 1));
}
for (x, y, val) in &dyn_pos_res {
for part in parts_in_sight {
if part.position == (*x as u16, *y as u16) {
//When element in sight, part is element in sight
}
}
}
dyn_pos_res.sort_by(|a, b| b.2.cmp(&a.2));
dyn_pos_res[0].2
/*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 Vec<components::Part>) {
// Find all elements that head can see
// Find all elements that head can see
for head_index in 0..canvas.len() {
if canvas[head_index].element.visual == '█' {
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(&parts_in_sight, &canvas[head_index].position , &canvas[head_index].direction.to_string() , 3);
}
}
}