2019-04-05 03:45:47 +11:00
|
|
|
use super::variables::{Position, Size};
|
2018-08-20 07:13:21 +10:00
|
|
|
|
2019-04-11 07:46:30 +10:00
|
|
|
use crossterm::{cursor, Colorize, TerminalCursor};
|
2018-08-20 07:13:21 +10:00
|
|
|
|
|
|
|
use rand::distributions::{IndependentSample, Range};
|
|
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
use rand;
|
|
|
|
|
2019-01-28 07:16:14 +11:00
|
|
|
pub struct Map {
|
2018-08-20 07:13:21 +10:00
|
|
|
pub size: Size,
|
|
|
|
pub foot_pos: Position,
|
|
|
|
}
|
|
|
|
|
2019-01-28 07:16:14 +11:00
|
|
|
impl Map {
|
|
|
|
pub fn new(size: Size) -> Self {
|
|
|
|
Map {
|
|
|
|
size: size,
|
|
|
|
foot_pos: Position::new(0, 0),
|
|
|
|
}
|
|
|
|
}
|
2018-08-20 07:13:21 +10:00
|
|
|
|
|
|
|
// render the map on the screen.
|
2019-04-11 07:46:30 +10:00
|
|
|
pub fn render_map(&mut self, free_positions: &mut HashMap<String, Position>) {
|
2019-01-28 07:16:14 +11:00
|
|
|
for y in 0..self.size.height {
|
|
|
|
for x in 0..self.size.height {
|
|
|
|
if (y == 0 || y == self.size.height - 1) || (x == 0 || x == self.size.width - 1) {
|
2019-04-11 07:46:30 +10:00
|
|
|
cursor().goto(x as u16, y as u16);
|
|
|
|
print!("{}", "█".magenta());
|
2019-01-28 07:16:14 +11:00
|
|
|
} else {
|
|
|
|
free_positions.insert(format!("{},{}", x, y), Position::new(x, y));
|
2018-08-20 07:13:21 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-28 07:16:14 +11:00
|
|
|
pub fn is_out_of_bounds(&self, new_pos: Position) -> bool {
|
|
|
|
if (new_pos.x == 0 || new_pos.x == self.size.width)
|
|
|
|
|| (new_pos.y == 0 || new_pos.y == self.size.height)
|
2018-08-20 07:13:21 +10:00
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2019-01-28 07:16:14 +11:00
|
|
|
pub fn is_food_eaten(&self, snake_head: Position) -> bool {
|
2018-08-20 07:13:21 +10:00
|
|
|
snake_head.x == self.foot_pos.x && snake_head.y == self.foot_pos.y
|
|
|
|
}
|
|
|
|
|
2019-04-11 07:46:30 +10:00
|
|
|
pub fn spawn_food(&mut self, free_positions: &HashMap<String, Position>) {
|
2018-08-20 07:13:21 +10:00
|
|
|
let index = Range::new(0, free_positions.len()).ind_sample(&mut rand::thread_rng());
|
|
|
|
self.foot_pos = free_positions.values().skip(index).next().unwrap().clone();
|
2019-04-11 07:46:30 +10:00
|
|
|
self.draw_food();
|
2018-08-20 07:13:21 +10:00
|
|
|
}
|
|
|
|
|
2019-04-11 07:46:30 +10:00
|
|
|
fn draw_food(&self) {
|
|
|
|
let cursor = TerminalCursor::new();
|
2019-01-28 07:16:14 +11:00
|
|
|
cursor.goto(self.foot_pos.x as u16, self.foot_pos.y as u16);
|
2019-04-11 07:46:30 +10:00
|
|
|
print!("{}", "$".green());
|
2018-08-20 07:13:21 +10:00
|
|
|
}
|
2019-01-28 07:16:14 +11:00
|
|
|
}
|