forked from technezio/snake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake_class.cpp
134 lines (123 loc) · 2.32 KB
/
snake_class.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "snake_class.h"
// Constructor
Snake::Snake()
{
lenght = 1;
head = new Dot;
head -> dir = RIGHT;
head -> x = 1;
head -> y = 1;
head -> next = NULL;
tail = head;
apple[0] = 0;
apple[1] = 0;
}
// Add a "piece" of snake after eating an apple
void Snake::append()
{
tail -> next = new Dot;
Dot *tmp = tail -> next;
tmp -> dir = tail -> dir;
switch(tail -> dir)
{
case UP:
tmp->x = tail->x;
tmp->y = tail->y + 1;
tmp->y = (tmp->y == 9) ? 1 : tmp->y;
break;
case RIGHT:
tmp->y = tail->y;
tmp->x = tail->x -1;
tmp->x = (tmp->x == 0) ? 8 : tmp->x;
break;
case DOWN:
tmp->x = tail->x;
tmp->y = tail->y - 1;
tmp->y = (tmp->y == 0) ? 8 : tmp->y;
break;
case LEFT:
tmp->y = tail->y;
tmp->x = tail->x +1;
tmp->x = (tmp->x == 9) ? 1 : tmp->x;
break;
}
tail = tail -> next;
tail -> next = NULL;
lenght++;
}
// Move the snake in the current direction
void Snake::move()
{
Dot *p = head;
direct tmp1 = p -> dir;
direct tmp2 = p -> dir;
for(byte i = 0; i < lenght; i++, p = p -> next)
{
switch(p -> dir)
{
case UP:
p -> y--;
p -> y = (p -> y == 0) ? 8 : p -> y;
break;
case RIGHT:
p -> x++;
p -> x = (p -> x == 9) ? 1 : p -> x;
break;
case DOWN:
p -> y++;
p -> y = (p -> y == 9) ? 1 : p -> y;
break;
case LEFT:
p -> x--;
p -> x = (p -> x == 0) ? 8 : p -> x;
break;
}
tmp2 = p -> dir;
p -> dir = tmp1;
tmp1 = tmp2;
}
}
// Change direction
void Snake::changeDir(direct d)
{
switch(d)
{
case UP:
if( head->dir != DOWN )
head->dir = d;
break;
case RIGHT:
if( head->dir != LEFT )
head->dir = d;
break;
case DOWN:
if( head->dir != UP )
head->dir = d;
break;
case LEFT:
if( head->dir != RIGHT )
head->dir = d;
break;
}
}
/*boolean Snake::posHead(byte x, byte y)
{
return ((x == head->x) && (y == head->y)) ? true: false;
}*/
// Spawn a new apple
void Snake::newApple()
{
do
{
apple[0] = random(1, 9);
apple[1] = random(1, 9);
}
while( (apple[0] == head->x) && (apple[1] == head->y) );
}
// Check if snake is eating the apple (head over the apple)
boolean Snake::eat()
{
if( (apple[0] == head->x) && (apple[1] == head->y) )
return true;
return false;
}