Created
July 10, 2025 12:15
-
-
Save nekename/77ae79c8861d014957c0505fe500ae62 to your computer and use it in GitHub Desktop.
RustSnake
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::VecDeque; | |
use std::process::exit; | |
use std::sync::mpsc::channel; | |
use std::thread::{sleep, spawn}; | |
use std::time::Duration; | |
use console::{Key, Term}; | |
const WALL: &str = "\u{001b}[45m "; | |
const BG: &str = "\u{001b}[102m "; | |
const SNAKE: &str = "\u{001b}[44m "; | |
const HEAD: &str = "\u{001b}[104m "; | |
const APPLE: &str = "\u{001b}[41m "; | |
const RESET: &str = "\u{001b}[0m "; | |
const SIZE: isize = 25; | |
fn main() { | |
let (sender, receiever) = channel::<Key>(); | |
spawn(move || { | |
let term = Term::stdout(); | |
loop { | |
if let Ok(key) = term.read_key() { | |
let _ = sender.send(key); | |
} | |
} | |
}); | |
let mut snake: VecDeque<[isize; 2]> = VecDeque::new(); | |
snake.push_back([2, SIZE / 2]); | |
snake.push_back([3, SIZE / 2]); | |
snake.push_back([4, SIZE / 2]); | |
use rand::Rng; | |
let mut rng = rand::rng(); | |
let mut apple = [ | |
rng.random_range(1usize..=23) as isize, | |
rng.random_range(1usize..=23) as isize, | |
]; | |
let mut direction: [isize; 2] = [1, 0]; | |
loop { | |
while let Ok(key) = receiever.try_recv() { | |
match key { | |
Key::ArrowUp if direction[1] == 0 => direction = [0, -1], | |
Key::ArrowDown if direction[1] == 0 => direction = [0, 1], | |
Key::ArrowLeft if direction[0] == 0 => direction = [-1, 0], | |
Key::ArrowRight if direction[0] == 0 => direction = [1, 0], | |
_ => {} | |
} | |
} | |
let mut new = snake[snake.len() - 1]; | |
new[0] += direction[0]; | |
new[1] += direction[1]; | |
if snake.contains(&new) | |
|| new[0] == 0 | |
|| new[0] == SIZE - 1 | |
|| new[1] == 0 | |
|| new[1] == SIZE - 1 | |
{ | |
exit(0); | |
} | |
if new == apple { | |
apple = [ | |
rng.random_range(1usize..=23) as isize, | |
rng.random_range(1usize..=23) as isize, | |
]; | |
} else { | |
snake.pop_front(); | |
} | |
snake.push_back(new); | |
for y in 0..SIZE { | |
for x in 0..SIZE { | |
if snake.contains(&[x, y]) { | |
if [x, y] == snake[snake.len() - 1] { | |
print!("{HEAD}"); | |
} else { | |
print!("{SNAKE}"); | |
} | |
} else if [x, y] == apple { | |
print!("{APPLE}"); | |
} else if x == 0 || x == SIZE - 1 || y == 0 || y == SIZE - 1 { | |
print!("{WALL}"); | |
} else { | |
print!("{BG}"); | |
} | |
} | |
println!("{RESET}"); | |
} | |
sleep(Duration::from_millis(200)); | |
println!("\x1b[H\x1b[2J"); | |
println!("{}", snake.len() - 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment