gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Как сделать змейку на хтмл
- User
Как сделать змейку на хтмл
- Assistant
Как сделать змейку на хтмл
Создание простой игры "Змейка" с использованием HTML, CSS и JavaScript — интересный проект. Вот базовый пример, который поможет вам начать:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Змейка</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Игра: Змейка</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
canvas {
border: 1px solid #000;
}
const canvas = document.getElementById("gameCanvas");
const ctx = 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 }; // начальная позиция пищи
let score = 0;
// Отображение змейки и пищи
function draw() {
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);
// Текущий счет
ctx.fillStyle = "black";
ctx.fillText("Счет: " + score, box, box);
}
// Управление движением змейки
document.addEventListener("keydown", directionControl);
function directionControl(event) {
if (event.key === "ArrowLeft" && direction !== "RIGHT") {
direction = "LEFT";
} else if (event.key === "ArrowUp" && direction !== "DOWN") {
direction = "UP";
} else if (event.key === "ArrowRight" && direction !== "LEFT") {
direction = "RIGHT";
} else if (event.key === "ArrowDown" && direction !== "UP") {
direction = "DOWN";
}
}
// Основной игровой цикл
function game() {
if (!direction) return;
// Текущие координаты головки змейки
let headX = snake[0].x;
let headY = snake[0].y;
// Изменение позиции в зависимости от направления
if (direction === "LEFT") headX -= box;
if (direction === "UP") headY -= box;
if (direction === "RIGHT") headX += box;
if (direction === "DOWN") headY += box;
// Проверка на столкновение с пищей
if (headX === food.x && headY === food.y) {
score++;
food = { x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box };
} else {
snake.pop(); // Удаляем последний элемент змейки
}
// Добавление новой головки змейки
let newHead = { x: headX, y: headY };
// Проверка на столкновение со стенами или самой собой
if (
headX < 0 || headY < 0 ||
headX >= canvas.width || headY >= canvas.height ||
collision(newHead, snake)
) {
clearInterval(gameInterval);
alert("Игра окончена! Счет: " + score);
return;
}
snake.unshift(newHead); // Добавляем новую головку
draw(); // Отображаем обновленное состояние
}
// Проверка столкновения с самой собой
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;
}
// Запуск игрового цикла
const gameInterval = setInterval(game, 100);
draw();
<canvas>, на котором будет рисоваться игра.index.html, style.css и script.js.index.html в браузере, чтобы начать играть!Надеюсь, этот код поможет вам создать свою собственную игру "Змейка"!
Not yet included in a published release.