Snake Game
Use the arrow keys to move. Eat the red squares. Don’t hit the wall or yourself.
Score: 0
const canvas = document.getElementById(“gameCanvas”);
const ctx = canvas.getContext(“2d”);
const scoreDisplay = document.getElementById(“score”);
const box = 20;
let snake;
let food;
let direction;
let score;
let game;
function startGame() {
snake = [{ x: 200, y: 200 }];
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
direction = null;
score = 0;
scoreDisplay.textContent = “Score: 0”;
clearInterval(game);
game = setInterval(drawGame, 120);
}
document.addEventListener(“keydown”, changeDirection);
function changeDirection(event) {
if (event.key === “ArrowLeft” && direction !== “RIGHT”) {
direction = “LEFT”;
} else if (event.key === “ArrowUp” && direction !== “DOWN”) {
direction = “UP”;
} else if (event.key === “ArrowRight” && direction !== “LEFT”) {
direction = “RIGHT”;
} else if (event.key === “ArrowDown” && direction !== “UP”) {
direction = “DOWN”;
}
}
function drawGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "#16a34a" : "#22c55e";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "#ffffff";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// Draw food
ctx.fillStyle = "#dc2626";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === "LEFT") snakeX -= box;
if (direction === "UP") snakeY -= box;
if (direction === "RIGHT") snakeX += box;
if (direction === "DOWN") snakeY += box;
// Eat food
if (snakeX === food.x && snakeY === food.y) {
score++;
scoreDisplay.textContent = "Score: " + score;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
const newHead = { x: snakeX, y: snakeY };
// Collision detection
if (
snakeX < 0 ||
snakeY = canvas.width ||
snakeY >= canvas.height ||
collision(newHead, snake)
) {
clearInterval(game);
ctx.fillStyle = “rgba(0, 0, 0, 0.75)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = “white”;
ctx.font = “32px Arial”;
ctx.fillText(“Game Over”, 115, 190);
ctx.font = “20px Arial”;
ctx.fillText(“Final Score: ” + score, 140, 225);
return;
}
snake.unshift(newHead);
}
function collision(head, body) {
for (let i = 0; i < body.length; i++) {
if (head.x === body[i].x && head.y === body[i].y) {
return true;
}
}
return false;
}
function restartGame() {
startGame();
}
startGame();