-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.cpp
87 lines (73 loc) · 2.27 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
#include <memory>
#include "snake.h"
Snake::Snake(int x, int y)
{
std::list<Point> initialCoordinates = {
Point{ x, y, Material::SNAKE_HEAD },
Point{ x + 1, y, Material::SNAKE_BODY },
Point{ x + 2, y, Material::SNAKE_BODY }
};
coordinates.insert(coordinates.end(), initialCoordinates.begin(), initialCoordinates.end());
}
void Snake::setDirection(Direction newDirection)
{
if (
(lastPerformedDirection == Direction::UP && newDirection == Direction::DOWN) ||
(lastPerformedDirection == Direction::DOWN && newDirection == Direction::UP) ||
(lastPerformedDirection == Direction::LEFT && newDirection == Direction::RIGHT) ||
(lastPerformedDirection == Direction::RIGHT && newDirection == Direction::LEFT)
)
{
return;
}
currentDirection = newDirection;
}
void Snake::move()
{
Point& head = coordinates.front();
Point tail = coordinates.back();
Point newHead;
switch (currentDirection)
{
case Direction::UP:
newHead = Point{ head.x, head.y - 1, Material::SNAKE_HEAD };
break;
case Direction::DOWN:
newHead = Point{ head.x, head.y + 1, Material::SNAKE_HEAD };
break;
case Direction::LEFT:
newHead = Point{ head.x - 1, head.y, Material::SNAKE_HEAD };
break;
case Direction::RIGHT:
newHead = Point{ head.x + 1, head.y, Material::SNAKE_HEAD };
break;
}
head = Point{ head.x, head.y, Material::SNAKE_BODY };
coordinates.pop_back();
coordinates.push_front(newHead);
if (willGrow)
{
coordinates.push_back(tail);
willGrow = false;
}
lastPerformedDirection = currentDirection;
}
void Snake::grow()
{
willGrow = true;
}
std::optional<std::pair<Entity&, Material>> Snake::checkCollision(const std::vector<std::reference_wrapper<Entity>>& entities) const
{
const Point& head = coordinates.front();
for (auto entity : entities)
{
for (auto point : entity.get().getCoordinates())
{
if (head.x == point.x && head.y == point.y && point.material != Material::SNAKE_HEAD)
{
return std::make_pair(entity, point.material);
}
}
}
return {};
}