forked from waffledood/ReverseSnake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.h
92 lines (72 loc) · 2 KB
/
snake.h
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
#ifndef __SNAKE_H__
#define __SNAKE_H__
#include "motion.h"
#define MAX_SNAKE_LENGTH 100
struct Snake constructSnake(int x, int y, double speed, int length);
void growSnake(struct Snake *s);
void moveSnake(struct Snake *s, struct Position playerPos);
void updateSnakeBody(struct Snake *s, struct Position newPos);
void setSnakeSpeed(struct Snake *s, double speed);
struct Snake {
struct Position body[MAX_SNAKE_LENGTH];
int ticksPerMove;
int length;
int ticksElapsed;
};
struct Snake constructSnake(int x, int y, double speed, int length) {
struct Snake snake;
snake.body[0].x = x;
snake.body[0].y = y;
snake.length = 1;
snake.ticksElapsed = 0;
setSnakeSpeed(&snake, speed);
int i;
for (i = 0; i < length - 1; i++) {
growSnake(&snake);
}
return snake;
}
void growSnake(struct Snake *s) {
if (s->length >= MAX_SNAKE_LENGTH) {
return;
}
s->body[s->length] = s->body[s->length - 1];
s->length++;
}
void moveSnake(struct Snake *s, struct Position playerPos) {
if (s->ticksElapsed < s->ticksPerMove) {
s->ticksElapsed++;
return;
}
s->ticksElapsed = 0;
struct Position nextPos;
nextPos.x = s->body[0].x;
nextPos.y = s->body[0].y;
int diffX = s->body[0].x - playerPos.x;
int diffY = s->body[0].y - playerPos.y;
if ((abs(diffX) >= abs(diffY))) {
if (diffX > 0) {
nextPos.x -= 1;
} else if (diffX < 0) {
nextPos.x += 1;
}
} else if (abs(diffX) < abs(diffY)) {
if (diffY > 0) {
nextPos.y -= 1;
} else if (diffY < 0) {
nextPos.y += 1;
}
}
updateSnakeBody(s, nextPos);
}
void updateSnakeBody(struct Snake *s, struct Position newPos) {
int i;
for (i = s->length - 1; i > 0; i--) {
s->body[i] = s->body[i - 1];
}
s->body[0] = newPos;
}
void setSnakeSpeed(struct Snake *s, double speed) {
s->ticksPerMove = (1 / speed) * GAME_UPDATE_HZ;
}
#endif // __SNAKE_H__