Repository navigation
Expand file tree
/
Copy pathsnake.js
More file actions
87 lines (74 loc) 路 1.64 KB
/
Copy pathsnake.js
File metadata and controls
87 lines (74 loc) 路 1.64 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
function Snake() {
this.x = 0;
this.y = 0;
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.y > canvas.height) {
this.y = 0;
}
if (this.x < 0) {
this.x = canvas.width;
}
if (this.y < 0) {
this.y = canvas.height;
}
}
this.changeDirection = function(direction) {
switch(direction) {
case 'Up':
this.xSpeed = 0;
this.ySpeed = -scale * 1;
break;
case 'Down':
this.xSpeed = 0;
this.ySpeed = scale * 1;
break;
case 'Left':
this.xSpeed = -scale * 1;
this.ySpeed = 0;
break;
case 'Right':
this.xSpeed = scale * 1;
this.ySpeed = 0;
break;
}
}
this.eat = function(fruit) {
if (this.x === fruit.x &&
this.y === fruit.y) {
this.total++;
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.tail = [];
}
}
}
}