const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Scale for the grid
const box = 20;
// Game variables
let snake = [{ x: 10 * box, y: 10 * box }];
let direction = 'RIGHT';
let food = {
x: Math.floor(Math.random() * (canvas.width / box)) * box,
y: Math.floor(Math.random() * (canvas.height / box)) * box
};
let score = 0;
// Event listener for keyboard controls
document.addEventListener('keydown', changeDirection);
function changeDirection(event) {
if(event.keyCode === 37 && direction !== 'RIGHT') {
direction = 'LEFT';
} else if(event.keyCode === 38 && direction !== 'DOWN') {
direction = 'UP';
} else if(event.keyCode === 39 && direction !== 'LEFT') {
direction = 'RIGHT';
} else if(event.keyCode === 40 && direction !== 'UP') {
direction = 'DOWN';
}
}
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'lightgreen';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// Draw the food
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
// Current head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Direction movement
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
// Check for food collision
if (snakeX === food.x && snakeY === food.y) {
score++;
food = {
x: Math.floor(Math.random() * (canvas.width / box)) * box,
y: Math.floor(Math.random() * (canvas.height / box)) * box
};
} else {
// Remove the tail
snake.pop();
}
// Add new head
const newHead = { x: snakeX, y: snakeY };
// Game over conditions
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert('Game Over! Your score: ' + score);
}
snake.unshift(newHead);
}
// Check for collision with itself
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
// Refresh rate
const game = setInterval(draw, 100);