<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000;
}
canvas {
border: 1px solid #fff;
}
</style>
</head>
<body>
<canvas id="snake" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('snake');
const context = canvas.getContext('2d');
const box = 20;
let snake = [{x: 9 * box, y: 9 * box}];
let direction;
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 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;
}
function draw() {
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < snake.length; i++) {
context.fillStyle = (i === 0) ? 'green' : 'white';
context.fillRect(snake[i].x, snake[i].y, box, box);
context.strokeStyle = 'black';
context.strokeRect(snake[i].x, snake[i].y, box, box);
}
context.fillStyle = 'red';
context.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;
if(snakeX === food.x && snakeY === food.y) {
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
let newHead = {x: snakeX, y: snakeY};
if(snakeX < 0 || snakeY < 0 || snakeX > (canvas.width - box) || snakeY > (canvas.height - box) || collision(newHead, snake)) {
clearInterval(game);
alert("Game Over");
}
snake.unshift(newHead);
}
let game = setInterval(draw, 100);
</script>
</body>
</html>
Feel free to improve upon this code by adding features like scoring, levels, or increasing the speed of the snake!