-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake.cpp
93 lines (79 loc) · 1.66 KB
/
Snake.cpp
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
#include "Snake.h"
#include <assert.h>
#include <thread>
#include <chrono>
Snake::Snake(const Location& loc)
{
segments[0].InitHead(loc);
}
void Snake::MoveBy(const Location& delta_loc)
{
for (int i = nSegments - 1; i > 0; --i) {
segments[i].Follow(segments[i - 1]);
}
segments[0].MoveBy(delta_loc);
}
void Snake::Grow()
{
if (nSegments < nSegmentsMax) {
segments[nSegments].InitBody();
++nSegments;
}
}
void Snake::Draw(Board& brd) const
{
for (int i = 0; i < nSegments; ++i) {
segments[i].Draw(brd);
}
}
Location Snake::GetNextHeadLocation(const Location& delta_loc) const
{
Location l(segments[0].GetLocation());
l.Add(delta_loc);
return l;
}
bool Snake::IsInTileExceptEnd(const Location& target) const
{
for (int i = 0; i < nSegments-1; ++i) {
if (segments[i].GetLocation() == target) {
return true;
}
}
return false;
}
bool Snake::IsInTile(const Location& target) const
{
for (int i = 0; i < nSegments; ++i) {
if (segments[i].GetLocation() == target) {
return true;
}
}
return false;
}
void Snake::Segment::Draw(Board& brd) const
{
brd.DrawCell(loc, c);
}
const Location& Snake::Segment::GetLocation() const
{
return loc;
}
void Snake::Segment::Follow(const Segment& next)
{
loc = next.loc;
}
void Snake::Segment::MoveBy(const Location& delta_loc)
{
assert(abs(delta_loc.x) + abs(delta_loc.y) == 1);
loc.Add(delta_loc);
std::this_thread::sleep_for(std::chrono::milliseconds(snakespeed));
}
void Snake::Segment::InitHead(const Location& in_loc)
{
loc = in_loc;
c = Snake::headColor;
}
void Snake::Segment::InitBody()
{
c = Snake::bodyColor;
}