-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.rs
More file actions
83 lines (70 loc) · 1.95 KB
/
base.rs
File metadata and controls
83 lines (70 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::{io::Stdout, ops::{Add, Sub}};
use crossterm::{cursor, execute, terminal};
#[derive(PartialEq, Clone, Copy)]
pub struct Vector2i {
x: i32,
y: i32,
}
impl Vector2i {
pub fn new(x: i32, y: i32) -> Self {
Self { x, y }
}
pub fn from_usize(val: &usize, width: &usize) -> Self {
Self { x: (val % width) as i32, y: (val / width) as i32 }
}
pub fn to_usize(&self, width: &usize) -> usize {
return self.x as usize + self.y as usize * width;
}
pub const RIGHT: Self = Self { x: 1, y: 0 };
pub const LEFT: Self = Self { x: -1, y: 0 };
pub const UP: Self = Self { x: 0, y: -1 };
pub const DOWN: Self = Self { x: 0, y: 1 };
}
impl Sub<Vector2i> for Vector2i {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
return Vector2i::new(self.x - rhs.x, self.y - rhs.y);
}
}
impl Add<Vector2i> for Vector2i {
type Output = Self;
fn add(self, rhs: Vector2i) -> Self::Output {
return Vector2i::new(self.x + rhs.x, self.y + rhs.y);
}
}
impl Add<&Vector2i> for Vector2i {
type Output = Self;
fn add(self, rhs: &Vector2i) -> Self::Output {
return Vector2i::new(self.x + rhs.x, self.y + rhs.y);
}
}
pub fn clear_field(matrix: &mut [Cell]) {
for i in 0..matrix.len() {
matrix[i] = Cell::Empty;
}
}
pub fn flush(matrix: &[Cell], width: usize, out: &mut Stdout) {
execute!(out, terminal::Clear(terminal::ClearType::All), cursor::MoveTo(0,0)).unwrap();
let mut res: String = String::new();
for row in matrix.chunks(width) {
for cell in row {
let val = decide_cell(&cell);
res.push(val);
}
res.push('\n');
}
print!("{}", res);
}
pub fn decide_cell(cell: &Cell) -> char {
return match cell {
Cell::Empty => '-',
Cell::Apple => '@',
Cell::Snake => '#'
}
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum Cell {
Empty,
Apple,
Snake
}