-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.cpp
More file actions
110 lines (90 loc) · 2.38 KB
/
Game.cpp
File metadata and controls
110 lines (90 loc) · 2.38 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 "Game.h"
void Game::Setup() {
queue.Enqueue((Point){ 3, 3 });
used[3][3] = WormPoint;
AddRandomFood();
AddRandomFood();
delayTimer = millis() + delay;
}
int Game::Update() {
const unsigned long currentTime = millis();
if (deadState >= 4)
return 1;
if (currentTime < delayTimer || deadState)
return 0;
delayTimer = currentTime + delay;
Point wormFront = queue.PeekBack();
Point nextPoint = wormFront.Add(direction);
if (nextPoint.x < 0 || nextPoint.x >= GAMESIZE || nextPoint.y < 0 || nextPoint.y >= GAMESIZE) {
SetDead();
return 0;
}
int *loc = GetPosition(nextPoint);
if (*loc & WormPoint) {
SetDead();
} else if (*loc & FoodPoint) {
queue.Enqueue(nextPoint);
*loc = WormPoint;
AddRandomFood();
} else {
queue.Enqueue(nextPoint);
*loc = WormPoint;
int *oldLoc = GetPosition(queue.Dequeue());
*oldLoc = 0;
}
}
void Game::GetVisuals(uint8_t *buffer) {
const unsigned long currentTime = millis();
if (!deadState) {
const int foodDelay = delay / 1.5;
bool blinkFood = (currentTime % foodDelay) < (foodDelay / 2);
for (int x = 0; x < GAMESIZE; x++) {
buffer[GAMESIZE - 1 - x] = 0;
for (int y = 0; y < GAMESIZE; y++) {
if (used[x][y] & WormPoint || (blinkFood && (used[x][y] & FoodPoint)))
buffer[GAMESIZE - 1 - x] |= 1 << (GAMESIZE - 1 - y);
}
}
} else {
for (int x = 0; x < GAMESIZE; x++) {
buffer[GAMESIZE - 1 - x] = 0;
for (int y = 0; y < GAMESIZE; y++) {
if (used[x][y] & WormPoint || (x >= (4 - deadState) && x <= (3 + deadState) && y >= (4 - deadState) && y <= (3 + deadState))) {
buffer[GAMESIZE - 1 - x] |= 1 << (GAMESIZE - 1 - y);
if (deadTimer < currentTime) {
deadTimer = currentTime + deadDelay;
deadState++;
}
}
}
}
}
}
int *Game::GetPosition(Point point) {
return &used[point.x][point.y];
}
void Game::AddRandomFood() {
int initX = random(0, GAMESIZE);
int initY = random(0, GAMESIZE);
int x = initX;
int y = initY;
do {
int *pos = &used[x][y];
if ((*pos == 0)) {
*pos = FoodPoint;
break;
}
x++;
if (x >= GAMESIZE) {
x = 0;
y++;
}
if (y >= GAMESIZE) {
y = 0;
}
} while (x != initX || y != initY);
}
void Game::SetDead() {
deadState = 1;
deadTimer = millis() + deadDelay;
}