-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.js
More file actions
101 lines (84 loc) · 2.48 KB
/
snake.js
File metadata and controls
101 lines (84 loc) · 2.48 KB
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
function Snake() {
this.x = 0;
this.y = 0;
this.maxSpeed = 250;
this.xSpeed = scale * 1;
this.ySpeed = 0;
this.total = 0;
this.tail = [];
this.draw = function(){
ctx.fillStyle = "#FFFFFF";
for (let i=0; i<this.tail.length; i++){
ctx.fillRect(this.tail[i].x, this.tail[i].y, scale, scale);
}
ctx.fillRect(this.x, this.y, scale, scale);
}
this.update = function() {
for (let i=0; i<this.tail.length -1; i++){
this.tail[i] = this.tail[i+1];
}
this.tail[this.total - 1] = { x: this.x, y: this.y }
this.x += this.xSpeed;
this.y += this.ySpeed;
if(this.x > canvas.width) {
this.x = 0;
}
if(this.x < 0) {
this.x = canvas.width;
}
if(this.y >= canvas.height) {
this.y = 0;
}
if(this.y < 0) {
this.y = canvas.height -10;
}
}
var prevDirection;
this.changeDirection = function(direction){
switch(direction){
case 'Up':
if (prevDirection == 'Down') break;
this.xSpeed = 0;
this.ySpeed = -scale * 1;
prevDirection = direction;
break;
case 'Down':
if (prevDirection == 'Up') break;
this.xSpeed = 0;
this.ySpeed = scale * 1;
prevDirection = direction;
break;
case 'Left':
if (prevDirection == 'Right') break;
this.xSpeed = -scale * 1;
this.ySpeed = 0;
prevDirection = direction;
break;
case 'Right':
if (prevDirection == 'Left') break;
this.xSpeed = scale * 1;
this.ySpeed = 0;
prevDirection = direction;
break;
}
}
this.eat = function(){
if (this.x === fruit.x && this.y === fruit.y){
this.total++;
this.maxSpeed *= .895;
return true;
}
return false;
}
this.checkCollision = function() {
for(var i=0; i<this.tail.length; i++){
if(this.x === this.tail[i].x && this.y === this.tail[i].y){
this.total = 0;
this.maxSpeed = 250;
this.tail = [];
ui.state.playing = 0;
startBtn.disabled = false;
}
}
}
}