added snake (WIP)
This commit is contained in:
parent
76257b7483
commit
9d46f2c47a
1
snake-wip/.gitignore
vendored
Normal file
1
snake-wip/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target
|
9
snake-wip/Cargo.toml
Normal file
9
snake-wip/Cargo.toml
Normal file
@ -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"
|
72
snake-wip/src/main.rs
Normal file
72
snake-wip/src/main.rs
Normal file
@ -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);
|
||||
};
|
||||
}
|
Loading…
Reference in New Issue
Block a user