Вот пример полного HTML-кода для реализации игры "Змейка", используя элемент <canvas> и JavaScript, без использования alert для сообщений:
<!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;
margin: 0;
background-color: #f4f4f4;
}
canvas {
border: 2px solid #000;
background-color: #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20; // Size of one segment of the snake and one unit of the grid
let snake = [{x: 10 * box, y: 10 * box}]; // Initial position of snake
let direction = 'RIGHT'; // Initial movement direction
let food = {
x: Math.floor(Math.random() * canvas.width / box) * box,
y: Math.floor(Math.random() * canvas.height / box) * box
};
let score = 0;
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() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(let segment of snake) {
ctx.fillStyle = 'green';
ctx.fillRect(segment.x, segment.y, box, box);
}
ctx.fillStyle = 'red';
ctx.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() * canvas.width / box) * box,
y: Math.floor(Math.random() * canvas.height / box) * box
};
score++;
} else {
snake.pop();
}
const newHead = {x: snakeX, y: snakeY};
if(snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Game Over. Score: ' + score, canvas.width / 4, canvas.height / 2);
return;
}
snake.unshift(newHead);
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, box, box);
}
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;
}
let game = setInterval(draw, 100);
</script>
</body>
</html>
Этот код создаёт простую игру "Змейка" с функцией управления через клавиатуру и отображением счёта на экране. Игра заканчивается, если змейка сталкивается с границами или самой собой. Вместо alert для уведомления об окончании игры используется текст на экране.