var canvas = document.getElementById("game-board");
var ctx = canvas.getContext("2d");
// Variables
var snake = [{ x: 10, y: 10 }];
var direction = "right";
var food = { x: 0, y: 0 };
var score = 0;
var gameOver = false;
// Functions
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the snake
ctx.fillStyle = "green";
for (var i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x * 10, snake[i].y * 10, 10, 10);
}
// Draw the food
ctx.fillStyle = "red";
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
// Update the score
document.getElementById("score").textContent = score;
}
function update() {
// Move the snake
var head = { x: snake[0].x, y: snake[0].y };
if (direction === "right") head.x++;
if (direction === "left") head.x--;
if (direction === "up") head.y--;
if (direction === "down") head.y++;
snake.unshift(head);
// Check if the snake has collided with the walls or itself
if (head.x < 0 || head.x >= canvas.width/10 || head.y < 0 || head.y >= canvas.height/10) {
clearInterval(gameLoop);
alert("Game Over!");
}
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
clearInterval(gameLoop);
alert("Game Over!");
}
}
// Check if the snake has eaten the food
if (head.x === food.x && head.y === food.y) {
score++;
generateFood();
} else {
snake.pop();
}
}
function generateFood() {
var x = Math.floor(Math.random() * canvas.width / 10);
var y = Math.floor(Math.random() * canvas.height / 10);
food = { x: x, y: y };
}
function resetGame() {
snake = [{ x: 10, y: 10 }];
direction = "right";
food = { x: 0, y: 0 };
score = 0;
gameOver = false;
}
function game() {
update();
draw();
if (gameOver) {
clearInterval(gameLoop);
alert("Game Over!");
}
}
document.addEventListener("keydown", function (event) {
if (event.keyCode === 37 && direction !== "right") direction = "left";
if (event.keyCode === 38 && direction !== "down") direction = "up";
if (event.keyCode === 39 && direction !== "left") direction = "right";
if (event.keyCode === 40 && direction !== "up") direction = "down";
});
generateFood();
gameLoop = setInterval(game, 100);
function resetGame() {
snake = [{ x: 10, y: 10 }];
direction = "right";
food = { x: 0, y: 0 };
score = 0;
gameOver = false;
}
document.getElementById("restart-button").addEventListener("click", function () {
resetGame();
generateFood();
gameLoop = setInterval(game, 100);
});