const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20; // Size of the snake and food
let snake = [{ x: 9 * box, y: 9 * box }];
let direction = 'RIGHT';
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
document.addEventListener('keydown', directionControl);
function directionControl(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 drawGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
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);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
// Old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Direction control
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
// Check for collision with food
if (snakeX === food.x && snakeY === food.y) {
// Create new food
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * 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!');
}
snake.unshift(newHead);
}
// Collision detection
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;
}
// Call drawGame every 100 milliseconds
const game = setInterval(drawGame, 100);