73 lines
2.0 KiB
Rust
73 lines
2.0 KiB
Rust
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);
|
|
};
|
|
}
|