исправь ошибки анимируй и визуализируй <!DOCTYPE html> <html lang="ru"> <head> <meta…
- User
исправь ошибки анимируй и визуализируй
canvas { border: 1px solid #000; background-color: #444; display: block; margin: 0 auto; } #ui { text-align: center; margin-top: 10px; } #info { display: inline-block; margin-right: 20px; } #towerSelection { display: inline-block; } #towerSelection button { margin: 5px; padding: 10px; } #upgradeMenu { display: none; position: absolute; background-color: rgba(0, 0, 0, 0.8); padding: 10px; border: 1px solid #fff; } #upgradeMenu button { margin: 5px; padding: 5px; } </style>// Параметры игры 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 }; // Обновление интерфейса 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.setProperties(); this.lastShotTime = 0; this.selected = false; } setProperties() { switch (this.type) { case 'basic': this.range = 120; this.fireRate = 800; this.damage = 50; this.level = 1; this.upgradeCost = 50; this.color = 'blue'; break; case 'slow': this.range = 100; this.fireRate = 1200; this.damage = 30; this.slowEffect = 0.5; this.slowDuration = 2000; this.level = 1; this.upgradeCost = 75; this.color = 'cyan'; break; case 'aoe': this.range = 80; this.fireRate = 1500; this.damage = 40; this.aoeRange = 50; this.level = 1; this.upgradeCost = 100; this.color = 'purple'; break; case 'sniper': this.range = 300; this.fireRate = 2000; this.damage = 100; this.level = 1; this.upgradeCost = 150; this.color = 'orange'; break; } } draw() { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, 15, 0, Math.PI * 2); ctx.fill(); if (this.selected) { ctx.strokeStyle = 'cyan'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(this.x, this.y, this.range, 0, Math.PI * 2); ctx.stroke(); } } update(deltaTime) { if (Date.now() - this.lastShotTime > this.fireRate) { const target = this.findTarget(); if (target) { this.shoot(target); this.lastShotTime = Date.now(); } } } findTarget() { if (this.type === 'sniper') { // Снайперская башня выбирает самого дальнего врага const enemiesInRange = game.enemies.filter(enemy => { const dist = Math.hypot(enemy.x - this.x, enemy.y - this.y); return dist <= this.range; }); if (enemiesInRange.length > 0) { return enemiesInRange.reduce((farthest, enemy) => { return enemy.distanceTraveled > farthest.distanceTraveled ? enemy : farthest; }); } } else { // Остальные башни выбирают ближайшего врага return game.enemies.find(enemy => { const dist = Math.hypot(enemy.x - this.x, enemy.y - this.y); return dist <= this.range; }); } return null; } shoot(target) { game.bullets.push(new Bullet(this.x, this.y, target, this)); } upgrade() { if (game.money >= this.upgradeCost) { game.money -= this.upgradeCost; this.level++; this.damage *= 1.5; this.range *= 1.1; this.fireRate *= 0.9; this.upgradeCost = Math.floor(this.upgradeCost * 1.5); updateUI(); } else { alert('Недостаточно денег для улучшения!'); } } } // Класс Врага class Enemy { constructor(path, type, id) { this.path = path; this.currentPoint = 0; this.x = path[0].x; this.y = path[0].y; this.type = type; this.id = id; // Уникальный идентификатор врага this.setProperties(); this.speedModifier = 1; this.slowDuration = 0; this.maxHealth = this.health; this.distanceTraveled = 0; this.markedForDeletion = false; } setProperties() { const levelMultiplier = game.level; switch (this.type) { case 'normal': this.speed = 80 + levelMultiplier * 2; this.health = 100 + levelMultiplier * 20; this.reward = 15; this.color = 'green'; break; case 'fast': this.speed = 120 + levelMultiplier * 3; this.health = 80 + levelMultiplier * 15; this.reward = 10; this.color = 'lime'; break; case 'tough': this.speed = 60 + levelMultiplier * 1.5; this.health = 200 + levelMultiplier * 30; this.reward = 25; this.color = 'brown'; break; case 'flying': this.speed = 100 + levelMultiplier * 2; this.health = 120 + levelMultiplier * 20; this.reward = 20; this.color = 'skyblue'; this.flying = true; // Некоторые башни могут не атаковать летающих break; case 'boss': this.speed = 50 + levelMultiplier; this.health = 1000 + levelMultiplier * 100; this.reward = 200; this.color = 'red'; break; } } draw() { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, 15, 0, Math.PI * 2); ctx.fill(); // Отрисовка полоски здоровья ctx.fillStyle = 'red'; ctx.fillRect(this.x - 15, this.y - 20, 30, 5); ctx.fillStyle = 'green'; ctx.fillRect(this.x - 15, this.y - 20, 30 * (this.health / this.maxHealth), 5); } update(deltaTime) { if (this.slowDuration > 0) { this.slowDuration -= deltaTime; if (this.slowDuration <= 0) { this.speedModifier = 1; } } const targetPoint = this.path[this.currentPoint + 1]; if (targetPoint) { const dx = targetPoint.x - this.x; const dy = targetPoint.y - this.y; const dist = Math.hypot(dx, dy); const moveDist = this.speed * this.speedModifier * (deltaTime / 1000); if (moveDist >= dist) { this.x = targetPoint.x; this.y = targetPoint.y; this.currentPoint++; } else { this.x += dx / dist * moveDist; this.y += dy / dist * moveDist; } this.distanceTraveled += moveDist; } else { // Враг достиг конца пути game.lives--; this.markedForDeletion = true; updateUI(); } } slow(amount, duration) { this.speedModifier = amount; this.slowDuration = duration; } } // Класс Пули class Bullet { constructor(x, y, target, tower) { this.x = x; this.y = y; this.target = target; this.tower = tower; this.speed = 400; this.color = this.getBulletColor(); this.markedForDeletion = false; } getBulletColor() { switch (this.tower.type) { case 'basic': return 'yellow'; case 'slow': return 'lightblue'; case 'aoe': return 'magenta'; case 'sniper': return 'orange'; } } draw() { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, 5, 0, Math.PI * 2); ctx.fill(); } update(deltaTime) { const dx = this.target.x - this.x; const dy = this.target.y - this.y; const dist = Math.hypot(dx, dy); const moveDist = this.speed * (deltaTime / 1000); if (dist <= moveDist || this.target.markedForDeletion) { // Пуля достигает цели this.hitTarget(); this.markedForDeletion = true; } else { this.x += dx / dist * moveDist; this.y += dy / dist * moveDist; } } hitTarget() { if (this.tower.type === 'aoe') { // Наносим урон по области game.enemies.forEach(enemy => { const dist = Math.hypot(enemy.x - this.target.x, enemy.y - this.target.y); if (dist <= this.tower.aoeRange) { enemy.health -= this.tower.damage; if (enemy.health <= 0 && !enemy.markedForDeletion) { enemy.markedForDeletion = true; game.money += enemy.reward; game.score += enemy.reward; updateUI(); } } }); } else { this.target.health -= this.tower.damage; if (this.tower.type === 'slow') { this.target.slow(this.tower.slowEffect, this.tower.slowDuration); } if (this.target.health <= 0 && !this.target.markedForDeletion) { this.target.markedForDeletion = true; game.money += this.target.reward; game.score += this.target.reward; updateUI(); } } } } // Создание пути врагов function createPath() { game.path = [ { x: 0, y: 150 }, { x: 150, y: 150 }, { x: 150, y: 450 }, { x: 300, y: 450 }, { x: 300, y: 150 }, { x: 450, y: 150 }, { x: 450, y: 450 }, { x: 600, y: 450 }, { x: 600, y: 150 }, { x: 750, y: 150 }, { x: 800, y: 200 } ]; } // Генерация врагов для текущего уровня function spawnEnemies() { if (!game.levelInProgress) return; if (Date.now() - game.lastEnemySpawn > game.enemySpawnInterval) { let enemyType; const level = game.level; if (level % 5 === 0 && game.enemies.length === 0) { enemyType = 'boss'; } else { const rand = Math.random(); if (rand < 0.4) { enemyType = 'normal'; } else if (rand < 0.6) { enemyType = 'fast'; } else if (rand < 0.8) { enemyType = 'tough'; } else { enemyType = 'flying'; } } game.enemies.push(new Enemy(game.path, enemyType, game.nextEnemyId++)); game.lastEnemySpawn = Date.now(); } } // Проверка окончания уровня function checkLevelEnd() { if (game.enemies.length === 0 && game.levelInProgress && game.lives > 0) { game.level++; if (game.level > game.maxLevels) { // Победа gameOver(true); } else { game.levelInProgress = false; updateUI(); setTimeout(() => { alert(`Уровень ${game.level - 1} завершен! Подготовьтесь к следующему уровню.`); startLevel(); }, 1000); } } } // Начало уровня function startLevel() { game.levelInProgress = true; game.enemySpawnInterval = Math.max(500, 2000 - game.level * 100); game.lastEnemySpawn = Date.now(); } // Отображение пути function drawPath() { ctx.strokeStyle = 'yellow'; ctx.lineWidth = 2; 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.stroke(); } // Главный цикл игры let lastTime = 0; function gameLoop(timestamp) { 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.enemies = game.enemies.filter(enemy => !enemy.markedForDeletion); game.bullets = game.bullets.filter(bullet => !bullet.markedForDeletion); checkLevelEnd(); // Проверка проигрыша if (game.lives <= 0) { gameOver(false); } else { requestAnimationFrame(gameLoop); } } // Конец игры function gameOver(won) { game.levelInProgress = false; ctx.fillStyle = 'white'; ctx.font = '50px Arial'; ctx.textAlign = 'center'; if (won) { ctx.fillText('Вы победили!', game.width / 2, game.height / 2); } else { ctx.fillText('Игра окончена', game.width / 2, game.height / 2); } } // Обработка установки башен canvas.addEventListener('click', (e) => { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; if (game.isBuilding) { 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; } if (game.money >= cost) { // Проверяем, чтобы башня не ставилась на путь if (!isOnPath(x, y)) { game.towers.push(new Tower(x, y, game.selectedTowerType)); game.money -= cost; updateUI(); } else { alert('Нельзя ставить башню на путь!'); } } else { alert('Недостаточно денег!'); } game.isBuilding = false; } 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); } } }); // Проверка, находится ли точка на пути function isOnPath(x, y) { for (let i = 0; i < game.path.length - 1; i++) { const start = game.path[i]; const end = game.path[i + 1]; const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.hypot(dx, dy); const t = ((x - start.x) * dx + (y - start.y) * dy) / (length * length); if (t >= 0 && t <= 1) { const closestX = start.x + t * dx; const closestY = start.y + t * dy; const dist = Math.hypot(x - closestX, y - closestY); if (dist < 25) { return true; } } } return 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; }); // Меню улучшения башни const upgradeMenu = document.createElement('div'); upgradeMenu.id = 'upgradeMenu'; document.body.appendChild(upgradeMenu); function showUpgradeMenu(x, y, tower) { upgradeMenu.style.left = x + 'px'; upgradeMenu.style.top = y + 'px'; upgradeMenu.style.display = 'block'; upgradeMenu.innerHTML = ` <p>Уровень башни: ${tower.level}</p> <p>Стоимость улучшения: $${tower.upgradeCost}</p> <button id="upgradeBtn">Улучшить</button> <button id="sellBtn">Продать</button> `; document.getElementById('upgradeBtn').addEventListener('click', () => { tower.upgrade(); hideUpgradeMenu(); }); document.getElementById('sellBtn').addEventListener('click', () => { game.money += Math.floor((tower.upgradeCost / 2) * (tower.level)); game.towers = game.towers.filter(t => t !== tower); hideUpgradeMenu(); updateUI(); }); } function hideUpgradeMenu() { upgradeMenu.style.display = 'none'; } // Запуск игры createPath(); updateUI(); startLevel(); requestAnimationFrame(gameLoop); </script> - Assistant