Конечно! Я проверил ваш код и исправил обнаруженные ошибки. Основные проблемы были связаны с дублированием классов эффектов и неправильным использованием массивов внутри циклов. Вот исправленный код:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Игра Tower Defense</title>
<style>
body {
margin: 0;
background-color: #1e1e1e;
color: #fff;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overflow: hidden;
position: relative;
}
/* Фон для канваса */
#gameCanvas {
display: none; /* Изначально скрыт */
margin: 0 auto;
background: linear-gradient(to bottom, #2c3e50 0%, #34495e 100%);
border: 2px solid #555;
box-shadow: 0 0 20px rgba(0,0,0,0.5);
display: block; /* Делает канвас видимым при отображении */
}
/* Стили для основного меню */
#mainMenu {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(30, 30, 30, 0.95);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
animation: fadeIn 1s;
z-index: 1000;
}
#mainMenu h1 {
font-size: 64px;
margin-bottom: 50px;
color: #f0db4f;
text-shadow: 2px 2px #000;
animation: slideDown 1s;
}
#mainMenu button {
margin: 15px;
padding: 20px;
font-size: 24px;
width: 250px;
cursor: pointer;
background-color: #f0db4f;
border: none;
border-radius: 10px;
color: #1e1e1e;
transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
box-shadow: 0 5px #cdaa6e;
}
#mainMenu button:active {
transform: translateY(4px);
box-shadow: 0 1px #cdaa6e;
}
#mainMenu button:hover {
background-color: #ffd700;
transform: scale(1.05);
}
/* Анимации */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideDown {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
/* Стили для пользовательского интерфейса */
#ui {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
text-align: center;
display: none;
color: #fff;
z-index: 500;
background: rgba(0, 0, 0, 0.5);
padding: 10px 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.7);
}
#info {
display: inline-block;
margin-right: 20px;
}
#info p {
margin: 5px;
font-size: 18px;
text-shadow: 1px 1px #000;
}
#towerSelection {
display: inline-block;
}
#towerSelection p {
margin: 5px;
font-size: 20px;
text-shadow: 1px 1px #000;
}
#towerSelection button {
margin: 5px;
padding: 10px 15px;
font-size: 16px;
cursor: pointer;
background-color: #555;
border: none;
border-radius: 5px;
color: #fff;
transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
box-shadow: 0 3px #333;
}
#towerSelection button:active {
transform: translateY(2px);
box-shadow: 0 1px #333;
}
#towerSelection button:hover {
background-color: #777;
transform: scale(1.05);
}
/* Стили для меню улучшения башни */
#upgradeMenu {
display: none;
position: absolute;
background-color: rgba(0, 0, 0, 0.95);
padding: 15px;
border: 2px solid #fff;
color: #fff;
border-radius: 10px;
z-index: 1000;
width: 220px;
box-shadow: 0 0 15px rgba(255,255,255,0.5);
animation: fadeIn 0.3s;
}
#upgradeMenu p {
margin: 5px 0;
font-size: 16px;
text-shadow: 1px 1px #000;
}
#upgradeMenu button {
margin: 5px;
padding: 10px;
width: 90px;
font-size: 14px;
cursor: pointer;
background-color: #f0db4f;
border: none;
border-radius: 5px;
color: #1e1e1e;
transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
box-shadow: 0 3px #cdaa6e;
}
#upgradeMenu button:active {
transform: translateY(2px);
box-shadow: 0 1px #cdaa6e;
}
#upgradeMenu button:hover {
background-color: #ffd700;
transform: scale(1.05);
}
/* Стили для экрана окончания игры */
#gameOverScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.85);
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 3000;
animation: fadeIn 1s;
}
#gameOverScreen h1 {
font-size: 48px;
margin-bottom: 20px;
text-shadow: 2px 2px #000;
}
#gameOverScreen p {
font-size: 24px;
margin-bottom: 30px;
text-shadow: 1px 1px #000;
}
#gameOverScreen button {
padding: 15px 30px;
font-size: 20px;
cursor: pointer;
background-color: #f0db4f;
border: none;
border-radius: 10px;
color: #1e1e1e;
transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
box-shadow: 0 5px #cdaa6e;
}
#gameOverScreen button:active {
transform: translateY(4px);
box-shadow: 0 1px #cdaa6e;
}
#gameOverScreen button:hover {
background-color: #ffd700;
transform: scale(1.05);
}
/* Эффекты для башен и врагов */
.tower-effect {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { box-shadow: 0 0 5px #f0db4f; }
50% { box-shadow: 0 0 20px #f0db4f; }
100% { box-shadow: 0 0 5px #f0db4f; }
}
</style>
</head>
<body>
<!-- Главное меню -->
<div id="mainMenu">
<h1>Tower Defense</h1>
<button id="startBtn">Старт</button>
<button id="settingsBtn">Настройки</button>
<button id="leaderboardBtn">Рейтинг</button>
</div>
<!-- Канвас игры -->
<canvas id="gameCanvas" width="800" height="600"></canvas>
<!-- Пользовательский интерфейс -->
<div id="ui">
<div id="info">
<p>Жизни: <span id="lives">20</span></p>
<p>Деньги: $<span id="money">200</span></p>
<p>Уровень: <span id="level">1</span></p>
<p>Очки: <span id="score">0</span></p>
</div>
<div id="towerSelection">
<p>Выберите башню:</p>
<button id="basicTowerBtn">Базовая ($50)</button>
<button id="slowTowerBtn">Замедляющая ($75)</button>
<button id="aoeTowerBtn">Площадная ($100)</button>
<button id="sniperTowerBtn">Снайперская ($150)</button>
</div>
</div>
<!-- Скрипт игры -->
<script>
// Получаем элементы DOM
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const mainMenu = document.getElementById('mainMenu');
const startBtn = document.getElementById('startBtn');
const settingsBtn = document.getElementById('settingsBtn');
const leaderboardBtn = document.getElementById('leaderboardBtn');
const ui = document.getElementById('ui');
const upgradeMenu = document.createElement('div');
upgradeMenu.id = 'upgradeMenu';
document.body.appendChild(upgradeMenu);
// Параметры игры
const game = {
width: canvas.width,
height: canvas.height,
towers: [],
enemies: [],
bullets: [],
money: 200,
lives: 20,
level: 1,
enemySpawnInterval: 2000,
lastEnemySpawn: 0,
selectedTowerType: null,
isBuilding: false,
path: [],
maxLevels: 10,
levelInProgress: false,
score: 0,
nextEnemyId: 1,
paused: false,
gameOver: false,
effects: [] // добавлено инициализация эффектов
};
// Обновление интерфейса
function updateUI() {
document.getElementById('lives').textContent = game.lives;
document.getElementById('money').textContent = game.money;
document.getElementById('level').textContent = game.level;
document.getElementById('score').textContent = game.score;
}
// Класс Башни
class Tower {
constructor(x, y, type) {
this.x = x;
this.y = y;
this.type = type;
this.level = 1;
this.upgradeCost = this.getUpgradeCost();
this.range = this.getRange();
this.damage = this.getDamage();
this.fireRate = this.getFireRate(); // время между выстрелами в миллисекундах
this.timeSinceLastShot = 0;
this.selected = false;
this.rangeCircle = this.range; // для анимации диапазона
}
getUpgradeCost() {
// Пример расчёта стоимости улучшения
return 50 * this.level;
}
getRange() {
switch (this.type) {
case 'basic':
return 100;
case 'slow':
return 120;
case 'aoe':
return 140;
case 'sniper':
return 160;
default:
return 100;
}
}
getDamage() {
switch (this.type) {
case 'basic':
return 10;
case 'slow':
return 8; // меньше урона, но эффект замедления можно добавить позже
case 'aoe':
return 12;
case 'sniper':
return 20;
default:
return 10;
}
}
getFireRate() {
// Время между выстрелами в миллисекундах
switch (this.type) {
case 'basic':
return 1000; // 1 выстрел в секунду
case 'slow':
return 1200;
case 'aoe':
return 1500;
case 'sniper':
return 2000;
default:
return 1000;
}
}
upgrade() {
const cost = this.upgradeCost;
if (game.money >= cost) {
game.money -= cost;
this.level += 1;
this.upgradeCost = this.getUpgradeCost();
this.range = this.getRange(); // можно увеличить дальность с уровнем
this.damage = this.getDamage(); // можно увеличить урон с уровнем
updateUI();
} else {
alert('Недостаточно денег для улучшения!');
}
}
draw() {
// Рисуем башню как круг с градиентом
const gradient = ctx.createRadialGradient(this.x, this.y, 5, this.x, this.y, 20);
switch (this.type) {
case 'basic':
gradient.addColorStop(0, '#2980b9');
gradient.addColorStop(1, '#3498db');
break;
case 'slow':
gradient.addColorStop(0, '#c0392b');
gradient.addColorStop(1, '#e74c3c');
break;
case 'aoe':
gradient.addColorStop(0, '#27ae60');
gradient.addColorStop(1, '#2ecc71');
break;
case 'sniper':
gradient.addColorStop(0, '#8e44ad');
gradient.addColorStop(1, '#9b59b6');
break;
default:
gradient.addColorStop(0, '#2980b9');
gradient.addColorStop(1, '#3498db');
}
ctx.beginPath();
ctx.arc(this.x, this.y, 20, 0, 2 * Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
ctx.strokeStyle = this.selected ? '#fff' : '#2c3e50';
ctx.lineWidth = 3;
ctx.stroke();
// Отображение диапазона при выборе башни
if (this.selected) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.range, 0, 2 * Math.PI);
ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
ctx.lineWidth = 2;
ctx.stroke();
}
}
update(deltaTime) {
this.timeSinceLastShot += deltaTime;
if (this.timeSinceLastShot >= this.fireRate) {
// Поиск цели
const target = game.enemies.find(enemy => {
const dist = Math.hypot(this.x - enemy.x, this.y - enemy.y);
return dist <= this.range;
});
if (target) {
// Создание пули
game.bullets.push(new Bullet(this.x, this.y, target, this));
this.timeSinceLastShot = 0;
// Добавление эффекта стрельбы
game.effects.push(new ShootingEffect(this.x, this.y));
}
}
}
}
// Класс Врага
class Enemy {
constructor(path, type, id) {
this.path = path; // Массив точек пути
this.type = type;
this.id = id;
this.currentSegment = 0;
this.x = path[0].x;
this.y = path[0].y;
this.speed = this.getSpeed();
this.health = this.getHealth();
this.markedForDeletion = false;
this.alpha = 1; // Для плавного исчезновения
this.isSlowed = false;
this.slowTimer = 0;
this.slowDuration = 2000; // длительность замедления в мс
this.originalSpeed = this.speed;
}
getSpeed() {
switch (this.type) {
case 'basic':
return 100; // пикселей в секунду
case 'fast':
return 150;
case 'tank':
return 60;
default:
return 100;
}
}
getHealth() {
switch (this.type) {
case 'basic':
return 100;
case 'fast':
return 75;
case 'tank':
return 200;
default:
return 100;
}
}
takeDamage(damage) {
this.health -= damage;
if (this.health <= 0) {
this.markedForDeletion = true;
game.score += 10; // Пример увеличения очков
game.money += 50; // Награда за убийство
// Добавление эффекта взрыва
game.effects.push(new ExplosionEffect(this.x, this.y));
updateUI();
}
}
slow() {
if (!this.isSlowed) {
this.isSlowed = true;
this.speed = this.originalSpeed * 0.6; // замедление на 40%
}
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
// Рисуем врага с градиентом
const gradient = ctx.createRadialGradient(this.x, this.y, 5, this.x, this.y, 15);
gradient.addColorStop(0, '#ecf0f1');
gradient.addColorStop(1, '#bdc3c7');
ctx.beginPath();
ctx.arc(this.x, this.y, 15, 0, 2 * Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
ctx.strokeStyle = '#2c3e50';
ctx.lineWidth = 2;
ctx.stroke();
// Отображение здоровья
ctx.fillStyle = '#e74c3c';
ctx.fillRect(this.x - 15, this.y - 20, 30 * (this.health / this.getHealth()), 5);
ctx.strokeStyle = '#000';
ctx.strokeRect(this.x - 15, this.y - 20, 30, 5);
ctx.restore();
}
update(deltaTime) {
if (this.isSlowed) {
this.slowTimer += deltaTime;
if (this.slowTimer >= this.slowDuration) {
this.isSlowed = false;
this.speed = this.originalSpeed;
this.slowTimer = 0;
}
}
if (this.markedForDeletion) {
this.alpha -= 0.02; // Скорость исчезновения
if (this.alpha <= 0) {
this.alpha = 0;
}
return;
}
if (this.currentSegment >= this.path.length - 1) {
// Достиг конца пути
game.lives -= 1;
updateUI();
this.markedForDeletion = true;
return;
}
const targetX = this.path[this.currentSegment + 1].x;
const targetY = this.path[this.currentSegment + 1].y;
const dx = targetX - this.x;
const dy = targetY - this.y;
const distance = Math.hypot(dx, dy);
const moveDistance = (this.speed * deltaTime) / 1000;
if (distance < moveDistance) {
this.x = targetX;
this.y = targetY;
this.currentSegment += 1;
} else {
this.x += (dx / distance) * moveDistance;
this.y += (dy / distance) * moveDistance;
}
}
}
// Класс Пули
class Bullet {
constructor(x, y, target, tower) {
this.x = x;
this.y = y;
this.target = target;
this.tower = tower;
this.speed = 500; // пикселей в секунду
this.damage = tower.damage;
this.markedForDeletion = false;
this.color = '#f1c40f';
this.radius = 5;
this.angle = Math.atan2(target.y - y, target.x - x);
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
ctx.strokeStyle = '#bdc3c7';
ctx.stroke();
}
update(deltaTime) {
const dx = this.target.x - this.x;
const dy = this.target.y - this.y;
const distance = Math.hypot(dx, dy);
const moveDistance = (this.speed * deltaTime) / 1000;
if (distance < moveDistance) {
// Попадание во врага
if (this.target.isSlowed === false && this.tower.type === 'slow') {
this.target.slow();
}
this.target.takeDamage(this.damage);
this.markedForDeletion = true;
// Добавление эффекта попадания
game.effects.push(new HitEffect(this.target.x, this.target.y));
} else {
this.x += Math.cos(this.angle) * moveDistance;
this.y += Math.sin(this.angle) * moveDistance;
}
}
}
// Класс Эффектов (например, взрывы, попадания)
class Effect {
constructor(x, y) {
this.x = x;
this.y = y;
this.alpha = 1;
this.markedForDeletion = false;
}
draw() {
// Перегружаемый метод
}
update(deltaTime) {
// Перегружаемый метод
}
}
class ExplosionEffect extends Effect {
constructor(x, y) {
super(x, y);
this.radius = 10;
this.maxRadius = 30;
this.growthRate = 0.2;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(231, 76, 60, 0.7)';
ctx.fill();
ctx.strokeStyle = 'rgba(192, 57, 43, 0.9)';
ctx.lineWidth = 2;
ctx.stroke();
ctx.restore();
}
update(deltaTime) {
this.radius += this.growthRate * deltaTime / 16; // адаптация к fps
this.alpha -= 0.02;
if (this.radius >= this.maxRadius || this.alpha <= 0) {
this.markedForDeletion = true;
}
}
}
class HitEffect extends Effect {
constructor(x, y) {
super(x, y);
this.radius = 3;
this.maxRadius = 10;
this.growthRate = 0.3;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(241, 196, 15, 0.8)';
ctx.fill();
ctx.restore();
}
update(deltaTime) {
this.radius += this.growthRate * deltaTime / 16;
this.alpha -= 0.03;
if (this.radius >= this.maxRadius || this.alpha <= 0) {
this.markedForDeletion = true;
}
}
}
class ShootingEffect extends Effect {
constructor(x, y) {
super(x, y);
this.radius = 2;
this.maxRadius = 10;
this.growthRate = 0.1;
this.alpha = 0.8;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = '#f0db4f';
ctx.fill();
ctx.restore();
}
update(deltaTime) {
this.radius += this.growthRate * deltaTime / 16;
this.alpha -= 0.02;
if (this.radius >= this.maxRadius || this.alpha <= 0) {
this.markedForDeletion = true;
}
}
}
// Создание пути врагов
function createPath() {
// Пример более сложного пути - можно настроить по желанию
game.path = [
{x: 0, y: 150},
{x: 250, y: 150},
{x: 250, y: 300},
{x: 500, y: 300},
{x: 500, y: 450},
{x: 800, y: 450}
];
}
// Проверка, находится ли точка на пути
function isOnPath(x, y) {
// Простая проверка: если точка находится в пределах некоторого расстояния от любого сегмента пути
const threshold = 20; // пикселей
for (let i = 0; i < game.path.length - 1; i++) {
const p1 = game.path[i];
const p2 = game.path[i + 1];
const dist = pointToSegmentDistance({x, y}, p1, p2);
if (dist < threshold) {
return true;
}
}
return false;
}
// Вспомогательная функция для расчёта расстояния от точки до сегмента
function pointToSegmentDistance(p, p1, p2) {
const A = p.x - p1.x;
const B = p.y - p1.y;
const C = p2.x - p1.x;
const D = p2.y - p1.y;
const dot = A * C + B * D;
const len_sq = C * C + D * D;
let param = -1;
if (len_sq !== 0) // проверка на нулевую длину линии
param = dot / len_sq;
let xx, yy;
if (param < 0) {
xx = p1.x;
yy = p1.y;
}
else if (param > 1) {
xx = p2.x;
yy = p2.y;
}
else {
xx = p1.x + param * C;
yy = p1.y + param * D;
}
const dx = p.x - xx;
const dy = p.y - yy;
return Math.hypot(dx, dy);
}
// Генерация врагов для текущего уровня
function spawnEnemies() {
if (!game.levelInProgress) return;
const now = Date.now();
if (now - game.lastEnemySpawn > game.enemySpawnInterval) {
// Разные типы врагов могут появляться в зависимости от уровня
let enemyType = 'basic';
if (game.level % 3 === 0) {
enemyType = 'fast';
} else if (game.level % 5 === 0) {
enemyType = 'tank';
}
game.enemies.push(new Enemy(game.path, enemyType, game.nextEnemyId++));
game.lastEnemySpawn = now;
}
}
// Проверка окончания уровня
function checkLevelEnd() {
if (game.levelInProgress && game.enemies.length === 0 && game.bullets.length === 0 && !game.gameOver) {
game.level += 1;
if (game.level > game.maxLevels) {
gameOver(true); // Игрок прошёл все уровни
} else {
startLevel();
}
}
}
function resetLevel() {
// Сброс параметров уровня, если необходимо
game.levelInProgress = false;
game.enemies = [];
game.bullets = [];
game.effects = [];
}
// Начало уровня
function startLevel() {
game.levelInProgress = true;
game.enemySpawnInterval = Math.max(500, 2000 - game.level * 100);
game.lastEnemySpawn = Date.now() - game.enemySpawnInterval;
}
// Отображение пути
function drawPath() {
ctx.beginPath();
ctx.moveTo(game.path[0].x, game.path[0].y);
for (let i = 1; i < game.path.length; i++) {
ctx.lineTo(game.path[i].x, game.path[i].y);
}
ctx.strokeStyle = '#95a5a6';
ctx.lineWidth = 30;
ctx.shadowColor = '#7f8c8d';
ctx.shadowBlur = 10;
ctx.stroke();
ctx.shadowBlur = 0;
}
// Главный цикл игры
let lastTime = 0;
function gameLoop(timestamp) {
if (game.paused || game.gameOver) {
requestAnimationFrame(gameLoop);
return;
}
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.clearRect(0, 0, game.width, game.height);
// Отрисовка пути
drawPath();
// Обновление и рисование башен
game.towers.forEach(tower => {
tower.update(deltaTime);
tower.draw();
});
// Спавн врагов
spawnEnemies();
// Обновление и рисование врагов
game.enemies.forEach(enemy => {
enemy.update(deltaTime);
enemy.draw();
});
// Обновление и рисование пуль
game.bullets.forEach(bullet => {
bullet.update(deltaTime);
bullet.draw();
});
// Обновление и рисование эффектов
game.effects.forEach(effect => {
effect.update(deltaTime);
effect.draw();
});
// Удаление объектов, отмеченных для удаления
game.bullets = game.bullets.filter(bullet => !bullet.markedForDeletion);
game.enemies = game.enemies.filter(enemy => !enemy.markedForDeletion || enemy.alpha > 0);
game.effects = game.effects.filter(effect => !effect.markedForDeletion);
checkLevelEnd();
// Проверка проигрыша
if (game.lives <= 0) {
gameOver(false);
} else {
requestAnimationFrame(gameLoop);
}
}
// Конец игры
function gameOver(won) {
game.gameOver = true;
hideUpgradeMenu();
ui.style.display = 'none';
canvas.style.display = 'none';
// Создание экрана окончания игры
const gameOverScreen = document.createElement('div');
gameOverScreen.id = 'gameOverScreen';
const message = document.createElement('h1');
message.textContent = won ? 'Поздравляем! Вы выиграли!' : 'Игра окончена!';
message.style.fontSize = '48px';
message.style.textAlign = 'center';
const scoreDisplay = document.createElement('p');
scoreDisplay.textContent = `Ваши очки: ${game.score}`;
scoreDisplay.style.fontSize = '24px';
const restartBtn = document.createElement('button');
restartBtn.textContent = 'Играть снова';
restartBtn.addEventListener('click', () => {
document.body.removeChild(gameOverScreen);
hideUpgradeMenu();
showMainMenu();
});
gameOverScreen.appendChild(message);
gameOverScreen.appendChild(scoreDisplay);
gameOverScreen.appendChild(restartBtn);
document.body.appendChild(gameOverScreen);
}
// Обработка установки башен
canvas.addEventListener('click', (e) => {
if (game.paused || game.gameOver) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (game.isBuilding && game.selectedTowerType) {
let cost;
switch (game.selectedTowerType) {
case 'basic':
cost = 50;
break;
case 'slow':
cost = 75;
break;
case 'aoe':
cost = 100;
break;
case 'sniper':
cost = 150;
break;
default:
cost = 50;
}
if (game.money >= cost) {
// Проверяем, чтобы башня не ставилась на путь
if (!isOnPath(x, y)) {
game.towers.push(new Tower(x, y, game.selectedTowerType));
game.money -= cost;
updateUI();
game.isBuilding = false;
game.selectedTowerType = null;
} else {
alert('Нельзя ставить башню на путь!');
}
} else {
alert('Недостаточно денег!');
}
} else {
// Проверяем, нажата ли башня
const tower = game.towers.find(tower => {
const dist = Math.hypot(tower.x - x, tower.y - y);
return dist <= 20;
});
if (tower) {
game.towers.forEach(t => t.selected = false);
tower.selected = true;
showUpgradeMenu(e.clientX, e.clientY, tower);
} else {
hideUpgradeMenu();
game.towers.forEach(t => t.selected = false);
}
}
});
// Выбор типа башни
document.getElementById('basicTowerBtn').addEventListener('click', () => {
game.selectedTowerType = 'basic';
game.isBuilding = true;
});
document.getElementById('slowTowerBtn').addEventListener('click', () => {
game.selectedTowerType = 'slow';
game.isBuilding = true;
});
document.getElementById('aoeTowerBtn').addEventListener('click', () => {
game.selectedTowerType = 'aoe';
game.isBuilding = true;
});
document.getElementById('sniperTowerBtn').addEventListener('click', () => {
game.selectedTowerType = 'sniper';
game.isBuilding = true;
});
// Меню улучшения башни
function showUpgradeMenu(x, y, tower) {
// Позиционируем меню рядом с курсором, но не выходя за границы окна
const menuWidth = 220;
const menuHeight = 180;
const pageWidth = window.innerWidth;
const pageHeight = window.innerHeight;
let posX = x + 10;
let posY = y + 10;
if (x + menuWidth > pageWidth) posX = x - menuWidth - 10;
if (y + menuHeight > pageHeight) posY = y - menuHeight - 10;
upgradeMenu.style.left = posX + 'px';
upgradeMenu.style.top = posY + 'px';
upgradeMenu.style.display = 'block';
upgradeMenu.innerHTML = `
<p>Уровень башни: ${tower.level}</p>
<p>Стоимость улучшения: $${tower.upgradeCost}</p>
<button id="upgradeBtn">Улучшить</button>
<button id="sellBtn">Продать</button>
`;
// Удаляем предыдущие обработчики событий, чтобы избежать накопления
const upgradeBtn = document.getElementById('upgradeBtn');
const sellBtn = document.getElementById('sellBtn');
// Клонируем кнопку, чтобы удалить старые слушатели
const newUpgradeBtn = upgradeBtn.cloneNode(true);
upgradeBtn.parentNode.replaceChild(newUpgradeBtn, upgradeBtn);
const newSellBtn = sellBtn.cloneNode(true);
sellBtn.parentNode.replaceChild(newSellBtn, sellBtn);
newUpgradeBtn.addEventListener('click', () => {
tower.upgrade();
hideUpgradeMenu();
});
newSellBtn.addEventListener('click', () => {
const refund = Math.floor(tower.upgradeCost / 2) * tower.level;
game.money += refund;
game.towers = game.towers.filter(t => t !== tower);
hideUpgradeMenu();
updateUI();
});
}
function hideUpgradeMenu() {
upgradeMenu.style.display = 'none';
}
// Главное меню
startBtn.addEventListener('click', () => {
hideMainMenu();
startGame();
});
settingsBtn.addEventListener('click', () => {
alert('Здесь будут настройки');
});
leaderboardBtn.addEventListener('click', () => {
alert('Здесь будет рейтинг');
});
function showMainMenu() {
mainMenu.style.display = 'flex';
ui.style.display = 'none';
canvas.style.display = 'none';
game.paused = true;
game.gameOver = false;
}
function hideMainMenu() {
mainMenu.style.display = 'none';
ui.style.display = 'block';
canvas.style.display = 'block';
game.paused = false;
}
function startGame() {
resetGame();
createPath();
updateUI();
startLevel();
requestAnimationFrame(gameLoop);
}
function resetGame() {
// Сброс всех параметров игры
game.towers = [];
game.enemies = [];
game.bullets = [];
game.effects = [];
game.money = 200;
game.lives = 20;
game.level = 1;
game.score = 0;
game.nextEnemyId = 1;
game.levelInProgress = false;
game.gameOver = false;
game.paused = false;
updateUI();
}
// Показ главного меню при загрузке
showMainMenu();
</script>
</body>
</html>
Изменения и исправления:
-
Удалено дублирование классов эффектов: В исходном коде классы Effect, ExplosionEffect, HitEffect и ShootingEffect были определены дважды. Я удалил второе определение этих классов.
-
Добавлена инициализация массива эффектов: В объекте game добавлено свойство effects: [], чтобы избежать ошибок при обращении к game.effects.
-
Исправлено удаление объектов внутри циклов: В цикле gameLoop удаление врагов из массива game.enemies происходило внутри функции forEach, что могло привести к ошибкам. Я перенёс удаление помеченных для удаления врагов после цикла с помощью фильтрации массива.
-
Обновлено управление прозрачностью врагов: Добавил уменьшение alpha внутри метода update класса Enemy, чтобы контролировать плавное исчезновение врагов при их удалении.
-
Обновлён метод takeDamage врага: Добавил вызов updateUI() для обновления интерфейса при уничтожении врага.
-
Исправлено обновление интерфейса при прохождении врагами до конца пути: В методе update класса Enemy при уменьшении жизней игрока вызывается updateUI().
-
Убедился, что классы и функции определены в правильном порядке: Это гарантирует, что все классы доступны к тому моменту, когда они используются.
Теперь код должен работать корректно без ошибок. Если у вас возникнут дополнительные вопросы или проблемы, пожалуйста, дайте мне знать!