pages/secret/snake/game.js

95 lines
2.3 KiB
JavaScript

"use strict";
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
const box = 20;
let snake = [{ x: 9 * box, y: 10 * box }];
let food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box,
};
let score = 0;
let d;
let game;
document.addEventListener("keydown", direction);
function direction(event) {
let key = event.keyCode;
if ((key == 37 || key == 65) && d != "RIGHT") d = "LEFT";
else if ((key == 38 || key == 87) && d != "DOWN") d = "UP";
else if ((key == 39 || key == 68) && d != "LEFT") d = "RIGHT";
else if ((key == 40 || key == 83) && d != "UP") d = "DOWN";
}
function collision(head, array) {
return array.some((part) => head.x == part.x && head.y == part.y);
}
function draw() {
ctx.fillStyle = "#0f380f";
ctx.fillRect(0, 0, cvs.width, cvs.height);
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i == 0 ? "lime" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "black";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d == "LEFT") snakeX -= box;
if (d == "UP") snakeY -= box;
if (d == "RIGHT") snakeX += box;
if (d == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box,
};
} else {
snake.pop();
}
let newHead = { x: snakeX, y: snakeY };
if (
snakeX < 0 ||
snakeX >= cvs.width ||
snakeY < 0 ||
snakeY >= cvs.height ||
collision(newHead, snake)
) {
clearInterval(game);
document.getElementById("restartBtn").style.display = "block";
return;
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 20);
}
function restartGame() {
snake = [{ x: 9 * box, y: 10 * box }];
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box,
};
score = 0;
d = "";
document.getElementById("restartBtn").style.display = "none";
game = setInterval(draw, 150);
}
document.getElementById("restartBtn").addEventListener("click", restartGame);
game = setInterval(draw, 150);