-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer_snake.pde
135 lines (111 loc) · 2.75 KB
/
player_snake.pde
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
134
135
class PlayerSnake {
float rectSize, genSpeed, xSpeed, ySpeed, x, y;
ArrayList<PVector> tail = new ArrayList<PVector>();
PlayerSnake(int rectSize) {
this.rectSize = rectSize;
genSpeed = rectSize;
xSpeed = genSpeed;
ySpeed = 0;
x = rectSize*2;
y = rectSize*2;
}
void growTail() {
tail.add(new PVector(x, y));
}
void updateDirection() {
// Read in movement keys
if (key == 'w' || key == UP) {
if (tail.size() == 0) {
direction(0, -genSpeed);
}
else if (xSpeed != 0 || ySpeed != genSpeed) {
direction(0, -genSpeed);
}
}
if (key == 'a' || key == LEFT) {
if (tail.size() == 0) {
direction(-genSpeed, 0);
}
else if (xSpeed != genSpeed || ySpeed != 0) {
direction(-genSpeed, 0);
}
}
if (key == 's' || key == DOWN) {
if (tail.size() == 0) {
direction(0, genSpeed);
}
else if (xSpeed != 0 || ySpeed != -genSpeed) {
direction(0, genSpeed);
}
}
if (key == 'd' || key == RIGHT) {
if (tail.size() == 0) {
direction(genSpeed, 0);
}
else if (xSpeed != -genSpeed || ySpeed != 0) {
direction(genSpeed, 0);
}
}
}
void updatePosition() {
float prevTailX = x;
float prevTailY = y;
float tempTailX;
float tempTailY;
// Update each rect in the tail with the position of the rect infront of it
for (PVector rectPoint : tail) {
// Hold this rect's position
tempTailX = rectPoint.x;
tempTailY = rectPoint.y;
// Update with new coordinates
rectPoint.x = prevTailX;
rectPoint.y = prevTailY;
// Save previous coordinates
prevTailX = tempTailX;
prevTailY = tempTailY;
}
// Move the head
x += xSpeed;
y += ySpeed;
}
void direction(float x, float y) {
xSpeed = x;
ySpeed = y;
}
boolean eat(Food food) {
if ((x > food.x - rectSize && x < food.x + food.rectSize) &&
(y > food.y - rectSize && y < food.y + food.rectSize)) {
return true;
}
else {
return false;
}
}
boolean death() {
boolean hitTail = false;
boolean hitTop = y < 0;
boolean hitBottom = x > height - rectSize;
boolean hitLeft = y > width - rectSize;
boolean hitRight = x < 0;
for (PVector t : tail) {
if ((x > t.x - rectSize && x < t.x + rectSize) &&
(y > t.y - rectSize && y < t.y + rectSize)) {
hitTail = true;
}
}
if (hitTop || hitBottom || hitLeft || hitRight || hitTail) {
return true;
}
else {
return false;
}
}
void show() {
fill(255);
stroke(51);
for (PVector v : tail) {
rect(v.x, v.y, rectSize, rectSize);
}
rect(x, y, rectSize, rectSize);
}
}