-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.js
77 lines (68 loc) · 1.85 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
function Snake() {
this.x = 0;
this.y = 0;
this.xSpeed = 0;
this.ySpeed = 0;
this.total = 0;
this.tail = [];
this.render = function () {
fill(255);
rect(this.x, this.y, scl, scl);
if (this.tail.length >= 1) {
for (var i = 0; i < this.tail.length; i++) {
rect(this.tail[i].x, this.tail[i].y, scl, scl);
}
}
}
this.constrain = function () {
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.move = function () {
if (this.total >= 2) {
for (var i = this.total - 1; i > 0; i--) {
this.tail[i] = this.tail[i - 1]
}
}
if (this.total >= 1) {
this.tail[0] = createVector(this.x, this.y);
}
this.x = this.x + this.xSpeed * scl;
this.y = this.y + this.ySpeed * scl;
}
this.dir = function (x, y) {
this.xSpeed = x;
this.ySpeed = y;
}
this.eat = function (pos) {
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.total++;
return true;
} else {
return false;
}
}
this.death = function () {
for (var i = 0; i < this.tail.length; i++) {
var pos = this.tail[i];
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
if (parseInt(localStorage._highScore) < this.total) {
localStorage._highScore = this.total.toString();
}
this.reset();
}
}
}
this.reset = function () {
this.total = 0;
this.tail = [];
this.x = 0;
this.y = 0;
this.xSpeed = 0;
this.ySpeed = 0;
tickSpeed = 150;
spawnFood();
}
}