tiny_terminal_snake/
snake.rs1use crate::frame::*;
2use std::io::{Error, ErrorKind, Result};
3
4#[derive(Copy, Clone, Debug)]
5pub enum Direction {
6 Up,
7 Down,
8 Left,
9 Right,
10}
11
12#[derive(Debug)]
13pub struct Snake {
14 pub body: Vec<(i32, i32)>,
15 dir: Direction,
16}
17
18impl Snake {
19 pub fn new(head: (i32, i32), dir: Direction, length: usize) -> Self {
20 let a = match dir {
21 Direction::Up => (-1, 0),
22 Direction::Down => (1, 0),
23 Direction::Left => (0, 1),
24 Direction::Right => (0, -1),
25 };
26
27 let b = (0..length)
29 .map(|x| (head.0 + x as i32 * a.0, head.1 + x as i32 * a.1))
30 .collect::<Vec<_>>();
31
32 if !b.iter().all(|x| x.0 >= 0 && x.1 >= 0) {
33 return Self { body: vec![], dir };
34 }
35
36 Self {
37 body: b.iter().map(|x| (x.0, x.1)).collect::<Vec<_>>(),
38 dir,
39 }
40 }
41
42 pub fn len(&self) -> usize {
43 self.body.len()
44 }
45
46 pub fn head(&self) -> (i32, i32) {
47 self.body.first().unwrap().clone()
48 }
49
50 pub fn add_tail(&mut self, d: (i32, i32)) {
51 self.body.push(d);
52 }
53
54 pub fn show(&self, frame: &mut Frame) -> Result<()> {
55 for b in &self.body {
56 frame.write(b.0, b.1, String::from("◼"))?;
57 }
58 Ok(())
59 }
60
61 pub fn move_one_step(&mut self, k: &Direction) -> Result<(i32, i32)> {
63 self.dir = *k;
64 let step = match self.dir {
65 Direction::Up => (-1, 0),
66 Direction::Down => (1, 0),
67 Direction::Left => (0, -1),
68 Direction::Right => (0, 1),
69 };
70
71 let tail = self.body.pop().unwrap();
72 let a = self.body.first().unwrap();
73 let new_head = (a.0 as i32 + step.0, a.1 as i32 + step.1);
74
75 if self.included(&(new_head.0 as usize, new_head.1 as usize)) {
76 return Err(Error::new(ErrorKind::AlreadyExists, ""));
77 }
78
79 self.body.insert(0, new_head);
80
81 Ok(tail)
82 }
83
84 pub fn included(&self, point: &(usize, usize)) -> bool {
85 self.body.contains(&(point.0 as i32, point.1 as i32))
86 }
87}