-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
334 lines (287 loc) · 8.07 KB
/
index.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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// ------------ BOARD SETUP -------------
let gameStarted = false;
let isGameOver = false;
let countdownText = 4;
const countDownAudio = new Audio("audio/countdown.wav");
const foodEatenAudio = new Audio("audio/eating.wav");
const gameOverAudio = new Audio("audio/gameover.wav");
// audio muted on default for accesability purposes
let muted = true;
[countDownAudio.muted, foodEatenAudio.muted, gameOverAudio.muted] = [
true,
true,
true,
];
// establishing canvas on the page
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
// setting canvas background
canvas.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// fillRect() paramaters = (x start, y start, width, height)
// display instructions to start
ctx.font = "20px monospace";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.fillText(
"Click enter to begin the game.",
canvas.width / 2,
canvas.height / 2 - 15
);
ctx.fillText(
"Use the arrow keys to play!",
canvas.width / 2,
canvas.height / 2 + 15
);
// ------------ LOCAL STORAGE ------------
if (!localStorage.getItem("storedScore")) {
localStorage.setItem("storedScore", "0");
}
let highscore = localStorage.getItem("storedScore");
// ------------ SCORE DISPLAY ------------
// displaying the score text on canvas
let score = 0;
let display = "000";
const displayScore = () => {
//clear old text
ctx.beginPath();
ctx.rect(0, 0, canvas.width, 30);
ctx.fillStyle = "black";
ctx.fill();
//format score for the display
score < 10
? (display = "000")
: score < 100
? (display = "00")
: score < 1000
? (display = "0")
: score < 10000
? (display = "")
: null;
//write new score
ctx.font = "16px monospace";
ctx.fillStyle = "white";
ctx.fillText(`score: ${display}${score}`, 390, 20);
// write highscore
ctx.font = "16px monospace";
ctx.fillStyle = "white";
ctx.fillText(`best: ${highscore}`, 50, 20);
};
// ------------ CLEAR BOARD FUNC -------------
//used throughtout all the sections
const clearBoard = () => {
ctx.beginPath();
ctx.rect(0, 30, canvas.width, canvas.height - 10);
ctx.fillStyle = "black";
ctx.fill();
};
// ------------ COUNTDOWN -------------
// function where the action starts! Called on keypress
const startGamePlay = (e) => {
if ((!gameStarted && e.keyCode === 13) || (isGameOver && e.keyCode === 13)) {
//Remove the instructions text
clearBoard();
displayScore();
gameStarted = true;
isGameOver = false; //reset if this is a replay
//Play sound and call countdown func
countDownAudio.play();
displayCountDown();
} else if (
e.keyCode === 37 ||
e.keyCode === 38 ||
e.keyCode === 39 ||
e.keyCode === 40
) {
changeDirection(e.keyCode); //or move the snake
}
};
// put settimout inside delay func to omit repetition
const delay = () => {
return new Promise((resolve) => {
setTimeout(() => resolve(), 800);
});
};
// function to display countdown
const displayCountDown = () => {
countdownText > 1 ? countdownText-- : (countdownText = "GO!");
Promise.resolve()
.then(() => {
// display the curret countdown text
ctx.font = "42px monospace";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.fillText(countdownText, canvas.height / 2, canvas.width / 2);
})
.then(() => delay()) // settimeout
.then(() => clearBoard()) // rid of old text
.then(() => {
countdownText !== "GO!" ? displayCountDown() : playSnake();
});
};
// ------------ PLAY SNAKE -------------
let snakeParts = [
{ x: 200, y: 220 },
{ x: 180, y: 220 },
{ x: 160, y: 220 },
];
let foodx;
let foody;
let speed = 250;
// The amount of the pixel the snake will move along x & y
// automatic direction is snake moving right
let xDirection = 20;
let yDirection = 0;
const playSnake = () => {
if (isGameOver) return;
setTimeout(() => {
// wrapped in settimeout for smooth gameplay
clearBoard();
displayScore();
moveSnake();
drawSnake();
playSnake();
}, speed);
};
const generateFood = () => {
let random1 = Math.random() * 420; //max board width
foodx = random1 - (random1 % 20); // must be multiple of 20
let random2 = Math.random() * (420 - 60) + 60; // not top 60px of board
foody = random2 - (random2 % 20);
// check if food position is beneath snake
for (let i = 0; i < snakeParts.length; i++) {
if (snakeParts[i].x === foodx.x && snakeParts[i].y === foody.y) {
generateFood();
}
}
};
const drawSnake = () => {
//draw the food first so it's beneth the snake
ctx.fillStyle = "red";
ctx.fillRect(foodx, foody, 20, 20);
ctx.strokeRect(foodx, foody, 20, 20); // block outline
//draw the snake
snakeParts.forEach((part) => {
ctx.fillStyle = "green";
ctx.fillRect(part.x, part.y, 20, 20);
ctx.strokeRect(part.x, part.y, 20, 20);
});
collisionDetect();
};
const moveSnake = () => {
const newBlock = {
x: snakeParts[0].x + xDirection,
y: snakeParts[0].y + yDirection,
};
snakeParts.unshift(newBlock); // add newBlock to front of snake
snakeParts.pop(); // remove last block
};
const changeDirection = (key) => {
//each if() checks key pressed and doesn't allow snake to move backwards
if (key === 37 && xDirection !== 20) {
xDirection = -20;
yDirection = 0;
}
if (key === 38 && yDirection !== 20) {
yDirection = -20;
xDirection = 0;
}
if (key === 39 && xDirection !== -20) {
xDirection = 20;
yDirection = 0;
}
if (key === 40 && yDirection !== -20) {
yDirection = 20;
xDirection = 0;
}
};
const collisionDetect = () => {
//if first block of snake and food have same position
if (snakeParts[0].x === foodx && snakeParts[0].y === foody) {
foodEatenAudio.play();
score = score + 10;
generateFood();
const newBlock = {
x: snakeParts[snakeParts.length - 1].x + xDirection,
y: snakeParts[snakeParts.length - 1].y + yDirection,
};
snakeParts.push(newBlock); //add new block to end of snake
//if new highscore then update in local storage
if (Number(score) > Number(highscore)) {
highscore = score;
localStorage.setItem("storedScore", score.toString());
}
}
if (score === 50) speed = 150; //speed up game
if (score === 100) speed = 100; //speed up game
//check if front of snake passes edge of board
if (
snakeParts[0].x > canvas.width - 20 ||
snakeParts[0].x < 0 ||
snakeParts[0].y < 0 ||
snakeParts[0].y > canvas.height - 20
) {
gameOver();
}
//check if front of snake hits any other snake part
for (let i = 1; i < snakeParts.length; i++) {
if (
snakeParts[0].x === snakeParts[i].x &&
snakeParts[0].y === snakeParts[i].y
) {
gameOver();
}
}
};
// ------------ GAME OVER -------------
const gameOver = () => {
isGameOver = true; // this stops the playGame() reccursion
gameOverAudio.play();
// display game over text
ctx.font = "80px monospace";
ctx.fillStyle = "white";
ctx.fillText("GAME", canvas.width / 2, canvas.height / 2 - 15);
ctx.fillText("OVER", canvas.width / 2, canvas.height / 2 + 45);
ctx.font = "17px monospace";
ctx.fillText("click enter to replay", canvas.width / 2, canvas.height - 45);
//reset countdown
countdownText = 4;
//reset snake
snakeParts = [
{ x: 200, y: 220 },
{ x: 180, y: 220 },
{ x: 160, y: 220 },
];
//reset score
score = 0;
//reset speed
speed = 250;
//reset direction on start
xDirection = 20;
yDirection = 0;
};
// eventListner on the page
window.addEventListener("keydown", startGamePlay);
generateFood(); //generate first food position on load
displayScore(); //display default score on load
// ------------ PAGE SOUND -------------
// eventListener for mute sound & image toggle
document.querySelector("button").addEventListener("click", (e) => {
if (muted) {
muted = false;
e.target.src = "images/mute.png";
} else {
muted = true;
e.target.src = "images/sound.png";
}
[countDownAudio.muted, foodEatenAudio.muted, gameOverAudio.muted] = [
muted,
muted,
muted,
];
});
// KEY CODES:
// left = 37
// up = 38
// right = 39
// down = 40