Untitled conversation
- Usercode
- Assistant
- User
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
- Assistant
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game — Поиграй в Змейку</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
font-family: 'Montserrat', sans-serif;
background:
radial-gradient(circle at center, #0f2027 0%, #203a43 60%, #2c5364 100%);
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
overflow-x: hidden;
}
/* Анимированный фон частиц */
#particles {
position: fixed;
top: 0; left: 0;
width: 100vw; height: 100vh;
pointer-events: none;
z-index: 0;
mix-blend-mode: screen;
}
header {
width: 100%;
padding: 2rem 1rem;
background: #111;
box-shadow: 0 4px 15px rgba(0,0,0,0.7);
text-align: center;
position: sticky;
top: 0;
z-index: 10;
}
header h1 {
margin: 0;
font-size: 3rem;
letter-spacing: 3px;
text-transform: uppercase;
background: linear-gradient(90deg, #00ff99, #00ccff);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
user-select: none;
text-shadow:
0 0 5px #00ff99,
0 0 10px #00ccff;
animation: glow 3s ease-in-out infinite alternate;
}
@keyframes glow {
from {
filter: drop-shadow(0 0 10px #00ff99);
}
to {
filter: drop-shadow(0 0 20px #00ccff);
}
}
main {
margin: 3rem 0 5rem;
display: flex;
flex-direction: column;
align-items: center;
gap: 1.8rem;
width: 100%;
max-width: 700px;
padding: 0 1rem;
z-index: 5;
position: relative;
}
.scoreboard {
font-size: 1.75rem;
font-weight: 800;
color: #00ff99;
letter-spacing: 1.5px;
text-shadow:
0 0 10px #00ff99,
0 0 18px #00ccff;
user-select: none;
min-width: 140px;
text-align: center;
background: rgba(0,0,0,0.3);
padding: 0.5rem 1rem;
border-radius: 12px;
backdrop-filter: blur(5px);
}
.game-container {
position: relative;
width: 600px;
height: 600px;
background: #111;
border-radius: 25px;
box-shadow:
0 0 40px #00ff99,
inset 0 0 50px #00ff99;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
canvas {
background: #222;
border-radius: 25px;
box-shadow:
0 0 25px #00ccff;
cursor: grab;
image-rendering: pixelated;
}
canvas:active {
cursor: grabbing;
}
button {
margin-top: 1rem;
padding: 0.85rem 2rem;
font-size: 1.25rem;
border: none;
border-radius: 50px;
background: linear-gradient(90deg, #00ff99, #00ccff);
color: #111;
font-weight: 700;
cursor: pointer;
box-shadow:
0 0 15px #00ff99,
0 0 30px #00ccff;
transition: background 0.3s ease, box-shadow 0.3s ease, transform 0.2s ease;
user-select: none;
letter-spacing: 0.05em;
}
button:hover {
background: linear-gradient(90deg, #00ccff, #00ff99);
box-shadow:
0 0 30px #00ccff,
0 0 40px #00ff99;
transform: scale(1.05);
}
button:active {
transform: scale(0.95);
}
footer {
margin-top: auto;
padding: 1rem;
width: 100%;
text-align: center;
background: #111;
color: #666;
font-size: 0.9rem;
user-select: none;
position: relative;
z-index: 5;
}
@media (max-width: 700px) {
.game-container {
width: 90vw;
height: 90vw;
}
canvas {
width: 90vw !important;
height: 90vw !important;
}
}
</style>
</head>
<body>
<div id="particles"></div>
<header>
<h1>Змейка</h1>
</header>
<main>
<div class="scoreboard" aria-live="polite" aria-atomic="true" id="scoreboard">
Счёт: <span id="score">0</span>
</div>
<div class="game-container" role="region" aria-label="Игра Змейка" tabindex="0">
<canvas id="gameCanvas" width="600" height="600" aria-label="Игровое поле Змейки"></canvas>
</div>
<button id="restartBtn" aria-label="Начать заново">Начать заново</button>
</main>
<footer>
© 2024 Профессиональный сайт с игрой Змейка. Все права защищены.
</footer>
<script>
(() => {
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElem = document.getElementById('score');
const restartBtn = document.getElementById('restartBtn');
const scoreboard = document.getElementById('scoreboard');
const COLS = 30;
const ROWS = 30;
const CELL_SIZE = canvas.width / COLS;
// Змейка и еда
let snake = [];
let direction = { x: 1, y: 0 };
let nextDirection = direction; // для плавного обновления направления
let food = {};
let score = 0;
let gameSpeed = 100; // базовая скорость в мс, чем меньше — тем быстрее
let speedModifier = 1;
let gameInterval = null;
// Бонусы
const bonusTypes = {
speedUp: 'speedUp',
slowDown: 'slowDown',
doubleScore: 'doubleScore',
};
let bonus = null; // {type, x, y, duration, activeTime}
let bonusActive = null;
// Аудио сигналы
const eatSound = new Audio('https://cdn.jsdelivr.net/gh/freeCodeCamp/cdn/audio/score.mp3');
const bonusSound = new Audio('https://freesound.org/data/previews/250/250629_4486188-lq.mp3');
// Плавный переход цвета головы змейки
let headHue = 180;
// Частицы при поедании еды и бонусов
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.size = Math.random() * 4 + 2;
this.color = color;
this.speedX = (Math.random() - 0.5) * 3;
this.speedY = (Math.random() - 0.5) * 3;
this.life = 25;
this.opacity = 1;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.life--;
this.opacity = this.life / 25;
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.opacity;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
let particles = [];
// Функция для создания частиц
function createParticles(gridX, gridY, color) {
const centerX = gridX * CELL_SIZE + CELL_SIZE / 2;
const centerY = gridY * CELL_SIZE + CELL_SIZE / 2;
for(let i = 0; i < 15; i++) {
particles.push(new Particle(centerX, centerY, color));
}
}
// Функция отрисовки частиц
function drawParticles() {
particles.forEach((p, i) => {
p.update();
p.draw(ctx);
if (p.life <= 0) particles.splice(i, 1);
});
}
// Генерирует случайное целое число в диапазоне [min, max]
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Инициализация змейки и игры
function init() {
snake = [
{ x: 10, y: 15 },
{ x: 9, y: 15 },
{ x: 8, y: 15 },
];
direction = { x: 1, y: 0 };
nextDirection = direction;
score = 0;
speedModifier = 1;
bonus = null;
bonusActive = null;
updateScore();
placeFood();
placeBonus();
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, gameSpeed);
// обновляем заголовок и доступность кнопок
restartBtn.disabled = false;
restartBtn.textContent = "Начать заново";
}
function updateScore() {
scoreElem.textContent = score;
}
// Помещаем еду в случайное свободное место
function placeFood() {
let newFoodPos;
do {
newFoodPos = {
x: Math.floor(Math.random() * COLS),
y: Math.floor(Math.random() * ROWS),
};
} while (snake.some(s => s.x === newFoodPos.x && s.y === newFoodPos.y) ||
(bonus && bonus.x === newFoodPos.x && bonus.y === newFoodPos.y));
food = newFoodPos;
}
// Помещаем бонус (с вероятностью 30%) в случайное свободное место
function placeBonus() {
// Вероятность появления бонуса
if (Math.random() > 0.3) {
bonus = null;
return;
}
const types = Object.values(bonusTypes);
let newBonusPos;
do {
newBonusPos = {
x: Math.floor(Math.random() * COLS),
y: Math.floor(Math.random() * ROWS),
};
} while (snake.some(s => s.x === newBonusPos.x && s.y === newBonusPos.y) ||
(food.x === newBonusPos.x && food.y === newBonusPos.y));
bonus = {
x: newBonusPos.x,
y: newBonusPos.y,
type: types[randomInt(0, types.length-1)],
duration: 6000, // бонус действует 6 секунд
activeTime: 0,
};
}
// Рисуем клетку с опцией свечения
function drawCell(x, y, color, glow = false) {
ctx.fillStyle = color;
ctx.shadowColor = glow ? color : 'transparent';
ctx.shadowBlur = glow ? 15 : 0;
ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
ctx.shadowBlur = 0;
}
// Рисуем сетку
function drawGrid() {
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.lineWidth = 1;
for (let i = 0; i <= COLS; i++) {
ctx.beginPath();
ctx.moveTo(i * CELL_SIZE, 0);
ctx.lineTo(i * CELL_SIZE, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= ROWS; i++) {
ctx.beginPath();
ctx.moveTo(0, i * CELL_SIZE);
ctx.lineTo(canvas.width, i * CELL_SIZE);
ctx.stroke();
}
}
// Плавное изменение цвета головы змейки (меняем hue)
function getHeadColor() {
headHue += 1;
if (headHue > 360) headHue = 0;
return `hsl(${headHue}, 100%, 50%)`;
}
// Отрисовываем змейку, еду, бонус и частицы
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid();
// Рисуем еду с эффектом свечения
drawCell(food.x, food.y, '#00ff99', true);
// Рисуем бонус (если есть) по типу цвета
if (bonus) {
let color;
switch (bonus.type) {
case bonusTypes.speedUp: color = '#ff4d4d'; break; // красный - ускорение
case bonusTypes.slowDown: color = '#4d79ff'; break; // синий - замедление
case bonusTypes.doubleScore: color = '#ffcc00'; break; // желтый - удвоение счета
default: color = '#fff'; break;
}
// Небольшая пульсация бонуса
const pulse = 0.7 + 0.3 * Math.sin(Date.now() / 300);
ctx.save();
ctx.globalAlpha = pulse;
drawCell(bonus.x, bonus.y, color, true);
ctx.restore();
}
// Змейка с градиентом для тела и меняющейся головой
const headColor = getHeadColor();
snake.forEach((segment, i) => {
if(i === 0) {
drawCell(segment.x, segment.y, headColor, true);
} else {
// тело от зеленого к синим с градиентом по позиции
const t = i / snake.length;
const r = Math.floor(0 + t * (0 - 0));
const g = Math.floor(255 - t * 100);
const b = Math.floor(153 + t * 102);
drawCell(segment.x, segment.y, `rgb(${r},${g},${b})`);
}
});
drawParticles();
}
// Перемещаем змейку и обрабатываем столкновения
function moveSnake() {
// Обновляем направление, если не противоположно текущему
if (Math.abs(nextDirection.x) !== Math.abs(direction.x) ||
Math.abs(nextDirection.y) !== Math.abs(direction.y)) {
direction = nextDirection;
}
const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
// Телепортация через стены
if (head.x < 0) head.x = COLS - 1;
if (head.x >= COLS) head.x = 0;
if (head.y < 0) head.y = ROWS - 1;
if (head.y >= ROWS) head.y = 0;
// Проверяем столкновение с телом
if (snake.some(s => s.x === head.x && s.y === head.y)) {
gameOver();
return false;
}
snake.unshift(head);
// Проверяем съедена ли еда
if (head.x === food.x && head.y === food.y) {
// Увеличиваем счёт
if (bonusActive && bonusActive.type === bonusTypes.doubleScore) {
score += 2;
} else {
score += 1;
}
updateScore();
eatSound.currentTime = 0;
eatSound.play();
createParticles(food.x, food.y, '#00ff99');
placeFood();
// С вероятностью 30% появляется бонус
if (!bonus) placeBonus();
} else {
snake.pop();
}
// Проверяем бонус
if (bonus && head.x === bonus.x && head.y === bonus.y) {
activateBonus(bonus);
bonus = null;
}
return true;
}
// Активируем бонус и запускаем таймер
function activateBonus(b) {
bonusActive = b;
bonusSound.currentTime = 0;
bonusSound.play();
createParticles(b.x, b.y, '#ffff55');
// Изменяем параметры в зависимости от типа бонуса
switch (b.type) {
case bonusTypes.speedUp:
speedModifier = 0.6; // игра ускоряется
break;
case bonusTypes.slowDown:
speedModifier = 1.6; // игра замедляется
break;
case bonusTypes.doubleScore:
speedModifier = 1;
break;
}
// Таймер деактивации бонуса
setTimeout(() => {
bonusActive = null;
speedModifier = 1;
}, b.duration);
}
function gameOver() {
clearInterval(gameInterval);
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#00ff99';
ctx.font = 'bold 60px Montserrat, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Game Over!', canvas.width / 2, canvas.height / 2 - 40);
ctx.font = '28px Montserrat, sans-serif';
ctx.fillText(`Ваш счёт: ${score}`, canvas.width / 2, canvas.height / 2 + 20);
// Отключаем кнопку рестарта на 1 секунду, чтобы избежать спама
restartBtn.disabled = true;
setTimeout(() => restartBtn.disabled = false, 1000);
}
// Обновляет таймер и скорость игры для плавности
function gameLoop() {
if (!moveSnake()) return;
draw();
}
// Обработка клавиш (стрелки и WASD)
function handleKey(e) {
const key = e.key.toLowerCase();
const allowedKeys = ['arrowup', 'w','arrowdown','s','arrowleft','a','arrowright','d'];
if(!allowedKeys.includes(key)) return;
// Запрещаем сразу менять направление на противоположное (судя по текущему движению)
if (key === 'arrowup' || key === 'w') {
if (direction.y !== 1) nextDirection = { x: 0, y: -1 };
} else if (key === 'arrowdown' || key === 's') {
if (direction.y !== -1) nextDirection = { x: 0, y: 1 };
} else if (key === 'arrowleft' || key === 'a') {
if (direction.x !== 1) nextDirection = { x: -1, y: 0 };
} else if (key === 'arrowright' || key === 'd') {
if (direction.x !== -1) nextDirection = { x: 1, y: 0 };
}
}
// Перезапускаем игру с новой скоростью и учитываем бонус
function refreshInterval() {
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, gameSpeed * speedModifier);
}
// Следим за изменением скорости при активации/деактивации бонуса
let lastSpeedModifier = speedModifier;
setInterval(() => {
if(lastSpeedModifier !== speedModifier) {
refreshInterval();
lastSpeedModifier = speedModifier;
}
}, 100);
// Акселерация для тач-данных (мобильные устройства)
let touchStartX = null;
let touchStartY = null;
const swipeThreshold = 30;
function onTouchStart(e) {
const t = e.touches[0];
touchStartX = t.clientX;
touchStartY = t.clientY;
}
function onTouchMove(e) {
if(!touchStartX || !touchStartY) return;
const t = e.touches[0];
const dx = t.clientX - touchStartX;
const dy = t.clientY - touchStartY;
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > swipeThreshold && direction.x !== -1) nextDirection = {x:1,y:0};
else if (dx < -swipeThreshold && direction.x !== 1) nextDirection = {x:-1,y:0};
} else {
if (dy > swipeThreshold && direction.y !== -1) nextDirection = {x:0,y:1};
else if (dy < -swipeThreshold && direction.y !== 1) nextDirection = {x:0,y:-1};
}
touchStartX = null;
touchStartY = null;
}
// Частицы фоновая анимация (мелкие светящиеся точки)
class BackgroundParticle {
constructor(width, height) {
this.x = Math.random() * width;
this.y = Math.random() * height;
this.radius = Math.random() * 1.2 + 0.3;
this.alpha = Math.random() * 0.7 + 0.3;
this.speed = Math.random() * 0.05 + 0.01;
this.width = width;
this.height = height;
this.direction = Math.random() < 0.5 ? 1 : -1;
}
update() {
this.alpha += this.speed * this.direction;
if (this.alpha >= 1) {
this.alpha = 1;
this.direction = -1;
} else if (this.alpha <= 0.3) {
this.alpha = 0.3;
this.direction = 1;
}
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = '#00ffcc';
ctx.shadowColor = '#00ffcc';
ctx.shadowBlur = 15;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
}
// Рендеринг фоновых частиц
const particlesCanvas = document.createElement('canvas');
const particlesCtx = particlesCanvas.getContext('2d');
let particlesArray = [];
function initBackgroundParticles() {
const particlesDiv = document.getElementById('particles');
particlesDiv.appendChild(particlesCanvas);
particlesCanvas.width = window.innerWidth;
particlesCanvas.height = window.innerHeight;
generateParticles();
}
function generateParticles() {
particlesArray = [];
for (let i = 0; i < 150; i++) {
particlesArray.push(new BackgroundParticle(particlesCanvas.width, particlesCanvas.height));
}
}
function animateBackgroundParticles() {
particlesCtx.clearRect(0, 0, particlesCanvas.width, particlesCanvas.height);
particlesArray.forEach(p => {
p.update();
p.draw(particlesCtx);
});
requestAnimationFrame(animateBackgroundParticles);
}
window.addEventListener('resize', () => {
particlesCanvas.width = window.innerWidth;
particlesCanvas.height = window.innerHeight;
generateParticles();
});
// --- Запуск ---
initBackgroundParticles();
animateBackgroundParticles();
restartBtn.addEventListener('click', () => {
init();
});
window.addEventListener('keydown', handleKey);
canvas.addEventListener('touchstart', onTouchStart, {passive: true});
canvas.addEventListener('touchmove', onTouchMove, {passive: true});
init();
})();
</script>
</body>
</html>
Преобразуй следующий код, чтобы он соответствовал уровню senior-разработчика: используй объектно-ориентированное программирование с инкапсуляцией, абстракцией и наследованием там, где это уместно, сделай архитектуру модульной, расширяемой и поддерживаемой, оптимизируй производительность и читаемость, улучшай именования переменных, функций и классов, устраняй дублирование кода, применяй подходящие паттерны проектирования для гибкости и масштабируемости, внедри обработку ошибок с информативными сообщениями и обеспечь логирование ключевых событий, добавь подробные комментарии и документацию к основным классам и методам, обеспечь финальный код простым для понимания, тестирования и поддержки.
Конечно! Ниже — одна из возможных реализаций улучшенного (senior-level) варианта вашего Snake Game. Код структурирован по классам с учетом инкапсуляции, абстракции и модульности. Использованы паттерны проектирования (Singleton для логгера, наблюдатель для событий), разбит на автономные классы с четкими зонами ответственности. Добавлена базовая обработка ошибок, логирование ключевых событий, подробные комментарии и JSDoc. Логика игры и UI четко разделены.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game — Поиграй в Змейку</title>
<style>
/* (оставляем ваш CSS без изменений, он довольно хорош и структурирован) */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
font-family: 'Montserrat', sans-serif;
background:
radial-gradient(circle at center, #0f2027 0%, #203a43 60%, #2c5364 100%);
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
overflow-x: hidden;
}
/* Анимированный фон частиц */
#particles {
position: fixed;
top: 0; left: 0;
width: 100vw; height: 100vh;
pointer-events: none;
z-index: 0;
mix-blend-mode: screen;
}
header {
width: 100%;
padding: 2rem 1rem;
background: #111;
box-shadow: 0 4px 15px rgba(0,0,0,0.7);
text-align: center;
position: sticky;
top: 0;
z-index: 10;
}
header h1 {
margin: 0;
font-size: 3rem;
letter-spacing: 3px;
text-transform: uppercase;
background: linear-gradient(90deg, #00ff99, #00ccff);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
user-select: none;
text-shadow:
0 0 5px #00ff99,
0 0 10px #00ccff;
animation: glow 3s ease-in-out infinite alternate;
}
@keyframes glow {
from {
filter: drop-shadow(0 0 10px #00ff99);
}
to {
filter: drop-shadow(0 0 20px #00ccff);
}
}
main {
margin: 3rem 0 5rem;
display: flex;
flex-direction: column;
align-items: center;
gap: 1.8rem;
width: 100%;
max-width: 700px;
padding: 0 1rem;
z-index: 5;
position: relative;
}
.scoreboard {
font-size: 1.75rem;
font-weight: 800;
color: #00ff99;
letter-spacing: 1.5px;
text-shadow:
0 0 10px #00ff99,
0 0 18px #00ccff;
user-select: none;
min-width: 140px;
text-align: center;
background: rgba(0,0,0,0.3);
padding: 0.5rem 1rem;
border-radius: 12px;
backdrop-filter: blur(5px);
}
.game-container {
position: relative;
width: 600px;
height: 600px;
background: #111;
border-radius: 25px;
box-shadow:
0 0 40px #00ff99,
inset 0 0 50px #00ff99;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
canvas {
background: #222;
border-radius: 25px;
box-shadow:
0 0 25px #00ccff;
cursor: grab;
image-rendering: pixelated;
}
canvas:active {
cursor: grabbing;
}
button {
margin-top: 1rem;
padding: 0.85rem 2rem;
font-size: 1.25rem;
border: none;
border-radius: 50px;
background: linear-gradient(90deg, #00ff99, #00ccff);
color: #111;
font-weight: 700;
cursor: pointer;
box-shadow:
0 0 15px #00ff99,
0 0 30px #00ccff;
transition: background 0.3s ease, box-shadow 0.3s ease, transform 0.2s ease;
user-select: none;
letter-spacing: 0.05em;
}
button:hover {
background: linear-gradient(90deg, #00ccff, #00ff99);
box-shadow:
0 0 30px #00ccff,
0 0 40px #00ff99;
transform: scale(1.05);
}
button:active {
transform: scale(0.95);
}
footer {
margin-top: auto;
padding: 1rem;
width: 100%;
text-align: center;
background: #111;
color: #666;
font-size: 0.9rem;
user-select: none;
position: relative;
z-index: 5;
}
@media (max-width: 700px) {
.game-container {
width: 90vw;
height: 90vw;
}
canvas {
width: 90vw !important;
height: 90vw !important;
}
}
</style>
</head>
<body>
<div id="particles"></div>
<header>
<h1>Змейка</h1>
</header>
<main>
<div class="scoreboard" aria-live="polite" aria-atomic="true" id="scoreboard">
Счёт: <span id="score">0</span>
</div>
<div class="game-container" role="region" aria-label="Игра Змейка" tabindex="0">
<canvas id="gameCanvas" width="600" height="600" aria-label="Игровое поле Змейки"></canvas>
</div>
<button id="restartBtn" aria-label="Начать заново">Начать заново</button>
</main>
<footer>
© 2024 Профессиональный сайт с игрой Змейка. Все права защищены.
</footer>
<script>
(() => {
'use strict';
/**
* #########################
* Logger Singleton
* #########################
* Универсальный логгер для консоли с разными уровнями.
* Позволяет централизованно управлять логированием.
*/
class Logger {
constructor() {
if (Logger.instance) return Logger.instance;
this.debugEnabled = true;
Logger.instance = this;
}
info(...args) {
console.info('[INFO]', ...args);
}
warn(...args) {
console.warn('[WARN]', ...args);
}
error(...args) {
console.error('[ERROR]', ...args);
}
debug(...args) {
if (this.debugEnabled) {
console.debug('[DEBUG]', ...args);
}
}
setDebug(state) {
this.debugEnabled = !!state;
}
}
const logger = new Logger();
/**
* #########################
* Utility Functions
* #########################
*/
/**
* Возвращает случайное целое число включительно между min и max
* @param {number} min
* @param {number} max
* @returns {number}
*/
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
/**
* Клонирует объект с положением (x,y)
* @param {{x:number, y:number}} pos
* @returns {{x:number, y:number}}
*/
const clonePosition = (pos) => ({ x: pos.x, y: pos.y });
/**
* Проверяет, равны ли две позиции
* @param {{x:number, y:number}} posA
* @param {{x:number, y:number}} posB
* @returns {boolean}
*/
const positionsEqual = (posA, posB) => posA.x === posB.x && posA.y === posB.y;
/**
* Проверяет входит ли элемент с позицией pos в массив объектов с позицией x,y
* @param {Array<{x:number,y:number}>} list
* @param {{x:number,y:number}} pos
* @returns {boolean}
*/
const containsPosition = (list, pos) => list.some(item => positionsEqual(item, pos));
/**
* #########################
* EventEmitter (наблюдатель)
* #########################
* Фасад для подписки/оповещения событий
*/
class EventEmitter {
constructor() {
this.listeners = {};
}
/**
* Подписка на событие
*/
on(event, callback) {
if (typeof callback !== 'function') {
logger.warn(`Listener for event "${event}" is not a function`);
return;
}
this.listeners[event] = this.listeners[event] || [];
this.listeners[event].push(callback);
}
/**
* Отписка от события
*/
off(event, callback) {
if (!this.listeners[event]) return;
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
}
/**
* Генерирует событие
*/
emit(event, ...args) {
if (!this.listeners[event]) return;
this.listeners[event].forEach(cb => {
try {
cb(...args);
} catch (error) {
logger.error(`Error in event listener for "${event}":`, error);
}
});
}
}
/**
* #########################
* Particle — Базовый класс
* #########################
* Частица с позиционированием и отрисовкой.
* Используется для эффекта частиц и фоновых частиц.
*/
class Particle {
/**
* @param {number} x
* @param {number} y
* @param {string} color
* @param {number} size
* @param {number} life
* @param {number} speedX
* @param {number} speedY
*/
constructor(x, y, color, size = 3, life = 25, speedX = 0, speedY = 0) {
this.x = x;
this.y = y;
this.color = color;
this.size = size;
this.life = life;
this.opacity = 1;
this.speedX = speedX;
this.speedY = speedY;
}
/**
* Логика обновления частицы
*/
update() {
this.x += this.speedX;
this.y += this.speedY;
this.life--;
this.opacity = Math.max(0, this.life / 25);
}
/**
* Рисует частицу на холсте
* @param {CanvasRenderingContext2D} ctx
*/
draw(ctx) {
if (this.life <= 0) return;
ctx.save();
ctx.globalAlpha = this.opacity;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
isAlive() {
return this.life > 0;
}
}
/**
* Частица фона (медленно пульсирующая светящаяся точка)
*/
class BackgroundParticle extends Particle {
constructor(canvasWidth, canvasHeight) {
const x = Math.random() * canvasWidth;
const y = Math.random() * canvasHeight;
const size = Math.random() * 1.2 + 0.3;
super(x, y, '#00ffcc', size, Infinity);
this.alpha = Math.random() * 0.7 + 0.3;
this.speed = Math.random() * 0.05 + 0.01;
this.direction = Math.random() < 0.5 ? 1 : -1;
this.canvasWidth = canvasWidth;
this.canvasHeight = canvasHeight;
}
update() {
this.alpha += this.speed * this.direction;
if (this.alpha >= 1) {
this.alpha = 1;
this.direction = -1;
} else if (this.alpha <= 0.3) {
this.alpha = 0.3;
this.direction = 1;
}
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.shadowColor = this.color;
ctx.shadowBlur = 15;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
}
/**
* #########################
* Entity — базовый класс для объектов на игровом поле (Snake segment, Food, Bonus)
* #########################
*/
class Entity {
/**
* @param {number} x
* @param {number} y
*/
constructor(x, y) {
this.x = x;
this.y = y;
}
/**
* Возвращает позицию в виде объекта
*/
get position() {
return { x: this.x, y: this.y };
}
/**
* Устанавливает позицию
* @param {{x:number,y:number}} pos
*/
set position(pos) {
this.x = pos.x;
this.y = pos.y;
}
equals(other) {
return other && this.x === other.x && this.y === other.y;
}
}
/**
* #########################
* Bonus разные типы бонусов
* #########################
*/
class Bonus extends Entity {
/**
* @param {number} x
* @param {number} y
* @param {string} type
* @param {number} duration — в мс
*/
constructor(x, y, type, duration = 6000) {
super(x, y);
this.type = type;
this.duration = duration;
this._creationTimestamp = Date.now();
}
/**
* Возвращает, истёк ли срок действия бонуса
* @returns {boolean}
*/
get isExpired() {
return (Date.now() - this._creationTimestamp) > this.duration;
}
}
/**
* #########################
* Snake — класс змейки
* #########################
*/
class Snake {
/**
* @param {{x:number, y:number}[]} initialSegments
*/
constructor(initialSegments = [{x:10,y:15},{x:9,y:15},{x:8,y:15}]) {
/** @type {Entity[]} */
this.segments = initialSegments.map(pos => new Entity(pos.x, pos.y));
this.direction = { x: 1, y: 0 };
this.nextDirection = { ...this.direction };
}
/**
* Получить позицию головы
* @returns {Entity}
*/
get head() {
return this.segments[0];
}
/**
* Проверяет, есть ли столкновение головы и тела (без головы)
* @returns {boolean}
*/
hasSelfCollision() {
const headPos = this.head.position;
return this.segments.slice(1).some(s => s.equals(headPos));
}
/**
* Устанавливаем направление движения. Отмена противоположного направления
* @param {{x:number,y:number}} newDir
*/
setDirection(newDir) {
if (
newDir.x === -this.direction.x && newDir.y === -this.direction.y
) {
logger.debug('Ignored reverse direction input');
return; // запретить движение в противоположную сторону сразу
}
this.nextDirection = { ...newDir };
}
/**
* Совершаем шаг змейкой, возвращая новое состояние
* @param {number} cols
* @param {number} rows
* @returns {{ ateFood: boolean }}
*/
move(cols, rows, foodPos) {
// Обновляем направление плавно
this.direction = { ...this.nextDirection };
// Вычисляем новые координаты головы
let newX = this.head.x + this.direction.x;
let newY = this.head.y + this.direction.y;
// Телепортация через стены
if (newX < 0) newX = cols -1;
if (newX >= cols) newX = 0;
if (newY < 0) newY = rows -1;
if (newY >= rows) newY = 0;
const newHead = new Entity(newX, newY);
// Проверяем столкновение с самим собой
if (this.segments.some(s => s.equals(newHead))) {
throw new Error('Snake collided with itself');
}
// Добавляем новую голову
this.segments.unshift(newHead);
// Проверяем съело ли еду
const ateFood = newHead.equals(foodPos);
if (!ateFood) {
// Удаляем хвост, если не съели
this.segments.pop();
}
return { ateFood };
}
}
/**
* #########################
* GameBoard — игровая доска и отрисовка
* #########################
*/
class GameBoard {
/**
* @param {HTMLCanvasElement} canvas
* @param {number} cols
* @param {number} rows
*/
constructor(canvas, cols=30, rows=30) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.cols = cols;
this.rows = rows;
this.cellSize = this.canvas.width / cols;
// Частицы еды / бонусов
this.particles = [];
// Используется для плавного изменения цвета головы
this.headHue = 180;
}
/**
* Создаёт частицы эффекта в позиции сетки
* @param {number} gridX
* @param {number} gridY
* @param {string} color
*/
createParticles(gridX, gridY, color) {
const centerX = gridX * this.cellSize + this.cellSize / 2;
const centerY = gridY * this.cellSize + this.cellSize / 2;
for (let i = 0; i < 15; i++) {
const speedX = (Math.random() - 0.5) * 3;
const speedY = (Math.random() - 0.5) * 3;
const size = Math.random() * 4 + 2;
this.particles.push(new Particle(centerX, centerY, color, size, 25, speedX, speedY));
}
logger.debug(`Created particles at (${gridX},${gridY}) with color ${color}`);
}
/**
* Отрисовывает клетки с возможным свечением
* @param {number} x
* @param {number} y
* @param {string} color
* @param {boolean} glow
*/
drawCell(x, y, color, glow = false) {
this.ctx.fillStyle = color;
this.ctx.shadowColor = glow ? color : 'transparent';
this.ctx.shadowBlur = glow ? 15 : 0;
this.ctx.fillRect(x * this.cellSize, y * this.cellSize, this.cellSize, this.cellSize);
this.ctx.shadowBlur = 0;
}
/**
* Рисует сетку игрового поля
*/
drawGrid() {
const ctx = this.ctx;
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.lineWidth = 1;
for (let i = 0; i <= this.cols; i++) {
ctx.beginPath();
ctx.moveTo(i * this.cellSize, 0);
ctx.lineTo(i * this.cellSize, this.canvas.height);
ctx.stroke();
}
for (let i = 0; i <= this.rows; i++) {
ctx.beginPath();
ctx.moveTo(0, i * this.cellSize);
ctx.lineTo(this.canvas.width, i * this.cellSize);
ctx.stroke();
}
}
/**
* Получает цвет для головы змеи с плавным изменением hue
* @returns {string} hsl цвет
*/
getHeadColor() {
this.headHue += 1;
if (this.headHue > 360) this.headHue = 0;
return `hsl(${this.headHue}, 100%, 50%)`;
}
/**
* Отрисовывает весь игровой контент: змейка, еда, бонус, частицы
* @param {Snake} snake
* @param {Entity} food
* @param {Bonus|null} bonus
*/
draw(snake, food, bonus) {
try {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawGrid();
// Рисуем еду с эффектом свечения
this.drawCell(food.x, food.y, '#00ff99', true);
// Рисуем бонус
if (bonus) {
let color;
switch (bonus.type) {
case 'speedUp': color = '#ff4d4d'; break;
case 'slowDown': color = '#4d79ff'; break;
case 'doubleScore': color = '#ffcc00'; break;
default: color = '#fff'; break;
}
const pulse = 0.7 + 0.3 * Math.sin(Date.now() / 300);
this.ctx.save();
this.ctx.globalAlpha = pulse;
this.drawCell(bonus.x, bonus.y, color, true);
this.ctx.restore();
}
// Отрисовываем змейку
const headColor = this.getHeadColor();
snake.segments.forEach((segment, i) => {
if (i === 0) {
this.drawCell(segment.x, segment.y, headColor, true);
} else {
// тело: градиент от зеленого к синему
const t = i / snake.segments.length;
const r = 0; // неизменяемый
const g = Math.floor(255 - t * 100);
const b = Math.floor(153 + t * 102);
this.drawCell(segment.x, segment.y, `rgb(${r},${g},${b})`);
}
});
this._updateAndDrawParticles();
} catch (err) {
logger.error('Ошибка при отрисовке игрового поля:', err);
}
}
/**
* Обновляет и отрисовывает все частицы
*/
_updateAndDrawParticles() {
for (let i = this.particles.length - 1; i >=0; i--) {
const p = this.particles[i];
p.update();
if (!p.isAlive()) {
this.particles.splice(i, 1);
} else {
p.draw(this.ctx);
}
}
}
}
/**
* #########################
* BonusManager — работа с бонусами
* #########################
*/
class BonusManager extends EventEmitter {
/**
* @param {number} cols
* @param {number} rows
*/
constructor(cols, rows) {
super();
this.cols = cols;
this.rows = rows;
this.bonus = null;
this.bonusTypes = ['speedUp', 'slowDown', 'doubleScore'];
}
/**
* Пытается разместить бонус в случайное свободное место с вероятностью 30%
* @param {Entity[]} occupiedPositions
*/
tryPlaceBonus(occupiedPositions) {
if (Math.random() > 0.3) {
this._clearBonus();
return;
}
for (let attempts = 0; attempts < 100; attempts++) {
const pos = { x: randomInt(0, this.cols -1), y: randomInt(0, this.rows -1) };
if (containsPosition(occupiedPositions, pos)) continue;
const type = this.bonusTypes[randomInt(0, this.bonusTypes.length - 1)];
this.bonus = new Bonus(pos.x, pos.y, type);
logger.info(`Bonus appeared at (${pos.x},${pos.y}) type ${type}`);
this.emit('bonusPlaced', this.bonus);
return;
}
// Если не удалось найти место за 100 попыток — убираем бонус
this._clearBonus();
}
/**
* Проверяет, съели ли бонус
* @param {Entity} position
*/
checkCollected(position) {
if (this.bonus && this.bonus.equals(position)) {
const activatedBonus = this.bonus;
this._clearBonus();
this.emit('bonusCollected', activatedBonus);
return activatedBonus;
}
return null;
}
/**
* Убирает бонус с поля
*/
_clearBonus() {
if (this.bonus) {
logger.info('Bonus expired or removed');
this.bonus = null;
this.emit('bonusCleared');
}
}
}
/**
* #########################
* Game — основной класс игры
* #########################
*/
class Game extends EventEmitter {
/**
* @param {HTMLCanvasElement} canvas
* @param {HTMLElement} scoreElement
* @param {HTMLButtonElement} restartButton
*/
constructor(canvas, scoreElement, restartButton) {
super();
// Размеры поля
this.cols = 30;
this.rows =30;
this.canvas = canvas;
this.scoreElement = scoreElement;
this.restartButton = restartButton;
// Game state
this.score = 0;
this.gameSpeedBase = 100; // ms per tick
this.speedModifier = 1;
this.gameIntervalId = null;
// Entities
this.snake = null;
this.food = null;
this.bonusManager = null;
this.activeBonus = null;
// Renderer
this.board = new GameBoard(this.canvas, this.cols, this.rows);
// Sounds
this.sounds = {
eat: new Audio('https://cdn.jsdelivr.net/gh/freeCodeCamp/cdn/audio/score.mp3'),
bonus: new Audio('https://freesound.org/data/previews/250/250629_4486188-lq.mp3')
};
// Bind handlers
this._handleKeyInput = this._handleKeyInput.bind(this);
this._onRestartClick = this._onRestartClick.bind(this);
this._speedCheckIntervalId = null;
this._init();
}
/**
* Инициализация и старт игры
*/
_init() {
logger.info('Инициализация игры');
this.snake = new Snake();
this.score = 0;
this.speedModifier = 1;
this.activeBonus = null;
this.food = this._placeFood();
this.bonusManager = new BonusManager(this.cols, this.rows);
this.bonusManager.on('bonusPlaced', (bonus) => {
this.emit('bonusPlaced', bonus);
});
this.bonusManager.on('bonusCollected', (bonus) => {
this._activateBonus(bonus);
});
this.bonusManager.on('bonusCleared', () => {
// bonus убран с поля
logger.debug('Bonus removed from field');
});
this._updateScore();
this._setupEventListeners();
this._restartGameLoop();
// Включаем кнопку рестарта
this.restartButton.disabled = false;
this.restartButton.textContent = "Начать заново";
logger.info('Игра запущена');
}
/**
* Ставит обработчики событий
*/
_setupEventListeners() {
window.removeEventListener('keydown', this._handleKeyInput); // на всякий перестраховка
window.addEventListener('keydown', this._handleKeyInput);
this.restartButton.removeEventListener('click', this._onRestartClick);
this.restartButton.addEventListener('click', this._onRestartClick);
}
/**
* Обработчик кнопки рестарта
*/
_onRestartClick() {
this.stop();
this._init();
}
/**
* Обработчик нажатия клавиш
* @param {KeyboardEvent} e
*/
_handleKeyInput(e) {
const key = e.key.toLowerCase();
switch(key) {
case 'arrowup':
case 'w':
this.snake.setDirection({x:0, y:-1});
break;
case 'arrowdown':
case 's':
this.snake.setDirection({x:0, y:1});
break;
case 'arrowleft':
case 'a':
this.snake.setDirection({x:-1, y:0});
break;
case 'arrowright':
case 'd':
this.snake.setDirection({x:1, y:0});
break;
}
}
/**
* Запускает основной игровой цикл с учётом скорости
*/
_restartGameLoop() {
if (this.gameIntervalId) clearInterval(this.gameIntervalId);
this.gameIntervalId = setInterval(() => this._gameTick(), this.gameSpeedBase * this.speedModifier);
// Проверяем изменение скорости каждые 100ms и обновляем таймер если нужно
if(this._speedCheckIntervalId) clearInterval(this._speedCheckIntervalId);
this._speedCheckIntervalId = setInterval(() => {
if(this._lastSpeedModifier !== this.speedModifier) {
this._restartGameLoop();
this._lastSpeedModifier = this.speedModifier;
}
}, 100);
}
/**
* Основной цикл игры - шаг змейкой, проверка столкновений, обновление UI
*/
_gameTick() {
try {
const moveResult = this.snake.move(this.cols, this.rows, this.food.position);
if (moveResult.ateFood) {
this._onFoodEaten();
}
this.bonusManager.tryPlaceBonus([...this.snake.segments.map(s => s.position), this.food.position]);
// Проверяем съели ли бонус
if (this.activeBonus === null) { // если бонус активен, не проверяем столкновение
const collectedBonus = this.bonusManager.checkCollected(this.snake.head.position);
if (collectedBonus) {
// бонус будет активирован в событии бонуса
this.emit('bonusCollectedExternally', collectedBonus);
}
}
this.board.draw(this.snake, this.food, this.bonusManager.bonus);
} catch (err) {
logger.error('Game over:', err.message);
this._onGameOver();
}
}
/**
* Обрабатывает съедание еды
*/
_onFoodEaten() {
let increment = 1;
if (this.activeBonus && this.activeBonus.type === 'doubleScore') {
increment = 2;
}
this.score += increment;
this._updateScore();
this._playSound('eat');
this.board.createParticles(this.food.x, this.food.y, '#00ff99');
this.food = this._placeFood();
logger.info(`Food eaten: +${increment} points, total: ${this.score}`);
}
/**
* Активирует бонус с его эффектом и настройкой таймера
* @param {Bonus} bonus
*/
_activateBonus(bonus) {
this.activeBonus = bonus;
logger.info(`Bonus activated: ${bonus.type} for ${bonus.duration}ms.`);
this._playSound('bonus');
this.board.createParticles(bonus.x, bonus.y, '#ffff55');
// Применяем эффект бонуса
switch(bonus.type) {
case 'speedUp':
this.speedModifier = 0.6;
break;
case 'slowDown':
this.speedModifier = 1.6;
break;
case 'doubleScore':
this.speedModifier = 1;
break;
}
if(this._bonusTimeoutId) clearTimeout(this._bonusTimeoutId);
this._bonusTimeoutId = setTimeout(() => {
this._deactivateBonus();
}, bonus.duration);
}
/**
* Деактивирует текущий бонус и восстанавливает параметры
*/
_deactivateBonus() {
logger.info('Bonus expired, reverting effects');
this.activeBonus = null;
this.speedModifier = 1;
}
/**
* Помещает еду в доступное случайное место, исключая змейку и бонус
* @returns {Entity}
*/
_placeFood() {
// Список занятых ячеек (змейка)
const occupied = new Set(this.snake.segments.map(s => `${s.x},${s.y}`));
// Если бонус есть — учесть и его позицию
if (this.bonusManager && this.bonusManager.bonus) {
occupied.add(`${this.bonusManager.bonus.x},${this.bonusManager.bonus.y}`);
}
let newFoodPos;
for (let attempt=0; attempt < 100; attempt++) {
const x = randomInt(0, this.cols - 1);
const y = randomInt(0, this.rows - 1);
const key = `${x},${y}`;
if (occupied.has(key)) continue;
newFoodPos = new Entity(x, y);
break;
}
if (!newFoodPos) {
throw new Error('Не удалось найти место для еды');
}
logger.info(`Food placed at (${newFoodPos.x},${newFoodPos.y})`);
return newFoodPos;
}
/**
* Обновляет счет на UI
*/
_updateScore() {
this.scoreElement.textContent = this.score.toString();
}
/**
* Проигрывает звук по ключу ('eat'|'bonus')
* @param {string} key
*/
_playSound(key) {
try {
if (this.sounds[key]) {
this.sounds[key].currentTime = 0;
this.sounds[key].play();
}
} catch (e) {
logger.warn(`Ошибка при воспроизведении звука ${key}:`, e);
}
}
/**
* Обрабатывает завершение игры
*/
_onGameOver() {
clearInterval(this.gameIntervalId);
clearInterval(this._speedCheckIntervalId);
const ctx = this.board.ctx;
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
ctx.fillStyle = '#00ff99';
ctx.font = 'bold 60px Montserrat, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Game Over!', this.canvas.width / 2, this.canvas.height / 2 - 40);
ctx.font = '28px Montserrat, sans-serif';
ctx.fillText(`Ваш счёт: ${this.score}`, this.canvas.width / 2, this.canvas.height / 2 + 20);
// Деактивируем кнопку рестарта на секунду
this.restartButton.disabled = true;
setTimeout(() => this.restartButton.disabled = false, 1000);
this.emit('gameOver', this.score);
logger.info('Игра завершена. Счёт: ', this.score);
}
/**
* Останавливает игру (чистит таймеры и слушатели)
*/
stop() {
clearInterval(this.gameIntervalId);
clearInterval(this._speedCheckIntervalId);
window.removeEventListener('keydown', this._handleKeyInput);
this.restartButton.removeEventListener('click', this._onRestartClick);
}
}
/**
* #########################
* BackgroundParticlesManager — отрисовка фоновых частиц
* #########################
*/
class BackgroundParticlesManager {
/**
* @param {HTMLElement} containerDiv
*/
constructor(containerDiv) {
this.container = containerDiv;
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
this.particles = [];
this.animationFrameId = null;
this.resizeHandler = this._onResize.bind(this);
this._setupCanvas();
this._createParticles();
this._startAnimation();
window.addEventListener('resize', this.resizeHandler);
}
_setupCanvas() {
this.canvas.style.position = 'fixed';
this.canvas.style.top = '0';
this.canvas.style.left = '0';
this.canvas.style.width = '100vw';
this.canvas.style.height = '100vh';
this.canvas.style.pointerEvents = 'none';
this.canvas.style.zIndex = '0';
this.canvas.style.mixBlendMode = 'screen';
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.container.appendChild(this.canvas);
}
_createParticles() {
this.particles = [];
const count = 150;
for (let i = 0; i < count; i++) {
this.particles.push(new BackgroundParticle(this.canvas.width, this.canvas.height));
}
logger.debug(`Создано ${count} фоновых частиц`);
}
_onResize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.particles.forEach(p => {
p.x = Math.random() * this.canvas.width;
p.y = Math.random() * this.canvas.height;
});
logger.debug('Фоновые частицы: изменен размер холста и обновлены позиции');
}
_animate() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (const particle of this.particles) {
particle.update();
particle.draw(this.ctx);
}
this.animationFrameId = requestAnimationFrame(() => this._animate());
}
_startAnimation() {
if (!this.animationFrameId) {
this._animate();
}
}
stop() {
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId);
this.animationFrameId = null;
}
window.removeEventListener('resize', this.resizeHandler);
if (this.canvas && this.container.contains(this.canvas)) {
this.container.removeChild(this.canvas);
}
}
}
// ==========================
// Запуск игры
// ==========================
try {
const canvas = document.getElementById('gameCanvas');
const scoreElem = document.getElementById('score');
const restartBtn = document.getElementById('restartBtn');
const particlesDiv = document.getElementById('particles');
const backgroundParticlesManager = new BackgroundParticlesManager(particlesDiv);
const game = new Game(canvas, scoreElem, restartBtn);
// Логируем ключевые события
game.on('gameOver', score => {
logger.info(`Game over. Final score: ${score}`);
});
game.on('bonusPlaced', bonus => {
logger.info(`Bonus placed of type ${bonus.type} at (${bonus.x},${bonus.y})`);
});
game.on('bonusCollectedExternally', bonus => {
logger.info(`Bonus collected: ${bonus.type} at position (${bonus.x},${bonus.y})`);
});
// Для мобильных устройств: поддержка свайпов
(() => {
let touchStartX = null;
let touchStartY = null;
const threshold = 30;
canvas.addEventListener('touchstart', (e) => {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
}, { passive: true });
canvas.addEventListener('touchmove', (e) => {
if (touchStartX === null || touchStartY === null) return;
const touch = e.touches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > threshold) game.snake.setDirection({ x: 1, y: 0 });
else if (dx < -threshold) game.snake.setDirection({ x: -1, y: 0 });
} else {
if (dy > threshold) game.snake.setDirection({ x: 0, y: 1 });
else if (dy < -threshold) game.snake.setDirection({ x: 0, y: -1 });
}
touchStartX = null;
touchStartY = null;
}, { passive: true });
})();
} catch (error) {
console.error('Ошибка инициализации игры:', error);
alert('Произошла ошибка при запуске игры. Пожалуйста, обновите страницу и попробуйте ещё раз.');
}
})();
</script>
</body>
</html>
Snake, GameBoard, Bonus, BonusManager, Particle, BackgroundParticlesManager и основной класс Game.Game с учётом модификатора скорости.GameBoard рисует то, что получает из Snake, BonusManager и т.д.При желании можно вынести каждый класс в отдельный файл и подключать модульно через bundler (webpack/rollup/etc). Также можно добавить unit-тесты — благодаря такой архитектуре это станет гораздо проще.
Если нужно — могу помочь с этим.
Ошибка
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
…обычно связана с расширениями браузера (например, Chrome Extensions), которые слушают сообщения (chrome.runtime.onMessage или похожие API), возвращают true, чтобы указать, что ответ будет отправлен асинхронно, но этого ответа не присылают, в итоге порт сообщения закрывается и возникает ошибка.
true (т.е. сообщает о том, что ответ будет асинхронным), но так и не вызывает функцию sendResponse, порт закрывается и эта ошибка выбрасывается.true из callback для асинхронного ответа, вы обязательно вызвали sendResponse.sendResponse ничего не вызывается, получите ошибку, подобную вашей.// Плохо: возвращаем true, но не вызываем sendResponse
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if(message.type === "async") {
doAsyncTask().then(result => {
sendResponse(result); // вызов sendResponse - ОК
});
return true; // указываем, что ответ будет асинхронным
}
// но если doAsyncTask() выбрасывает ошибку, sendResponse не вызывается => ошибка
});
Верное исправление — гарантировать, что sendResponse всегда вызывается, даже при ошибках.
Ваша игра и её код (в виде HTML+JS) — не вызывают эту ошибку.
Если же ошибка возникает у вас в рамках других ваших расширений или вложенных приложений — дайте знать, могу показать примеры корректных обработчиков сообщений с асинхронным ответом.
Not yet included in a published release.