canvas {
border: 1px solid black;
}
Snake Game in JavaScript
const canvas = document.getElementById(‘gameCanvas’);
const ctx = canvas.getContext(‘2d’);
const boxSize = 10;
let snake = [{ x: 10, y: 10 }];
let food = { x: 20, y: 20 };
let direction = ‘right’;
function drawSnake() {
ctx.fillStyle = ‘green’;
for (let i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x * boxSize, snake[i].y * boxSize, boxSize, boxSize);
}
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x * boxSize, food.y * boxSize, boxSize, boxSize);
}
function moveSnake() {
let head = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case 'up':
head.y -= 1;
break;
case 'down':
head.y += 1;
break;
case 'left':
head.x -= 1;
break;
case 'right':
head.x += 1;
break;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
createFood();
} else {
snake.pop();
}
}
function createFood() {
food.x = Math.floor(Math.random() * (canvas.width / boxSize));
food.y = Math.floor(Math.random() * (canvas.height / boxSize));
}
function checkCollision() {
if (snake[0].x = canvas.width / boxSize ||
snake[0].y = canvas.height / boxSize) {
clearInterval(gameInterval);
alert(‘Game over!’);
}
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
moveSnake();
checkCollision();
}
document.addEventListener(‘keydown’, function(event) {
switch (event.key) {
case ‘ArrowUp’:
direction = ‘up’;
break;
case ‘ArrowDown’:
direction = ‘down’;
break;
case ‘ArrowLeft’:
direction = ‘left’;
break;
case ‘ArrowRight’:
direction = ‘right’;
break;
}
});
createFood();
const gameInterval = setInterval(gameLoop, 100);