<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>Squirrel…
- Usercode
- Assistant
// Переменные игры
let koala = { x: 280, y: 180, width: 40, height: 40, speed: 5 };
let strawberries = [];
let squirrel = null;
let keysPressed = {};
let gameOver = false;
let gameWon = false;
let gameStart = false;
let timer = 0;
let gameTime = 0;
// Цвета
const colors = {
background: '#000000',
koala: '#00FF00',
strawberry: '#FF0000',
squirrel: '#FFFF00',
text: '#FFFFFF'
};
// Обработчики клавиатуры
document.addEventListener('keydown', function(e) {
keysPressed[e.key] = true;
});
document.addEventListener('keyup', function(e) {
keysPressed[e.key] = false;
});
// Обработчики сенсорных кнопок
const touchControls = document.getElementById('touchControls');
const upBtn = document.getElementById('upBtn');
const downBtn = document.getElementById('downBtn');
const leftBtn = document.getElementById('leftBtn');
const rightBtn = document.getElementById('rightBtn');
function startGame() {
document.getElementById('instructions').style.display = 'none';
touchControls.style.display = 'flex';
gameStart = true;
gameOver = false;
gameWon = false;
timer = 0;
gameTime = 0;
koala.x = 280;
koala.y = 180;
strawberries = [];
squirrel = null;
requestAnimationFrame(gameLoop);
}
function gameLoop(timestamp) {
if (!gameStart) return;
update();
draw();
if (gameOver || gameWon) {
setTimeout(startGame, 2000); // Перезапуск после 2 секунд
return;
}
requestAnimationFrame(gameLoop);
}
function update() {
// Обновление таймера
timer += 1/60;
gameTime += 1/60;
// Движение коалы
if (keysPressed['ArrowUp'] || keysPressed['Up']) {
if (koala.y > 0) koala.y -= koala.speed;
}
if (keysPressed['ArrowDown'] || keysPressed['Down']) {
if (koala.y + koala.height < canvas.height) koala.y += koala.speed;
}
if (keysPressed['ArrowLeft'] || keysPressed['Left']) {
if (koala.x > 0) koala.x -= koala.speed;
}
if (keysPressed['ArrowRight'] || keysPressed['Right']) {
if (koala.x + koala.width < canvas.width) koala.x += koala.speed;
}
// Движение с помощью сенсорных кнопок
if (touchKeys['up']) {
if (koala.y > 0) koala.y -= koala.speed;
}
if (touchKeys['down']) {
if (koala.y + koala.height < canvas.height) koala.y += koala.speed;
}
if (touchKeys['left']) {
if (koala.x > 0) koala.x -= koala.speed;
}
if (touchKeys['right']) {
if (koala.x + koala.width < canvas.width) koala.x += koala.speed;
}
// Появление клубники каждую секунду
if (Math.floor(timer) >= 1) {
spawnStrawberry();
timer = 0;
}
// Обновление клубники
strawberries.forEach(strawberry => {
strawberry.x += strawberry.vx;
strawberry.y += strawberry.vy;
// Отскок от стен
if (strawberry.x <= 0 || strawberry.x + strawberry.width >= canvas.width) {
strawberry.vx *= -1;
}
if (strawberry.y <= 0 || strawberry.y + strawberry.height >= canvas.height) {
strawberry.vy *= -1;
}
// Проверка столкновений с коалой
if (checkCollision(koala, strawberry)) {
gameOver = true;
}
});
// Появление белки через 3 секунды
if (!squirrel && gameTime >= 3) {
spawnSquirrel();
}
// Обновление белки
if (squirrel) {
squirrel.x += squirrel.vx;
squirrel.y += squirrel.vy;
// Отскок от стен
if (squirrel.x <= 0 || squirrel.x + squirrel.width >= canvas.width) {
squirrel.vx *= -1;
}
if (squirrel.y <= 0 || squirrel.y + squirrel.height >= canvas.height) {
squirrel.vy *= -1;
}
// Проверка столкновений с коалой
if (checkCollision(koala, squirrel)) {
gameWon = true;
}
}
}
function draw() {
// Очистка холста
ctx.fillStyle = colors.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Текст "openai"
ctx.fillStyle = colors.text;
ctx.font = '20px Courier New';
ctx.fillText('openai', canvas.width / 2 - 30, 30);
// Таймер
ctx.fillText('Время: ' + Math.floor(gameTime) + 'с', 10, 30);
// Отрисовка коалы
drawKoala(koala.x, koala.y);
// Отрисовка клубники
strawberries.forEach(strawberry => {
drawStrawberry(strawberry.x, strawberry.y);
});
// Отрисовка белки
if (squirrel) {
drawSquirrel(squirrel.x, squirrel.y);
}
// Сообщения о выигрыше или проигрыше
if (gameOver) {
ctx.fillStyle = colors.text;
ctx.font = '40px Courier New';
ctx.fillText('Вы проиграли!', canvas.width / 2 - 110, canvas.height / 2);
}
if (gameWon) {
ctx.fillStyle = colors.text;
ctx.font = '40px Courier New';
ctx.fillText('Вы выиграли!', canvas.width / 2 - 110, canvas.height / 2);
}
}
function spawnStrawberry() {
let strawberry = {
x: Math.random() * (canvas.width - 40),
y: Math.random() * (canvas.height - 40),
width: 40,
height: 40,
vx: (Math.random() < 0.5 ? -1 : 1) * 2,
vy: (Math.random() < 0.5 ? -1 : 1) * 2
};
strawberries.push(strawberry);
}
function spawnSquirrel() {
squirrel = {
x: Math.random() * (canvas.width - 40),
y: Math.random() * (canvas.height - 40),
width: 40,
height: 40,
vx: (Math.random() < 0.5 ? -1 : 1) * 3,
vy: (Math.random() < 0.5 ? -1 : 1) * 3
};
}
function checkCollision(a, b) {
return a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y;
}
function drawKoala(x, y) {
ctx.fillStyle = colors.koala;
ctx.fillRect(x, y, 40, 40);
// Лицо коалы
ctx.fillStyle = colors.background;
ctx.fillRect(x + 10, y + 10, 5, 5);
ctx.fillRect(x + 25, y + 10, 5, 5);
ctx.fillRect(x + 15, y + 25, 10, 5);
}
function drawStrawberry(x, y) {
ctx.fillStyle = colors.strawberry;
ctx.beginPath();
ctx.moveTo(x + 20, y);
ctx.lineTo(x + 40, y + 20);
ctx.lineTo(x + 20, y + 40);
ctx.lineTo(x, y + 20);
ctx.closePath();
ctx.fill();
}
function drawSquirrel(x, y) {
ctx.fillStyle = colors.squirrel;
ctx.fillRect(x, y, 40, 40);
// Хвост белки
ctx.fillStyle = colors.background;
ctx.fillRect(x + 25, y + 10, 5, 20);
}
// Переменные для сенсорного управления
let touchKeys = {
up: false,
down: false,
left: false,
right: false
};
// Обработчики событий для сенсорных кнопок
upBtn.addEventListener('touchstart', function(e) {
e.preventDefault();
touchKeys.up = true;
});
upBtn.addEventListener('touchend', function(e) {
e.preventDefault();
touchKeys.up = false;
});
downBtn.addEventListener('touchstart', function(e) {
e.preventDefault();
touchKeys.down = true;
});
downBtn.addEventListener('touchend', function(e) {
e.preventDefault();
touchKeys.down = false;
});
leftBtn.addEventListener('touchstart', function(e) {
e.preventDefault();
touchKeys.left = true;
});
leftBtn.addEventListener('touchend', function(e) {
e.preventDefault();
touchKeys.left = false;
});
rightBtn.addEventListener('touchstart', function(e) {
e.preventDefault();
touchKeys.right = true;
});
rightBtn.addEventListener('touchend', function(e) {
e.preventDefault();
touchKeys.right = false;
});
// Свайп-управление
let touchStartX = null;
let touchStartY = null;
canvas.addEventListener('touchstart', function(e) {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchmove', function(e) {
if (!touchStartX || !touchStartY) return;
const touch = e.touches[0];
let touchEndX = touch.clientX;
let touchEndY = touch.clientY;
let diffX = touchEndX - touchStartX;
let diffY = touchEndY - touchStartY;
if (Math.abs(diffX) > Math.abs(diffY)) {
// Горизонтальный свайп
if (diffX > 30) {
// Свайп вправо
touchKeys.right = true;
touchKeys.left = false;
} else if (diffX < -30) {
// Свайп влево
touchKeys.left = true;
touchKeys.right = false;
}
} else {
// Вертикальный свайп
if (diffY > 30) {
// Свайп вниз
touchKeys.down = true;
touchKeys.up = false;
} else if (diffY < -30) {
// Свайп вверх
touchKeys.up = true;
touchKeys.down = false;
}
}
// Сбрасываем начальные координаты, чтобы не было бесконечного движения
touchStartX = null;
touchStartY = null;
});
canvas.addEventListener('touchend', function(e) {
touchKeys.up = false;
touchKeys.down = false;
touchKeys.left = false;
touchKeys.right = false;
});
// Предотвращаем прокрутку страницы при свайпе в игре
document.body.addEventListener('touchmove', function(e) { e.preventDefault(); }, { passive: false });
</script>
Ниже представлен улучшенный вариант игры "Squirrel Finder" с улучшенной логикой и проверкой:
Основные улучшения:
Улучшенное управление состоянием игры: Добавлены различные состояния игры ('start', 'playing', 'gameOver', 'gameWon') для лучшего управления игровым процессом.
Предотвращение появления объектов на игроке: При генерации клубники и белки теперь проверяется, чтобы они не появлялись на позиции коалы.
Улучшенная обработка окончания игры: Вместо автоматического перезапуска игры через 2 секунды, теперь отображается сообщение с кнопкой "Играть снова", позволяя игроку самостоятельно решать, когда начать новую игру.
Оптимизирована обработка событий: Улучшены обработчики клавиатуры и сенсорных кнопок для предотвращения конфликтов и обеспечения более плавного управления.
Код структурирован и оптимизирован: Логика игры организована в функции и объекты для улучшения читаемости и удобства поддержки кода.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Squirrel Finder</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000000;
color: #FFFFFF;
font-family: 'Courier New', Courier, monospace;
}
#gameCanvas {
display: block;
margin: 0 auto;
background-color: #000000;
border: 1px solid #FFFFFF;
touch-action: none;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
color: #FFFFFF;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#overlay button {
margin-top: 20px;
padding: 10px 20px;
background-color: #FFFFFF;
color: #000000;
border: none;
cursor: pointer;
font-size: 16px;
}
#overlay button:hover {
background-color: #CCCCCC;
}
/* Сенсорные кнопки */
#touchControls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
justify-content: center;
width: 100%;
max-width: 400px;
}
.touch-button {
background-color: rgba(255, 255, 255, 0.2);
color: #FFFFFF;
border: 1px solid #FFFFFF;
width: 60px;
height: 60px;
margin: 5px;
font-size: 30px;
text-align: center;
line-height: 60px;
user-select: none;
touch-action: none;
}
/* Адаптивность */
@media screen and (max-width: 600px) {
#gameCanvas {
width: 100%;
height: auto;
}
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="600" height="400"></canvas>
<!-- Оверлей для сообщений и кнопок -->
<div id="overlay">
<h1>Squirrel Finder</h1>
<p>Вы — коала. Используйте клавиши со стрелками или сенсорные кнопки для перемещения.</p>
<p>Каждую секунду появляется клубника, которая движется по экрану.</p>
<p>Если клубника коснётся вас, вы проиграете.</p>
<p>Через три секунды появится белка, которая также будет двигаться по экрану.</p>
<p>Если вы коснётесь белки, вы выиграете!</p>
<button onclick="startGame()">Начать игру</button>
</div>
<!-- Сенсорные кнопки -->
<div id="touchControls" style="display: none;">
<div class="touch-button" id="leftBtn">◄</div>
<div class="touch-button" id="upBtn">▲</div>
<div class="touch-button" id="downBtn">▼</div>
<div class="touch-button" id="rightBtn">►</div>
</div>
<script>
// Объект игры
const Game = {
canvas: document.getElementById('gameCanvas'),
ctx: null,
width: 600,
height: 400,
koala: null,
strawberries: [],
squirrel: null,
keysPressed: {},
touchKeys: { up: false, down: false, left: false, right: false },
gameState: 'start', // 'start', 'playing', 'gameOver', 'gameWon'
timer: 0,
gameTime: 0,
colors: {
background: '#000000',
koala: '#00FF00',
strawberry: '#FF0000',
squirrel: '#FFFF00',
text: '#FFFFFF'
},
init: function() {
this.ctx = this.canvas.getContext('2d');
this.width = this.canvas.width;
this.height = this.canvas.height;
this.bindEvents();
this.showOverlay('start');
this.loop();
},
start: function() {
this.gameState = 'playing';
this.timer = 0;
this.gameTime = 0;
this.strawberries = [];
this.squirrel = null;
this.koala = new Player(280, 180, 40, 40, 5);
this.hideOverlay();
document.getElementById('touchControls').style.display = 'flex';
},
gameOver: function(win) {
this.gameState = win ? 'gameWon' : 'gameOver';
this.showOverlay(this.gameState);
document.getElementById('touchControls').style.display = 'none';
},
loop: function() {
requestAnimationFrame(() => this.loop());
if (this.gameState === 'playing') {
this.update();
this.draw();
}
},
update: function() {
// Обновление таймеров
this.timer += 1 / 60;
this.gameTime += 1 / 60;
// Движение коалы
this.koala.update(this.keysPressed, this.touchKeys, this.width, this.height);
// Появление клубники каждую секунду
if (Math.floor(this.timer) >= 1) {
this.spawnStrawberry();
this.timer = 0;
}
// Обновление клубники
this.strawberries.forEach(strawberry => {
strawberry.update(this.width, this.height);
if (strawberry.checkCollision(this.koala)) {
this.gameOver(false);
}
});
// Появление белки через 3 секунды
if (!this.squirrel && this.gameTime >= 3) {
this.spawnSquirrel();
}
// Обновление белки
if (this.squirrel) {
this.squirrel.update(this.width, this.height);
if (this.squirrel.checkCollision(this.koala)) {
this.gameOver(true);
}
}
},
draw: function() {
// Очистка холста
this.ctx.fillStyle = this.colors.background;
this.ctx.fillRect(0, 0, this.width, this.height);
// Текст "openai"
this.ctx.fillStyle = this.colors.text;
this.ctx.font = '20px Courier New';
this.ctx.fillText('openai', this.width / 2 - 30, 30);
// Таймер
this.ctx.fillText('Время: ' + Math.floor(this.gameTime) + 'с', 10, 30);
// Отрисовка коалы
this.koala.draw(this.ctx);
// Отрисовка клубники
this.strawberries.forEach(strawberry => {
strawberry.draw(this.ctx);
});
// Отрисовка белки
if (this.squirrel) {
this.squirrel.draw(this.ctx);
}
},
spawnStrawberry: function() {
let strawberry = new Enemy('strawberry', this.colors.strawberry, 40, 40, 2);
this.positionEntity(strawberry);
this.strawberries.push(strawberry);
},
spawnSquirrel: function() {
this.squirrel = new Enemy('squirrel', this.colors.squirrel, 40, 40, 3);
this.positionEntity(this.squirrel);
},
positionEntity: function(entity) {
do {
entity.x = Math.random() * (this.width - entity.width);
entity.y = Math.random() * (this.height - entity.height);
} while (entity.checkCollision(this.koala));
},
bindEvents: function() {
// Клавиатура
document.addEventListener('keydown', e => {
this.keysPressed[e.key] = true;
});
document.addEventListener('keyup', e => {
this.keysPressed[e.key] = false;
});
// Сенсорные кнопки
const upBtn = document.getElementById('upBtn');
const downBtn = document.getElementById('downBtn');
const leftBtn = document.getElementById('leftBtn');
const rightBtn = document.getElementById('rightBtn');
const touchStart = (key) => (e) => {
e.preventDefault();
this.touchKeys[key] = true;
};
const touchEnd = (key) => (e) => {
e.preventDefault();
this.touchKeys[key] = false;
};
upBtn.addEventListener('touchstart', touchStart('up'));
upBtn.addEventListener('touchend', touchEnd('up'));
downBtn.addEventListener('touchstart', touchStart('down'));
downBtn.addEventListener('touchend', touchEnd('down'));
leftBtn.addEventListener('touchstart', touchStart('left'));
leftBtn.addEventListener('touchend', touchEnd('left'));
rightBtn.addEventListener('touchstart', touchStart('right'));
rightBtn.addEventListener('touchend', touchEnd('right'));
// Предотвращение событий жестов на сенсорных кнопках
[upBtn, downBtn, leftBtn, rightBtn].forEach(btn => {
btn.addEventListener('touchmove', e => e.preventDefault());
});
},
showOverlay: function(state) {
const overlay = document.getElementById('overlay');
overlay.style.display = 'flex';
const title = overlay.querySelector('h1');
const message = overlay.querySelectorAll('p');
const button = overlay.querySelector('button');
if (state === 'start') {
title.textContent = 'Squirrel Finder';
button.textContent = 'Начать игру';
button.onclick = () => this.start();
} else if (state === 'gameOver') {
title.textContent = 'Вы проиграли!';
message.forEach(p => p.style.display = 'none');
button.textContent = 'Играть снова';
button.onclick = () => this.start();
} else if (state === 'gameWon') {
title.textContent = 'Вы выиграли!';
message.forEach(p => p.style.display = 'none');
button.textContent = 'Играть снова';
button.onclick = () => this.start();
}
},
hideOverlay: function() {
const overlay = document.getElementById('overlay');
overlay.style.display = 'none';
}
};
// Класс игрока (коала)
class Player {
constructor(x, y, width, height, speed) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
this.color = Game.colors.koala;
}
update(keysPressed, touchKeys, maxWidth, maxHeight) {
if (keysPressed['ArrowUp'] || keysPressed['Up'] || touchKeys.up) {
if (this.y > 0) this.y -= this.speed;
}
if (keysPressed['ArrowDown'] || keysPressed['Down'] || touchKeys.down) {
if (this.y + this.height < maxHeight) this.y += this.speed;
}
if (keysPressed['ArrowLeft'] || keysPressed['Left'] || touchKeys.left) {
if (this.x > 0) this.x -= this.speed;
}
if (keysPressed['ArrowRight'] || keysPressed['Right'] || touchKeys.right) {
if (this.x + this.width < maxWidth) this.x += this.speed;
}
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
// Лицо коалы
ctx.fillStyle = Game.colors.background;
ctx.fillRect(this.x + 10, this.y + 10, 5, 5);
ctx.fillRect(this.x + 25, this.y + 10, 5, 5);
ctx.fillRect(this.x + 15, this.y + 25, 10, 5);
}
}
// Класс врага (клубника и белка)
class Enemy {
constructor(type, color, width, height, speed) {
this.type = type;
this.color = color;
this.width = width;
this.height = height;
this.speed = speed;
this.x = 0;
this.y = 0;
this.vx = (Math.random() < 0.5 ? -1 : 1) * speed;
this.vy = (Math.random() < 0.5 ? -1 : 1) * speed;
}
update(maxWidth, maxHeight) {
this.x += this.vx;
this.y += this.vy;
if (this.x <= 0 || this.x + this.width >= maxWidth) {
this.vx *= -1;
}
if (this.y <= 0 || this.y + this.height >= maxHeight) {
this.vy *= -1;
}
}
draw(ctx) {
ctx.fillStyle = this.color;
if (this.type === 'strawberry') {
ctx.beginPath();
ctx.moveTo(this.x + this.width / 2, this.y);
ctx.lineTo(this.x + this.width, this.y + this.height / 2);
ctx.lineTo(this.x + this.width / 2, this.y + this.height);
ctx.lineTo(this.x, this.y + this.height / 2);
ctx.closePath();
ctx.fill();
} else if (this.type === 'squirrel') {
ctx.fillRect(this.x, this.y, this.width, this.height);
// Хвост белки
ctx.fillStyle = Game.colors.background;
ctx.fillRect(this.x + this.width * 0.6, this.y + this.height * 0.25, this.width * 0.1, this.height * 0.5);
}
}
checkCollision(other) {
return this.x < other.x + other.width &&
this.x + this.width > other.x &&
this.y < other.y + other.height &&
this.y + this.height > other.y;
}
}
// Инициализация игры
Game.init();
</script>
</body>
</html>
Описание улучшений:
Управление состоянием игры: Введены состояния игры (gameState), которые контролируют игровой процесс. Например, когда игрок выигрывает или проигрывает, игра переходит в соответствующее состояние, и отображается соответствующее сообщение.
Предотвращение появления объектов на коале: При генерации клубники и белки добавлена проверка на столкновение с коалой, чтобы они не появлялись прямо на игроке.
Улучшенная обработка событий: Обработчики событий для клавиатуры и сенсорных кнопок были оптимизированы, чтобы предотвратить конфликты и обеспечить более плавное управление.
Класс Player и Enemy: Созданы классы Player и Enemy для организации кода, что делает его более читабельным и легко расширяемым.
Улучшенный интерфейс: Вместо скрытия и отображения инструкций, введён элемент overlay, который отображает текущее состояние игры и предоставляет кнопку для начала или перезапуска игры.
Улучшенная отрисовка: Функции отрисовки объектов теперь находятся внутри соответствующих классов, что улучшает структуру кода.
Предотвращение перезапуска игры без согласия игрока: Теперь после выигрыша или проигрыша игрок должен нажать кнопку "Играть снова", чтобы начать новую игру, что улучшает пользовательский опыт.
Теперь игра должна работать более плавно, с улучшенной логикой и проверками, обеспечивая лучшее взаимодействие с пользователем.
Not yet included in a published release.