-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.cpp
More file actions
118 lines (98 loc) · 2.56 KB
/
Copy pathboard.cpp
File metadata and controls
118 lines (98 loc) · 2.56 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
111
112
113
114
115
116
117
118
#include "board.h"
Board::Board(const int &width, const int &height)
: width_(width), heigth_(height)
{
head_ = new Square();
head_->color_ = QColor("orange");
head_->position = {width_ / 2 + 2, heigth_ / 2};
int i = 0;
for (Square* current = head_; current != nullptr; current = current->next) {
if (i++ >= 3) break;
current->next = new Square();
current->next->color_ = QColor("yellow");
current->next->position = current->position + Vec2({-1, 0});
}
makeApple();
}
Board::~Board()
{
deleteSnake(head_);
}
bool Board::move()
{
Vec2 oldPos = head_->position;
eatApple();
head_->position += moveDir;
if (head_->position.x >= width_) {
head_->position.x = 0;
}
if (head_->position.x < 0) {
head_->position.x = width_ - 1;
}
if (head_->position.y >= heigth_) {
head_->position.y = 0;
}
if (head_->position.y < 0) {
head_->position.y = heigth_ - 1;
}
if (collision(head_->position)) {
// Game over
head_->position = oldPos;
return false;
}
for (Square* current = head_->next; current != nullptr; current = current->next) {
Vec2 curPos = current->position;
lastPos_ = curPos;
current->position = oldPos;
oldPos = curPos;
}
return true;
}
int Board::getScore()
{
return score_;
}
bool Board::collision(Vec2 newPos)
{
for (Square* current = head_->next; current != nullptr; current = current->next) {
if (current->position == newPos) {
return true;
}
}
return false;
}
void Board::makeApple()
{
int seed = time(0);
randomEng_.seed(seed);
distrX_ = std::uniform_int_distribution<int>(0, width_ - 1);
distrX_(randomEng_);
int appleX = distrX_(randomEng_);
distrY_ = std::uniform_int_distribution<int>(0, heigth_ - 1);
int appleY = distrY_(randomEng_);
apple_ = new Square();
apple_->color_ = QColor("red");
apple_->position = {appleX, appleY};
}
void Board::eatApple()
{
// Check for apple to eat
if (apple_->position == head_->position) {
delete apple_;
makeApple();
Square *current = head_;
while (current->next != nullptr) {
current = current->next;
}
current->next = new Square();
current->next->color_ = QColor("yellow");
current->next->position = lastPos_;
score_ += 20;
}
}
void Board::deleteSnake(Square *square)
{
if (square == nullptr) return;
deleteSnake(square->next);
delete square;
}