-
Notifications
You must be signed in to change notification settings - Fork 1
/
snake.js
61 lines (53 loc) · 1.57 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
function Snake(){
this.show = function(){
//draw the snake tail
for(var i=0;i<this.tail.length;i++){
var prot = this.tailProteins[this.tail.length - 1 - i];
fill(prot.colour);
rect(this.tail[i].x, this.tail[i].y, pixelSize, pixelSize);
}
//draw the snake head
fill(this.tailProteins[this.tailProteins.length - 1].colour);
rect(this.pos.x, this.pos.y, pixelSize, pixelSize)
}
this.update = function(){
//move snake's position into tail and pop off the end
if(movement.length){
if(snake.speed.x != movement[0][0]*-1 && snake.speed.y != movement[0][1]*-1){
snake.dir(movement[0][0], movement[0][1]);
}
movement.splice(0, 1);
}
this.tail.unshift(createVector(this.pos.x, this.pos.y));
this.tail.pop();
//move the snake
this.pos.x += this.speed.x * pixelSize;
this.pos.y += this.speed.y * pixelSize;
}
this.dir = function(x, y){
this.speed.x = x;
this.speed.y = y;
}
this.checkDeath = function(){
if(this.pos.x >= width || this.pos.y >= height || this.pos.x < 0 || this.pos.y < 0){
gameState = 'end';
}
for(var i=0;i<this.tail.length;i++){
if(this.tail[i].x == this.pos.x && this.tail[i].y == this.pos.y){
gameState = 'end';
}
}
}
this.eat = function(pos){
return this.pos.x == pos.x && this.pos.y == pos.y;
}
this.reset = function(){
shots = [];
this.score = 0;
this.tail = [];
this.tailProteins = [getRandomShot()];
this.pos = createVector(0, 0);
this.speed = createVector(1, 0);
}
this.reset();
}