Привет! Ниже представлен полный HTML-файл, который создаёт простую игру, где ИИ управляет кубом, поднимающимся по платформам для сбора монет. После сбора всех монет появляется сообщение о победе и возможность перезапустить игру. Игра адаптирована для мобильных устройств.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Игра с ИИ Кубом</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body, html {
width: 100%;
height: 100%;
overflow: hidden;
background-color: #222;
display: flex;
justify-content: center;
align-items: center;
}
#gameCanvas {
background-color: #333;
border: 2px solid #555;
width: 90vw;
height: 90vh;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.7);
color: #fff;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, sans-serif;
font-size: 2em;
z-index: 2;
display: none;
}
#restartButton {
margin-top: 20px;
padding: 10px 20px;
font-size: 0.5em;
cursor: pointer;
border: none;
background-color: #28a745;
color: #fff;
border-radius: 5px;
}
@media (max-width: 600px) {
#overlay {
font-size: 1.5em;
}
#restartButton {
padding: 8px 16px;
font-size: 0.8em;
}
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<div id="overlay">
<div id="message">Победа!</div>
<button id="restartButton">Перезапустить</button>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const overlay = document.getElementById('overlay');
const message = document.getElementById('message');
const restartButton = document.getElementById('restartButton');
// Установка размера канваса
function resizeCanvas() {
canvas.width = window.innerWidth * 0.9;
canvas.height = window.innerHeight * 0.9;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Игровые объекты
class Cube {
constructor(x, y, size, color) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.vx = 0;
this.vy = 0;
this.speed = 2;
this.jumpStrength = -10;
this.onGround = false;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.size, this.size);
}
update() {
// Гравитация
this.vy += 0.5;
this.x += this.vx;
this.y += this.vy;
// Ограничение по границам
if (this.x < 0) this.x = 0;
if (this.x + this.size > canvas.width) this.x = canvas.width - this.size;
if (this.y + this.size > canvas.height) {
this.y = canvas.height - this.size;
this.vy = 0;
this.onGround = true;
} else {
this.onGround = false;
}
}
}
class Platform {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
class Coin {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.collected = false;
}
draw() {
if (!this.collected) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
}
let player;
let platforms = [];
let coins = [];
let gameOver = false;
function init() {
// Инициализация игрока
player = new Cube(canvas.width / 2 - 15, canvas.height - 60, 30, '#4CAF50');
// Инициализация платформ
platforms = [
new Platform(canvas.width / 2 - 50, canvas.height - 30, 100, 10, '#555'),
new Platform(100, canvas.height - 100, 100, 10, '#555'),
new Platform(canvas.width - 200, canvas.height - 200, 100, 10, '#555'),
new Platform(100, canvas.height - 300, 100, 10, '#555'),
new Platform(canvas.width - 200, canvas.height - 400, 100, 10, '#555'),
new Platform(canvas.width / 2 - 50, canvas.height - 500, 100, 10, '#555'),
];
// Инициализация монет
coins = [
new Coin(canvas.width / 2, canvas.height - 60, 10, '#FFD700'),
new Coin(150, canvas.height - 120, 10, '#FFD700'),
new Coin(canvas.width - 150, canvas.height - 220, 10, '#FFD700'),
new Coin(150, canvas.height - 320, 10, '#FFD700'),
new Coin(canvas.width - 150, canvas.height - 420, 10, '#FFD700'),
new Coin(canvas.width / 2, canvas.height - 520, 10, '#FFD700'),
];
gameOver = false;
overlay.style.display = 'none';
}
init();
// Простая логика ИИ для управления игроком
function aiControl() {
// Найти ближайшую монету
let target = null;
let minDist = Infinity;
for (let coin of coins) {
if (!coin.collected) {
let dist = Math.hypot(coin.x - (player.x + player.size / 2), coin.y - (player.y + player.size));
if (dist < minDist) {
minDist = dist;
target = coin;
}
}
}
if (target) {
// Простая логика движения к цели
if (target.x < player.x + player.size / 2) {
player.vx = -player.speed;
} else {
player.vx = player.speed;
}
// Прыжок, если цель выше
if (target.y < player.y + player.size && player.onGround) {
player.vy = player.jumpStrength;
}
} else {
// Остановиться, если все монеты собраны
player.vx = 0;
if (player.onGround && !gameOver) {
gameOver = true;
showVictory();
}
}
}
function showVictory() {
message.textContent = "Победа!";
overlay.style.display = 'flex';
}
function showDefeat() {
message.textContent = "Поражение!";
overlay.style.display = 'flex';
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Управление ИИ
aiControl();
// Обновление и отрисовка игрока
player.update();
// Проверка коллизий с платформами
for (let platform of platforms) {
if (player.x < platform.x + platform.width &&
player.x + player.size > platform.x &&
player.y + player.size < platform.y + platform.height &&
player.y + player.size + player.vy >= platform.y) {
player.y = platform.y - player.size;
player.vy = 0;
player.onGround = true;
}
}
// Отрисовка платформ
for (let platform of platforms) {
platform.draw();
}
// Отрисовка и проверка монет
for (let coin of coins) {
coin.draw();
if (!coin.collected) {
let dist = Math.hypot(coin.x - (player.x + player.size / 2), coin.y - (player.y + player.size / 2));
if (dist < player.size / 2 + coin.radius) {
coin.collected = true;
}
}
}
// Отрисовка игрока поверх платформ
player.draw();
// Проверка победы
if (coins.every(coin => coin.collected)) {
if (!gameOver) {
showVictory();
}
}
if (!gameOver) {
requestAnimationFrame(update);
}
}
update();
// Обработка кнопки перезапуска
restartButton.addEventListener('click', () => {
init();
update();
});
</script>
</body>
</html>
Описание Кода
-
HTML Структура
<canvas id="gameCanvas"></canvas>: Используется для отрисовки игры.
<div id="overlay">: Накладывается поверх канваса для отображения сообщений о победе и кнопки перезапуска.
-
Стилизация
- Канвас адаптируется под размеры экрана (90% ширины и высоты).
- Оверлей центрируется и становится видимым при окончании игры.
- Кнопка перезапуска стилизована для удобства на мобильных устройствах.
-
JavaScript Логика
-
Адаптивность
- Канвас и элементы интерфейса автоматически подстраиваются под размер экрана.
- Используются медиазапросы для улучшения отображения на мобильных устройствах.
Как Использовать
-
Сохраните Код: Скопируйте приведённый выше код и сохраните его в файл с расширением .html, например game.html.
-
Запустите в Браузере: Откройте сохранённый файл в любом современном веб-браузере (Chrome, Firefox, Edge и т.д.).
-
Игровой Процесс:
- ИИ автоматически управляет кубом, поднимаясь по платформам и собирая монеты.
- После сбора всех монет появится сообщение о победе.
- Нажмите кнопку "Перезапустить" для повторной игры.
Возможные Улучшения
- Сложность ИИ: Улучшить логику ИИ для более эффективного сбора монет и избегания препятствий.
- Добавление Звуков: Включить звуковые эффекты для действий в игре.
- Разные Уровни: Создать несколько уровней с увеличивающейся сложностью.
- Анимации: Добавить анимации для более плавной и привлекательной графики.
Надеюсь, эта игра принесёт вам удовольствие! Если у вас есть вопросы или требуется дополнительная функциональность, не стесняйтесь спрашивать.