-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.cpp
85 lines (62 loc) · 1.79 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
#include "snake.h"
void snakeEffect(int time, int drawTime) {
emptyCube();
//Snake* snake1 = new Snake(5, 0);
Snake* snake2 = new Snake(6, 25);
drawState(drawTime);
NonBlockDelay timer;
timer.delay(time);
while(!timer.timeout()) {
//snake1->update();
snake2->update();
drawState(drawTime);
}
//delete snake1;
delete snake2;
}
/***************
* Snake class *
***************/
Snake::Snake(byte length, byte turnChance) {
xyz startPos = randomPosition();
init(length, turnChance, startPos, randomValidDirection(startPos));
}
Snake::Snake(byte length, byte turnChance, xyz startPos) {
init(length, turnChance, startPos, randomValidDirection(startPos));
}
Snake::Snake(byte length, byte turnChance, xyz startPos, xyz dir) {
init(length, turnChance, startPos, dir);
}
void Snake::init(byte length, byte turnChance, xyz startPos, xyz dir) {
this->length = length;
this->turnChance = turnChance;
direction = dir;
snakeParts = new xyz[length];
for (byte idx = 0; idx < length; idx++) {
snakeParts[idx] = {-1, -1, -1};
}
snakeParts[0] = startPos;
headIndex = 0;
}
void Snake::update() {
byte nextIndex = (headIndex + 1) % length;
//Serial.print("nextIndex: ");
// Serial.println(nextIndex);
// Turn off the tail
xyz tail = snakeParts[nextIndex];
ledOff(tail.x, tail.y, tail.z);
// Replace the tail with the head and turn it on
xyz next = nextPart();
snakeParts[nextIndex] = next;
ledOn(next.x, next.y, next.z);
headIndex = nextIndex;
}
xyz Snake::nextPart() {
xyz head = snakeParts[headIndex];
xyz moved = head + direction;
if ( !inRange(moved.x, moved.y, moved.z) || (random(100) < turnChance) ) {
direction = randomValidDirection(head, direction.negate());
return head + direction;
}
return moved;
}