-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.hpp
133 lines (120 loc) · 2.49 KB
/
snake.hpp
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <deque>
#include <algorithm>
struct Coord
{
int x, y;
bool operator==(const Coord a)
{
return a.x == x && a.y == y;
}
};
enum Direction
{
North,
West,
East,
South
};
class Snake
{
public:
// Creates a new snake with no body
// facing North
Snake();
// Adds a head to the Snake at Coord(x, y)
// and a next at Coord(x, y+1)
void begin(int x, int y);
// Checks if any of the Snake parts is at
// Coord(x,y)
bool occupies(int x, int y);
// Checks if any of the Snake parts is at xy
bool occupies(Coord xy);
// Checks if Coord(x, y) is occupied by the snake head
bool ishead(int x, int y);
// Returns the next position of the snake head if the snakes moves once in its
// direction
Coord next_move();
// Returns the position of the snake head
Coord head();
// Move adds a Coord to the snake head then deletes a Coord from it's tail
// if the snake is "growing" it doesn't delete tails until it stops "growing"
void move();
// Changes the direction of the snake
void redirect(Direction direct);
// Extend the snake lenght by pausing tail deletion while
// moving for x moves
void eat(int x);
private:
int growth;
Direction dir;
std::deque<Coord> coords;
};
Snake::Snake()
: dir(North), growth(0)
{
}
void Snake::begin(int x, int y)
{
coords.push_back({x, y});
coords.push_back({x, y + 1});
}
bool Snake::ishead(int x, int y)
{
return coords.front().x == x && coords.front().y == y;
}
bool Snake::occupies(Coord xy)
{
return std::find(coords.begin(), coords.end(), xy) != coords.end();
}
bool Snake::occupies(int x, int y)
{
return std::find(coords.begin(), coords.end(), Coord{x, y}) != coords.end();
}
Coord Snake::next_move()
{
Coord xy = coords.front();
switch (dir)
{
case North:
xy.x--;
break;
case East:
xy.y++;
break;
case South:
xy.x++;
break;
case West:
xy.y--;
break;
}
return xy;
}
void Snake::move()
{
Coord xy = next_move();
coords.push_front(xy);
if (growth > 0)
{
growth--;
}
else
{
coords.pop_back();
}
}
void Snake::eat(int x)
{
growth += x;
}
void Snake::redirect(Direction direct)
{
// Don't redirect to the opposite direction
// so the snake doesn't try to enter it's neck
if (direct + dir != 3)
dir = direct;
}
Coord Snake::head()
{
return coords.front();
}