-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.cpp
More file actions
110 lines (94 loc) · 1.94 KB
/
Snake.cpp
File metadata and controls
110 lines (94 loc) · 1.94 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
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
#include "Snake.h"
#include "utils.h"
Snake::Snake()
{
constexpr Pos head = { WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2 };
this->body.push_back(head);
for (size_t i = 0; i < SNAKE_INIT_LENGTH; i++)
{
Pos pos = { this->body.back().x - SNAKE_SIZE, head.y };
this->body.push_back(pos);
}
}
void Snake::move()
{
for (auto it = this->body.end() - 1; it != this->body.begin(); --it)
{
const Pos prev = *(it - 1);
(*it).x = prev.x;
(*it).y = prev.y;
}
const Pos headNext = this->getHeadNextPos();
this->body.front().x = headNext.x;
this->body.front().y = headNext.y;
}
void Snake::render(SDL_Renderer* renderer) const
{
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
for (auto it = this->body.begin(); it != this->body.end(); ++it)
{
SDL_Rect rect = { (*it).x, (*it).y, SNAKE_SIZE, SNAKE_SIZE };
SDL_RenderFillRect(renderer, &rect);
}
}
bool Snake::checkCollision(Pos pos)
{
for (auto it = this->body.begin(); it != this->body.end(); ++it)
{
if (checkPosOverlap(pos, *it) == true)
{
return true;
}
}
return false;
}
bool Snake::checkHeadBodyCollision()
{
const Pos head = this->getHeadPos();
for (auto it = this->body.begin() + 1; it != this->body.end(); ++it)
{
if (checkPosOverlap(head, *it) == true)
{
return true;
}
}
return false;
}
void Snake::appendHead(Pos newHeadPos)
{
const Pos newHead = { newHeadPos.x, newHeadPos.y };
this->body.insert(this->body.begin(), newHead);
}
Pos Snake::getHeadPos() const
{
return this->body.front();
}
Pos Snake::getHeadNextPos() const
{
Pos head = this->getHeadPos();
constexpr int moveStep = SNAKE_SIZE;
switch (this->direction)
{
case UP:
head.y -= moveStep;
break;
case DOWN:
head.y += moveStep;
break;
case LEFT:
head.x -= moveStep;
break;
case RIGHT:
head.x += moveStep;
break;
}
return head;
}
Direction Snake::getDirection() const
{
return this->direction;
}
void Snake::setDirection(const Direction dire)
{
this->direction = dire;
}