-
Notifications
You must be signed in to change notification settings - Fork 1
/
snake.js
108 lines (94 loc) · 2.45 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
let pieceSize = 10;
class Snake {
constructor(startX, startY, startDirX = 1, startDirY = 0, shouldDraw = true) {
this.body = [new Piece(startX, startY)];
this.dir = [startDirX, startDirY];
this.piecesToAdd = 0;
this.alive = true;
this.shouldDraw = shouldDraw;
}
draw() {
if (this.shouldDraw) {
for (var i = 0; i < this.body.length; i++) {
if(i == 0){
this.body[i].draw(0);
} else {
this.body[i].draw(255);
}
}
}
}
addPiece() {
this.piecesToAdd++
}
setDirection(dir) {
if ((this.dir[0] != 0 && dir[0] != 0) ||
(this.dir[1] != 0 && dir[1] != 0)) {
return;
}
this.dir = dir;
}
move() {
if (!this.alive) {
return;
}
var lastPos = this.body[this.body.length - 1].getPos();
for (var i = this.body.length - 1; i > 0; i--) {
this.body[i].setPos(this.body[i - 1].getPos());
}
this.body[0].move(this.dir);
// console.log(this.body[0]);
if (this.piecesToAdd > 0) {
this.body.push(new Piece(lastPos[0], lastPos[1]));
this.piecesToAdd--;
}
this.checkCollision();
this.draw();
}
checkCollision() {
for (var i = 0; i < this.body.length; i++) {
for (var j = 0; j < this.body.length; j++) {
if (i != j && this.body[i].equals(this.body[j])) {
// console.log("killed");
this.alive = false;
}
}
}
}
posIsTail(x, y) {
for (var i = 1; i < this.body.length; i++) {
if (this.body[i].x == x && this.body[i].y == y) {
return true;
}
}
return false;
}
getHeadPos() {
return this.body[0].getPos();
}
}
class Piece {
constructor(x, y) {
this.x = x;
this.y = y;
}
getPos() {
return [this.x, this.y]
}
setPos(pos) {
this.x = pos[0];
this.y = pos[1];
}
move(dir) {
this.x += dir[0] * pieceSize;
this.y += dir[1] * pieceSize;
}
draw(color) {
fill(color);
rectMode(CENTER);
rect(this.x, this.y, pieceSize, pieceSize);
}
equals(piece) {
return this.x == piece.x && this.y == piece.y;
}
}