Here's a simple HTML game about snake:
<!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>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
#food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<h1>Snake Game</h1>
<div id="game-board">
</div>
<script>
let snake = [{x: 200, y: 200}];
let direction = 'right';
let food = {x: 100, y: 100};
let score = 0;
const gameBoard = document.getElementById('game-board');
function drawSnake() {
gameBoard.innerHTML = '';
snake.forEach(segment => {
const snakeElement = document.createElement('div');
snakeElement.style.left = segment.x + 'px';
snakeElement.style.top = segment.y + 'px';
snakeElement.classList.add('snake');
gameBoard.appendChild(snakeElement);
});
}
function generateFood() {
const x = Math.floor(Math.random() * 20) * 20;
const y = Math.floor(Math.random() * 20) * 20;
food = {x, y};
const foodElement = document.createElement('div');
foodElement.style.left = x + 'px';
foodElement.style.top = y + 'px';
foodElement.id = 'food';
gameBoard.appendChild(foodElement);
}
function move() {
const head = { ...snake[0] };
switch (direction) {
case 'up':
head.y -= 20;
break;
case 'down':
head.y += 20;
break;
case 'left':
head.x -= 20;
break;
case 'right':
head.x += 20;
break;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score++;
generateFood();
} else {
snake.pop();
}
drawSnake();
}
generateFood();
setInterval(move, 200);
document.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
direction = 'up';
break;
case 'ArrowDown':
direction = 'down';
break;
case 'ArrowLeft':
direction = 'left';
break;
case 'ArrowRight':
direction = 'right';
break;
}
});
</script>
</body>
</html>
This code creates a simple snake game where the player controls the snake using arrow keys. The snake moves continuously, and the player must navigate it to eat the food (red square) and grow longer. The game keeps track of the player's score, which increases each time the snake eats the food. Players can control the direction of the snake using the arrow keys.