From 9d46f2c47aaeab899c58e57fe615f085f338d39c Mon Sep 17 00:00:00 2001 From: deadvey Date: Tue, 24 Dec 2024 17:43:48 +0000 Subject: [PATCH] added snake (WIP) --- snake-wip/.gitignore | 1 + snake-wip/Cargo.toml | 9 ++++++ snake-wip/src/main.rs | 72 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 snake-wip/.gitignore create mode 100644 snake-wip/Cargo.toml create mode 100644 snake-wip/src/main.rs diff --git a/snake-wip/.gitignore b/snake-wip/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/snake-wip/.gitignore @@ -0,0 +1 @@ +/target diff --git a/snake-wip/Cargo.toml b/snake-wip/Cargo.toml new file mode 100644 index 0000000..789632a --- /dev/null +++ b/snake-wip/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "snake" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.8.5" diff --git a/snake-wip/src/main.rs b/snake-wip/src/main.rs new file mode 100644 index 0000000..aa2d8ae --- /dev/null +++ b/snake-wip/src/main.rs @@ -0,0 +1,72 @@ +use rand::Rng; +use std::io::{stdin,stdout,Write}; + +fn write_map(snake: char, apple: char, x_snake: u16, y_snake: u16, x_apple: u16, y_apple: u16, width: u16, height: u16) { + print!("{}[2J", 27 as char); + for y in 0..height { + for x in 0..width { + if x == x_snake && y == y_snake { + print!("{}",snake); + } + else if x == x_apple && y == y_apple { + print!("{}", apple); + } + else { + print!("."); + } + } + println!(); + } + println!("Snake: {},{}\nApple: {},{}",x_snake,y_snake,x_apple,y_apple) +} + +fn input() -> String{ + let mut s=String::new(); + let _=stdout().flush(); + stdin().read_line(&mut s).expect("Did not enter a correct string"); + if let Some('\n')=s.chars().next_back() { + s.pop(); + } + if let Some('\r')=s.chars().next_back() { + s.pop(); + } + return s; +} + +fn main() { + let mut rng = rand::thread_rng(); + + let width: u16 = 130; + let height: u16 = 30; + + let mut x_snake: u16 = 0; + let mut y_snake: u16 = 0; + let mut x_apple: u16 = rand::thread_rng().gen_range(0..width); + let mut y_apple: u16 = rand::thread_rng().gen_range(0..height); + println!("X apple: {}, Y apple: {}",x_apple,y_apple); + + let snake: char = 'S'; + let apple: char = 'A'; + + let mut alive: bool = true; + + write_map(snake, apple, x_snake, y_snake, x_apple, y_apple, width, height); + while alive { + let direction: &str = &input(); + // Movement + if direction == "w" { + if y_snake == 0 { y_snake = height - 1 } + else { y_snake-=1 } + } + if direction == "a" { + if x_snake == 0 { x_snake = width - 1 } + else { x_snake-=1 } + } + if direction == "s" { y_snake+=1 } + if direction == "d" { x_snake+=1 } + // Looping over edge + if x_snake > width { x_snake = 0 } + if x_snake < 0 { x_snake = width } + write_map(snake, apple, x_snake, y_snake, x_apple, y_apple, width, height); + }; +}