-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
165 lines (142 loc) · 3.83 KB
/
script.js
File metadata and controls
165 lines (142 loc) · 3.83 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
class Snake {
constructor(initialPos) {
// last element of array is head of snake
this._body = [initialPos];
// dx, dy represent velocity of snake in terms of x, y components
this._dx = 0;
this._dy = 0;
}
advance(ateApple) {
this._body.push(this.next());
if (!ateApple) this._body.shift();
}
next() {
const head = this.getFront();
return { x: head.x + this._dx, y: head.y + this._dy };
}
*iterBody() {
yield* this._body;
}
size() {
return this._body.length;
}
contains({ x, y }) {
return this._body.some((cell) => cell.x === x && cell.y === y);
}
getFront() {
return this._body.at(-1);
}
handleKeypress(event) {
// FIXME: it's possible to turn in the opposite direction and immediately die
switch (event.key) {
case 'w':
case 'ArrowUp':
this._dx = 0;
this._dy = -1;
break;
case 'a':
case 'ArrowLeft':
this._dx = -1;
this._dy = 0;
break;
case 's':
case 'ArrowDown':
this._dx = 0;
this._dy = 1;
break;
case 'd':
case 'ArrowRight':
this._dx = 1;
this._dy = 0;
break;
}
}
}
function selectRandomElement(items) {
return items[Math.floor(Math.random() * items.length)];
}
class Game {
static GRID_SIZE = 16;
constructor(canvas) {
this.reset();
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
}
update() {
const next = this._snake.next();
if (this._snake.contains(next)) {
// collided with other part of the snake
// FIXME: notify player
this.reset();
} else if (0 <= next.x && next.x < Game.GRID_SIZE && 0 <= next.y && next.y < Game.GRID_SIZE) {
const ateApple = next.x === this._apple.x && next.y === this._apple.y;
this._snake.advance(ateApple);
if (ateApple) {
const maxSize = Game.GRID_SIZE * Game.GRID_SIZE;
if (this._snake.size === maxSize) {
// game completed
// FIXME: notify player
this.reset();
} else {
// select a new position for the apple
const candidates = [];
for (let x = 0; x < Game.GRID_SIZE; x++) {
for (let y = 0; y < Game.GRID_SIZE; y++) {
if (!this._snake.contains({ x, y })) candidates.push({ x, y });
}
}
this._apple = selectRandomElement(candidates);
}
}
} else {
// died
// FIXME: notify player
this.reset();
}
this._render();
}
_render() {
this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
const h = this._canvas.height / Game.GRID_SIZE;
const w = this._canvas.width / Game.GRID_SIZE;
this._ctx.fillStyle = 'red';
this._ctx.fillRect(this._apple.x * w, this._apple.y * h, w - 1, h - 1);
this._ctx.fillStyle = 'green';
for (const cell of this._snake.iterBody()) {
this._ctx.fillRect(cell.x * w, cell.y * h, w - 1, h - 1);
}
}
handleKeypress(event) {
this._snake.handleKeypress(event);
}
reset() {
this._snake = new Snake({
x: Math.floor(Game.GRID_SIZE / 2),
y: Math.floor(Game.GRID_SIZE / 2),
});
this._apple = { x: 5, y: 5 };
}
}
// See https://stackoverflow.com/questions/1955687/best-way-for-simple-game-loop-in-javascript.
function callWithFrameDelay(f, frameDelay) {
let prevTime = 0;
let delta = 0;
function loop(time) {
const dt = time - prevTime;
delta += dt;
prevTime = time;
while (delta > frameDelay) {
f();
delta -= frameDelay;
}
requestAnimationFrame(loop);
}
requestAnimationFrame((time) => {
prevTime = time;
requestAnimationFrame(loop);
});
}
const FRAME_DELAY = 90; // how many milliseconds between updates -- higher value means slower movement and vice versa
const game = new Game(document.getElementById('game'));
document.addEventListener('keydown', (event) => game.handleKeypress(event));
callWithFrameDelay(() => game.update(), FRAME_DELAY);