-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
500 lines (436 loc) · 14.3 KB
/
script.js
File metadata and controls
500 lines (436 loc) · 14.3 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// --- DOM Elements ---
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const scoreElement = document.getElementById("score");
const gameOverElement = document.getElementById("gameOver");
const finalScoreElement = document.getElementById("finalScore");
const restartButton = document.getElementById("restartButton");
const startMessageElement = document.getElementById("startMessage");
const startButton = document.getElementById("startButton");
const gameContainer = document.querySelector(".game-container");
const canvasContainer = document.querySelector(".canvas-container");
const easterEggVideo = document.getElementById("easterEggVideo");
const pausedMessageElement = document.getElementById("pausedMessage");
// --- Game Constants ---
const GRID_SIZE = 20; // Number of cells in the grid
let CANVAS_WIDTH, CANVAS_HEIGHT;
let CELL_SIZE;
const POWER_UP_POINTS = 3;
const EATER_EGG_TRIGGER = 50;
// --- Audio Elements ---
const eatSound = new Audio('media/eat.mp3');
const gameOverSound = new Audio('media/game-over.mp3');
// --- Image Elements ---
const powerUpImage = new Image();
powerUpImage.src = 'media/rat.png';
// --- Define color gradient start/end colors ---
// Head has darker color and gradually becomes lighter towards the tail
const SNAKE_HEAD_COLOR_RGB = [22, 101, 52]; // Dark Green (rgb(22, 101, 52))
const SNAKE_TAIL_COLOR_RGB = [134, 239, 172]; // Lighter Green (tailwind green-400)
const FOOD_COLOR = "#ef4444"; // Red (tailwind red-500)
const BORDER_COLOR = "#555555"; // Slightly lighter border for contrast on white
const INITIAL_SPEED_MS = 150;
const MAX_SPEED_MS = 80;
// --- Game State ---
let snake = [];
let food = { x: 0, y: 0 };
let powerUp = null;
let dx = 0;
let dy = 0;
let score = 0;
let changingDirection = false;
let gameLoopInterval = null;
let gameActive = false;
let currentSpeed = INITIAL_SPEED_MS;
let isPaused = false;
// --- Touch Controls ---
const btnUp = document.getElementById("btnUp");
const btnDown = document.getElementById("btnDown");
const btnLeft = document.getElementById("btnLeft");
const btnRight = document.getElementById("btnRight");
// --- Functions ---
// dynamic canvas size based on container width(cater for different screen sizes)
function calculateCanvasSize() {
const containerWidth = canvasContainer.clientWidth;
CELL_SIZE = Math.floor(containerWidth / GRID_SIZE);
CANVAS_WIDTH = CELL_SIZE * GRID_SIZE;
CANVAS_HEIGHT = CELL_SIZE * GRID_SIZE;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
const maxHeight = window.innerHeight * 0.6;
if (CANVAS_HEIGHT > maxHeight) {
CELL_SIZE = Math.floor(maxHeight / GRID_SIZE);
CANVAS_WIDTH = CELL_SIZE * GRID_SIZE;
CANVAS_HEIGHT = CELL_SIZE * GRID_SIZE;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
}
}
function clearCanvas() {
// --- Explicitly clear with white ---
ctx.fillStyle = "#ffffff"; // White background
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
// Function to interpolate between two RGB colors
// to create a gradient effect on the snake
function interpolateColor(color1, color2, factor) {
// Factor is between 0 and 1 (0 = color1, 1 = color2)
const r = Math.round(color1[0] + (color2[0] - color1[0]) * factor);
const g = Math.round(color1[1] + (color2[1] - color1[1]) * factor);
const b = Math.round(color1[2] + (color2[2] - color1[2]) * factor);
return `rgb(${r}, ${g}, ${b})`;
}
// --- drawSnakePart now needs index and length for gradient ---
function drawSnakePart(part, index, length) {
let segmentColor;
if (length <= 1) {
// Only head exists, use head color
segmentColor = `rgb(${SNAKE_HEAD_COLOR_RGB.join(",")})`;
} else {
// Calculate interpolation factor (0 for head, 1 for tail)
const factor = index / (length - 1);
segmentColor = interpolateColor(
SNAKE_HEAD_COLOR_RGB,
SNAKE_TAIL_COLOR_RGB,
factor
);
}
ctx.fillStyle = segmentColor; // fill with gradient color
ctx.strokeStyle = BORDER_COLOR; // border color
ctx.lineWidth = 1;
// draw the snake part
ctx.fillRect(part.x * CELL_SIZE, part.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
ctx.strokeRect(part.x * CELL_SIZE, part.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// --- Pass index and length to drawSnakePart ---
function drawSnake() {
const snakeLength = snake.length;
snake.forEach((part, index) => {
drawSnakePart(part, index, snakeLength);
});
}
function drawFood() {
ctx.fillStyle = FOOD_COLOR;
ctx.strokeStyle = BORDER_COLOR; // Use the same border for consistency
ctx.lineWidth = 1;
// draw the food
ctx.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
ctx.strokeRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// Function to draw the power-up
function drawPowerUp() {
// image must fit into the cell
if (powerUp) {
ctx.drawImage(
powerUpImage,
powerUp.x * CELL_SIZE,
powerUp.y * CELL_SIZE,
CELL_SIZE,
CELL_SIZE
);
}
}
function moveSnake() {
if (!gameActive || isPaused) return;
// snake[0] is the head
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
// Wall Wrapping
// when the head hit the wall, it will wrap around(reappear) to the other side
if (head.x < 0) head.x = GRID_SIZE - 1;
else if (head.x >= GRID_SIZE) head.x = 0;
if (head.y < 0) head.y = GRID_SIZE - 1;
else if (head.y >= GRID_SIZE) head.y = 0;
// update the new head position
// by inserting the new head at the beginning of the snake array
snake.unshift(head);
// check if the head hit the food
if (head.x === food.x && head.y === food.y) {
score++;
scoreElement.textContent = `Score: ${score}`;
eatSound.play();
// Check for easter egg
if (score === EATER_EGG_TRIGGER) {
triggerEasterEgg();
}
// create food at a new position
generateFood();
// Generate power-up every 10 points
if (score % 10 === 0) {
generatePowerUp();
}
// we increase the speed as the game progresses to make it more challenging
// this can be achieved by reducing the interval time between each game loop
// so that the snake get redrawn more frequently
if (score % 5 === 0 && currentSpeed > MAX_SPEED_MS) {
currentSpeed -= 10;
console.log(currentSpeed)
clearInterval(gameLoopInterval);
gameLoopInterval = setInterval(gameLoop, currentSpeed);
}
} else if (powerUp && head.x === powerUp.x && head.y === powerUp.y) {
// Handle power-up collection
eatSound.play();
score += POWER_UP_POINTS;
scoreElement.textContent = `Score: ${score}`;
powerUp = null; // Remove the power-up
} else {
// if the head did not hit the food, we remove the last part of the snake
// making it look like the snake is moving forward
snake.pop();
}
changingDirection = false;
}
function generateFood() {
let newFoodX, newFoodY;
do {
newFoodX = Math.floor(Math.random() * GRID_SIZE);
newFoodY = Math.floor(Math.random() * GRID_SIZE);
} while (snake.some((part) => part.x === newFoodX && part.y === newFoodY));
food = { x: newFoodX, y: newFoodY };
}
// Function to generate a power-up
function generatePowerUp() {
let newPowerUpX, newPowerUpY;
do {
newPowerUpX = Math.floor(Math.random() * GRID_SIZE);
newPowerUpY = Math.floor(Math.random() * GRID_SIZE);
} while (
snake.some((part) => part.x === newPowerUpX && part.y === newPowerUpY) ||
(food.x === newPowerUpX && food.y === newPowerUpY)
);
powerUp = { x: newPowerUpX, y: newPowerUpY };
}
function handleKeyDown(event) {
// allow player to restart the game by pressing enter
if (
event.key === "Enter" &&
!gameActive &&
!gameOverElement.classList.contains("hidden")
) {
startGame();
return;
}
if (!gameActive || changingDirection || isPaused) return;
const keyPressed = event.key;
// just translate condition to booleans for better readability
const goingUp = dy === -1;
const goingDown = dy === 1;
const goingLeft = dx === -1;
const goingRight = dx === 1;
// self-imposed constraint: x-axis has priority over y-axis
// we also update one axis at a time to avoid the snake moving in diagonal
if ((keyPressed === "ArrowLeft" || keyPressed === "a") && !goingRight) {
dx = -1;
dy = 0;
changingDirection = true;
} else if ((keyPressed === "ArrowUp" || keyPressed === "w") && !goingDown) {
dx = 0;
dy = -1;
changingDirection = true;
} else if (
(keyPressed === "ArrowRight" || keyPressed === "d") &&
!goingLeft
) {
dx = 1;
dy = 0;
changingDirection = true;
} else if ((keyPressed === "ArrowDown" || keyPressed === "s") && !goingUp) {
dx = 0;
dy = 1;
changingDirection = true;
}
}
// handle touch control for mobile players
function handleTouchControl(newDx, newDy) {
// make sure the previous direction is executed before a new direction is set
if (changingDirection || !gameActive || isPaused) return;
// just translate condition to booleans for better readability
const goingUp = dy === -1;
const goingDown = dy === 1;
const goingLeft = dx === -1;
const goingRight = dx === 1;
// self-imposed constraint: x-axis has priority over y-axis
// we also update one axis at a time to avoid the snake moving in diagonal
if (newDx === -1 && !goingRight) {
dx = -1;
dy = 0;
} else if (newDx === 1 && !goingLeft) {
dx = 1;
dy = 0;
} else if (newDy === -1 && !goingDown) {
dx = 0;
dy = -1;
} else if (newDy === 1 && !goingUp) {
dx = 0;
dy = 1;
} else {
return;
}
changingDirection = true;
}
function checkGameOver() {
const head = snake[0];
// Self collision check
// any of the snake parts has the same position as the head
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
function gameLoop() {
if (isPaused) return;
if (checkGameOver()) {
endGame();
return;
}
clearCanvas();
drawFood();
drawPowerUp();
moveSnake();
drawSnake();
}
function startGame() {
if (gameActive) return;
console.log("Starting game...");
gameActive = true;
score = 0;
currentSpeed = INITIAL_SPEED_MS;
dx = 1;
dy = 0;
changingDirection = false;
isPaused = false;
scoreElement.textContent = `Score: ${score}`;
gameOverElement.classList.add("hidden");
startMessageElement.classList.add("hidden");
pausedMessageElement.classList.add("hidden");
const startX = Math.floor(GRID_SIZE / 2);
const startY = Math.floor(GRID_SIZE / 2);
snake = [
{ x: startX, y: startY },
{ x: startX - 1, y: startY },
{ x: startX - 2, y: startY },
];
generateFood();
clearCanvas();
// Draw initial state correctly
drawFood();
drawSnake();
if (gameLoopInterval) clearInterval(gameLoopInterval);
gameLoopInterval = setInterval(gameLoop, currentSpeed);
}
function endGame() {
if(!gameOverElement.classList.contains("hidden")) {
return; // Prevent multiple game over messages
}
console.log("Game Over!");
gameActive = false;
clearInterval(gameLoopInterval);
gameLoopInterval = null;
finalScoreElement.textContent = score;
gameOverElement.classList.remove("hidden");
gameOverSound.play(); // Play game over sound effect
powerUp = null;
currentSpeed = INITIAL_SPEED_MS; // Reset speed for next game
}
function showStartMessage() {
calculateCanvasSize();
clearCanvas();
// Draw a representative snake/food for the start screen
const startX = Math.floor(GRID_SIZE / 2);
const startY = Math.floor(GRID_SIZE / 2);
// Create a temporary snake for drawing on start screen
const tempSnake = [
{ x: startX, y: startY },
{ x: startX - 1, y: startY },
];
const tempFood = { x: startX + 2, y: startY };
// Draw the temporary snake using the gradient logic
const tempLength = tempSnake.length;
tempSnake.forEach((part, index) => {
drawSnakePart(part, index, tempLength); // Use the updated drawSnakePart
});
// Draw the food
ctx.fillStyle = FOOD_COLOR;
ctx.strokeStyle = BORDER_COLOR;
ctx.lineWidth = 1;
ctx.fillRect(
tempFood.x * CELL_SIZE,
tempFood.y * CELL_SIZE,
CELL_SIZE,
CELL_SIZE
);
ctx.strokeRect(
tempFood.x * CELL_SIZE,
tempFood.y * CELL_SIZE,
CELL_SIZE,
CELL_SIZE
);
// Reset snake and food state variables for actual game start
snake = [];
food = { x: 0, y: 0 };
startMessageElement.classList.remove("hidden");
gameOverElement.classList.add("hidden");
}
function triggerEasterEgg() {
// Pause the game
gameActive = false;
// Show and play the video
easterEggVideo.classList.remove("hidden");
easterEggVideo.play();
// Hide the video when it ends
easterEggVideo.onended = function () {
easterEggVideo.classList.add("hidden");
// Resume the game
gameActive = true;
};
}
// Function to pause the game
function pauseGame() {
isPaused = true;
pausedMessageElement.classList.remove("hidden");
}
// Function to resume the game
function resumeGame() {
isPaused = false;
pausedMessageElement.classList.add("hidden");
}
// Function to handle space key press
document.addEventListener('keydown', (event) => {
if (event.code === 'Space') {
// is game over or not started, play the game
if (!gameActive &&
(!gameOverElement.classList.contains("hidden") || !startMessageElement.classList.contains("hidden"))
) {
startGame();
} else if (isPaused) {
resumeGame();
} else {
pauseGame();
}
}
});
// --- Event Listeners ---
document.addEventListener("keydown", handleKeyDown);
restartButton.addEventListener("click", startGame);
startButton.addEventListener("click", startGame);
btnUp.addEventListener("click", () => handleTouchControl(0, -1));
btnDown.addEventListener("click", () => handleTouchControl(0, 1));
btnLeft.addEventListener("click", () => handleTouchControl(-1, 0));
btnRight.addEventListener("click", () => handleTouchControl(1, 0));
window.addEventListener("resize", () => {
calculateCanvasSize();
if (!gameActive && !startMessageElement.classList.contains("hidden")) {
showStartMessage(); // Redraw start message with correct elements/colors
} else if (gameActive) {
clearCanvas(); // Clear with white
drawFood();
drawPowerUp(); // Draw the power-up
drawSnake(); // Redraw gradient snake
} else if (!gameOverElement.classList.contains("hidden")) {
clearCanvas(); // Clear with white
}
});
// Initial call
showStartMessage();