gpt-4-turbo-2024-04-09· OpenAI
WildChat-4.8M (AI2)
Напиши HTML код для игры змейка, который я смогу вставить в блакнот и играть.
- User
Напиши HTML код для игры змейка, который я смогу вставить в блакнот и играть.
- Assistant
Напиши HTML код для игры змейка, который я смогу вставить в блакнот и играть.
Создание игры "Змейка" может быть весьма увлекательным занятием. Ниже приведен простой пример HTML и JavaScript, который реализует эту игру. Вы можете скопировать код, вставить его в файл с расширением .html созданный в блокноте и открыть этот файл в вашем веб-браузере.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Змейка</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f4f4f4; }
canvas { background: #000; }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let speed = 7;
let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;
let headX = 10;
let headY = 10;
const snakeParts = [];
let tailLength = 2;
let appleX = 5;
let appleY = 5;
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
// Игровой цикл
function drawGame() {
changeSnakePosition();
let result = isGameOver();
if (result) {
return;
}
clearScreen();
checkAppleCollision();
drawApple();
drawSnake();
drawScore();
setTimeout(drawGame, 1000 / speed);
}
function isGameOver() {
let gameOver = false;
if (yVelocity === 0 && xVelocity === 0) {
return false;
}
// Столкновения со стенами
if (headX < 0 || headX === tileCount || headY < 0 || headY === tileCount) {
gameOver = true;
}
// Столкновение с самим собой
for(let i=0; i < snakeParts.length; i++) {
let part = snakeParts[i];
if (part.x === headX && part.y === headY) {
gameOver = true;
break;
}
}
if (gameOver) {
ctx.fillStyle = "white";
ctx.font = "50px Verdana";
ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
}
return gameOver;
}
function drawScore() {
ctx.fillStyle = "white";
ctx.font = "10px Verdana";
ctx.fillText("Score " + score, canvas.width - 50, 10);
}
function clearScreen() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = "green";
for(let i = 0; i < snakeParts.length; i++) {
let part = snakeParts[i];
ctx.fillRect(part.x * tileCount, part.y * tileCount, tileSize, tileSize);
}
snakeParts.push({ x: headX, y: headY });
while (snakeParts.length > tailLength) {
snakeParts.shift();
}
ctx.fillStyle = "orange";
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize);
}
function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}
function drawApple() {
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}
function checkAppleCollision() {
if (appleX === headX && appleY === headY) {
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
tailLength++;
score++;
}
}
document.body.addEventListener("keydown", keyDown);
function keyDown(event) {
// Вверх
if (event.keyCode == 38) {
if (yVelocity == 1) return;
yVelocity = -1;
xVelocity = 0;
}
// Вниз
if (event.keyCode == 40) {
if (yVelocity == -1) return;
yVelocity = 1;
xVelocity = 0;
}
// Влево
if (event.keyCode == 37) {
if (xVelocity == 1) return;
xVelocity = -1;
yVelocity = 0;
}
// Вправо
if (event.keyCode == 39) {
if (xVelocity == -1) return;
xVelocity = 1;
yVelocity = 0;
}
}
drawGame();
</script>
</body>
</html>
Этот код создает игру "Змейка", в которой вы управляете змейкой с помощью клавиш стрелок. Змейка должна собирать красные яблоки, при этом она увеличивается в размерах. Игра заканчивается, если змейка столкнётся с собственным хвостом или границами игрового поля.
Not yet included in a published release.