-
Notifications
You must be signed in to change notification settings - Fork 1
/
snake.js
113 lines (95 loc) · 2.53 KB
/
snake.js
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
/*
Date: 4th of August 2017
version 0.1
All source under GPL version 3 or latter
(GNU General Public License - http://www.gnu.org/)
contact martin@linux.com for more information about this code
*/
function Snake(headX, headY, blockSize, headColour, bodyColour) {
this.headX = headX;
this.headY = headY;
this.blockSize = blockSize;
this.headColour = headColour;
this.bodyColour = bodyColour;
this.body = [];
this.direction = "WEST";
this.speed = 1;
this.growing = 0;
var b = new Block(this.headX + this.blockSize, this.headY,
this.blockSize, this.bodyColour);
this.body.push(b);
}
Snake.prototype.show = function() {
noStroke();
fill(255)
rect(this.headX,this.headY,this.blockSize,this.blockSize);
for (var i = 0; i < this.body.length; i++) {
this.body[i].show();
}
}
Snake.prototype.grow = function(v) {
this.growing = this.growing + v;
}
Snake.prototype.move = function() {
var len = this.body.length;
var oldPosX;
var oldPosY;
var b;
if (this.growing == 0) {
for (var i = 1; i < len; i = i + 1) {
oldPosX = this.body[i].xpos;
oldPosY = this.body[i].ypos;
this.body[i-1].newPosition(oldPosX,oldPosY);
}
this.body[len-1].newPosition(this.headX,this.headY);
} else {
b = new Block(this.headX, this.headY,
this.blockSize, this.bodyColour);
this.body.push(b);
this.growing = this.growing - 1;
}
if (this.direction == "WEST") {
this.headX = this.headX - this.blockSize;
}
if (this.direction == "NORTH") {
this.headY = this.headY - this.blockSize;
}
if (this.direction == "SOUTH") {
this.headY = this.headY + this.blockSize;
}
if (this.direction == "EAST") {
this.headX = this.headX + this.blockSize;
}
}
Snake.prototype.changeDirectionUp = function() {
if (this.direction != "SOUTH") {
this.direction = "NORTH";
}
}
Snake.prototype.changeDirectionDown = function() {
if (this.direction != "NORTH") {
this.direction = "SOUTH";
}
}
Snake.prototype.changeDirectionLeft = function() {
if (this.direction != "EAST") {
this.direction = "WEST";
}
}
Snake.prototype.changeDirectionRight = function() {
if (this.direction != "WEST") {
this.direction = "EAST";
}
}
Snake.prototype.collision = function() {
var i;
if (this.headX < blockSize) return true;
if (this.headY < blockSize) return true;
if (this.headX >= width - this.blockSize) return true;
if (this.headY >= height - this.blockSize) return true;
for (i = 0; i < this.body.length-1; i++) {
if ((this.headX == this.body[i].xpos) &&
(this.headY == this.body[i].ypos)) return true;
}
return false;
}