-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.js
108 lines (88 loc) · 1.76 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
export class Snake {
segments = [];
direction = {
x: 0,
y: 0,
};
init(position) {
this.segments = [position];
}
moveUp() {
if (this.direction.y !== 0) {
return;
}
this.direction = {
x: 0,
y: -1,
};
}
moveDown() {
if (this.direction.y !== 0) {
return;
}
this.direction = {
x: 0,
y: 1,
};
}
moveLeft() {
if (this.direction.x !== 0) {
return;
}
this.direction = {
x: -1,
y: 0,
};
}
moveRight() {
if (this.direction.x !== 0) {
return;
}
this.direction = {
x: 1,
y: 0,
};
}
update() {
const head = this.getHead();
const newHead = {
x: head.x + this.direction.x,
y: head.y + this.direction.y,
};
this.segments = this.segments.slice(0, -1);
this.segments.unshift(newHead);
}
render(canvas) {
this.segments.forEach((segment) => {
const snakeElement = document.createElement("div");
snakeElement.style.gridRowStart = segment.y;
snakeElement.style.gridColumnStart = segment.x;
snakeElement.classList.add("snake");
snakeElement.append("🐍");
canvas.appendChild(snakeElement);
});
}
getHead() {
return this.segments[0];
}
getTail() {
return this.segments[this.segments.length - 1];
}
grow() {
this.segments.push({ ...this.getTail() });
}
onHit(position) {
const head = this.getHead();
return head.x === position.x && head.y === position.y;
}
onHitSelf() {
return this.segments.slice(1).some((segment) => {
return this.onHit(segment);
});
}
onBody(position) {
return this.segments.some(
(segment) => segment.x === position.x && segment.y === position.y
);
}
}