/
magarich
/
web
Обзор
Документация
Войти
/
magarich
/
web
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
html/lab4/script.js
240 строк
8 KB
Юра Магарьян
Final submission: Lab2 and Lab3 by Magaryan Yury PIZ2402
17 апр 2026, 23:12
17 апр 2026, 23:12
0827836
Код
Авторство
О чём код?
class SpaceBattle { constructor() { this.spaceBattle = document.querySelector('.space-battle'); this.starsContainer = document.querySelector('.stars'); this.ships = []; this.lasers = []; this.explosions = []; this.createStars(); this.createShips(); this.startBattle(); } createStars() { for (let i = 0; i < 200; i++) { const star = document.createElement('div'); star.className = 'star'; star.style.width = Math.random() * 2 + 1 + 'px'; star.style.height = star.style.width; star.style.left = Math.random() * 100 + '%'; star.style.top = Math.random() * 100 + '%'; star.style.opacity = Math.random() * 0.8 + 0.2; star.style.animation = `twinkle ${Math.random() * 3 + 2}s infinite alternate`; this.starsContainer.appendChild(star); } // Добавляем анимацию мерцания в стили const style = document.createElement('style'); style.textContent = ` @keyframes twinkle { 0%, 100% { opacity: 0.2; } 50% { opacity: 1; } } `; document.head.appendChild(style); } createShips() { const shipTypes = ['x-wing', 'tie-fighter', 'falcon']; // Создаем корабли Повстанцев for (let i = 0; i < 3; i++) { this.createShip(shipTypes[0], 'rebel', i * 200 + 100); } // Создаем корабли Империи for (let i = 0; i < 3; i++) { this.createShip(shipTypes[1], 'empire', i * 200 + 150); } // Создаем Millennium Falcon this.createShip(shipTypes[2], 'rebel', 400); } createShip(type, faction, top) { const ship = document.createElement('div'); ship.className = `${type} ${faction}-ship`; ship.dataset.faction = faction; // Начальная позиция if (faction === 'rebel') { ship.style.left = '-100px'; ship.style.top = top + 'px'; } else { ship.style.left = 'calc(100% + 100px)'; ship.style.top = top + 'px'; ship.style.transform = 'scaleX(-1)'; } this.spaceBattle.appendChild(ship); this.ships.push(ship); return ship; } startBattle() { this.moveShips(); this.startShooting(); } moveShips() { this.ships.forEach((ship, index) => { const faction = ship.dataset.faction; let x, y; if (faction === 'rebel') { x = Math.sin(Date.now() * 0.001 + index) * 100 + 200 + index * 50; y = Math.cos(Date.now() * 0.0005 + index) * 50 + (index * 100 + 100); } else { x = Math.cos(Date.now() * 0.001 + index) * 100 + (window.innerWidth - 300 - index * 50); y = Math.sin(Date.now() * 0.0005 + index) * 50 + (index * 100 + 150); } ship.style.left = x + 'px'; ship.style.top = y + 'px'; }); requestAnimationFrame(() => this.moveShips()); } startShooting() { setInterval(() => { this.ships.forEach(ship => { if (Math.random() > 0.7) { // 30% chance to shoot this.createLaser(ship); } }); }, 1000); // Проверка столкновений setInterval(() => this.checkCollisions(), 100); } createLaser(ship) { const laser = document.createElement('div'); const faction = ship.dataset.faction; const rect = ship.getBoundingClientRect(); laser.className = `laser ${faction}`; if (faction === 'rebel') { laser.style.left = (rect.right - 2) + 'px'; laser.style.top = (rect.top + rect.height / 2 - 10) + 'px'; } else { laser.style.left = (rect.left - 2) + 'px'; laser.style.top = (rect.top + rect.height / 2 - 10) + 'px'; } this.spaceBattle.appendChild(laser); this.lasers.push({ element: laser, faction: faction, x: parseInt(laser.style.left), y: parseInt(laser.style.top) }); // Анимация полета лазера this.animateLaser(laser, faction); } animateLaser(laser, faction) { let x = parseInt(laser.style.left); const speed = faction === 'rebel' ? 10 : -10; const animate = () => { x += speed; laser.style.left = x + 'px'; // Удаляем лазер, если он улетел за экран if (x < -100 || x > window.innerWidth + 100) { laser.remove(); this.lasers = this.lasers.filter(l => l.element !== laser); return; } requestAnimationFrame(animate); }; animate(); } checkCollisions() { this.lasers.forEach((laser, laserIndex) => { this.ships.forEach((ship, shipIndex) => { if (laser.faction !== ship.dataset.faction) { const laserRect = laser.element.getBoundingClientRect(); const shipRect = ship.getBoundingClientRect(); if (this.isColliding(laserRect, shipRect)) { this.createExplosion( laserRect.left + laserRect.width / 2, laserRect.top + laserRect.height / 2 ); // Удаляем лазер laser.element.remove(); this.lasers.splice(laserIndex, 1); // Временное мерцание корабля при попадании this.hitEffect(ship); } } }); }); } isColliding(rect1, rect2) { return !(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top > rect2.bottom); } createExplosion(x, y) { const explosion = document.createElement('div'); explosion.className = 'explosion'; explosion.style.left = x + 'px'; explosion.style.top = y + 'px'; this.spaceBattle.appendChild(explosion); // Удаляем взрыв после анимации setTimeout(() => { explosion.remove(); }, 600); } hitEffect(ship) { ship.style.filter = 'brightness(2)'; setTimeout(() => { ship.style.filter = ''; }, 200); } } // Запускаем битву когда страница загрузится document.addEventListener('DOMContentLoaded', () => { new SpaceBattle(); }); // Добавляем звуковые эффекты при клике (опционально) document.addEventListener('click', () => { // Имитация звука лазера const audioContext = new (window.AudioContext || window.webkitAudioContext)(); const oscillator = audioContext.createOscillator(); const gainNode = audioContext.createGain(); oscillator.connect(gainNode); gainNode.connect(audioContext.destination); oscillator.frequency.setValueAtTime(200, audioContext.currentTime); oscillator.frequency.exponentialRampToValueAtTime(100, audioContext.currentTime + 0.1); gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1); oscillator.start(); oscillator.stop(audioContext.currentTime + 0.1); });