0% found this document useful (0 votes)
39 views19 pages

Game

Uploaded by

devinder98141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views19 pages

Game

Uploaded by

devinder98141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

{

"configurations": [
{
"name": "Launch Chrome",
"request": "launch",
"type": "chrome",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seam Shooter 2D (Complete)</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000;
font-family: 'Inter', sans-serif;
color: #fff;
flex-direction: column;
overflow: hidden;
}
canvas {
background-color: transparent;
border: 2px solid #fff;
border-radius: 10px;
box-shadow: 0 0 20px rgba(255, 255, 255, 0.3);
cursor: none; /* Hide default cursor */
}
#ui-container {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 20px;
font-size: 1.5rem;
font-weight: bold;
color: #fff;
padding: 10px 20px;
border-radius: 8px;
z-index: 10;
background-color: rgba(0, 0, 0, 0.5);
min-width: 300px;
justify-content: space-between;
}
#boss-health-bar-container {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-width: 600px;
height: 25px;
background-color: #333;
border-radius: 5px;
border: 2px solid #fff;
overflow: hidden;
display: none;
z-index: 10;
}
#boss-health-bar {
height: 100%;
width: 100%;
background-color: #e74c3c;
transition: width 0.3s ease-in-out;
}
#main-menu, #message-box, #pause-menu {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 30px;
border-radius: 10px;
text-align: center;
font-size: 1.5rem;
border: 2px solid #fff;
z-index: 1000;
}
#main-menu h1, #message-box h1, #pause-menu h1 {
font-size: 3rem;
margin-bottom: 20px;
}
.button-group {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
margin-top: 20px;
}
button {
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
border: none;
background-color: #4CAF50;
color: white;
border-radius: 5px;
transition: transform 0.1s ease-in-out;
width: 200px;
}
button:hover {
transform: scale(1.05);
}
#difficulty-select button, #player-select button {
background-color: #3498db;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/Tone.min.js"></
script>
</head>
<body>
<div id="ui-container" style="display: none;">
<div id="score-display">Score: 0</div>
<div id="lives-display">Lives: 3</div>
<div id="high-score-display">High Score: 0</div>
</div>
<div id="boss-health-bar-container">
<div id="boss-health-bar"></div>
</div>
<canvas id="gameCanvas"></canvas>

<!-- Starry background canvas -->


<canvas id="backgroundCanvas" style="position: absolute; top: 0; left: 0; z-
index: -1;"></canvas>

<!-- Game Menus -->


<div id="main-menu">
<h1>Seam Shooter 2D</h1>
<p style="font-size: 1rem;">Use mouse to move and click to shoot. Press 'P'
to pause.</p>
<div class="button-group">
<p>Select Difficulty:</p>
<div id="difficulty-select">
<button data-difficulty="easy">Easy</button>
<button data-difficulty="medium">Medium</button>
<button data-difficulty="hard">Hard</button>
</div>
<p style="margin-top: 20px;">Select Player Ship:</p>
<div id="player-select">
<button data-emoji="🚀">🚀</button>
<button data-emoji="🚗">🚗</button>
<button data-emoji="☄️">☄️

</button>
</div>
<p id="high-score-menu-display" style="margin-top: 20px;">High Score:
0</p>
<button id="start-game-btn" style="margin-top: 20px;">Start
Game</button>
</div>
</div>

<div id="message-box" style="display: none;">


<p id="game-message">Game Over!</p>
<p id="final-stats"></p>
<div class="button-group">
<button id="restart-game-btn">Restart</button>
</div>
</div>

<div id="pause-menu" style="display: none;">


<h1>Game Paused</h1>
<p>Press 'P' or click to resume.</p>
<button id="resume-btn">Resume</button>
<button id="main-menu-btn">Main Menu</button>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const bgCanvas = document.getElementById('backgroundCanvas');
const bgCtx = bgCanvas.getContext('2d');
let animationFrameId = null;
let bgAnimationFrameId = null;

// UI Elements
const scoreDisplay = document.getElementById('score-display');
const livesDisplay = document.getElementById('lives-display');
const highScoreDisplay = document.getElementById('high-score-display');
const uiContainer = document.getElementById('ui-container');
const mainMenu = document.getElementById('main-menu');
const messageBox = document.getElementById('message-box');
const pauseMenu = document.getElementById('pause-menu');
const bossHealthBarContainer = document.getElementById('boss-health-bar-
container');
const bossHealthBar = document.getElementById('boss-health-bar');
const startButton = document.getElementById('start-game-btn');
const restartButton = document.getElementById('restart-game-btn');
const difficultyButtons = document.querySelectorAll('#difficulty-select
button');
const playerButtons = document.querySelectorAll('#player-select button');
const resumeButton = document.getElementById('resume-btn');
const mainMenuButton = document.getElementById('main-menu-btn');

// Audio Setup
let shootSynth = null;
let hitSynth = null;
let powerUpSynth = null;
let bombSynth = null;
let bossHitSynth = null;
let backgroundMusic = null;

// Game state variables


let score = 0;
let lives = 3;
let highScore = localStorage.getItem('seamShooterHighScore') || 0;
let gameOver = false;
let gameStarted = false;
let isPaused = false;
let currentDifficulty = 'easy';
let rapidFireActive = false;
let rapidFireTimer = null;
let scoreMultiplierActive = false;
let scoreMultiplierTimer = null;
let shieldActive = false;
let shieldTimer = null;
let boss = null;
let bossSpawnScore = 500;
let playerEmoji = '🚀';

// Game objects
let player = {
x: canvas.width / 2,
y: canvas.height - 50,
width: 50,
height: 50,
emoji: '🚀'
};
let bullets = [];
let enemies = [];
let powerups = [];
let particles = [];
let stars = [];
let bossBullets = [];

// Game timers and rates


let enemySpawnInterval = 1000;
let lastEnemySpawnTime = 0;
let powerupSpawnInterval = 15000;
let lastPowerupSpawnTime = 0;
let bossFireInterval = 1500;
let bossLastFireTime = 0;

// Enemy configurations with emojis based on difficulty


const difficultySettings = {
easy: { spawnRate: 1000, speed: 2 },
medium: { spawnRate: 700, speed: 3.5 },
hard: { spawnRate: 400, speed: 5 }
};

const enemyTypes = {
basic: { emoji: '👽', size: 30, speed: 2, points: 66 },
fast: { emoji: '👾', size: 20, speed: 4, points: 66 },
big: { emoji: '🛸', size: 50, speed: 2, points: 66 }
};

const bossConfig = {
emoji: '👹', size: 100, health: 50, speed: 1.5, points: 1000,
bulletSpeed: 4
};

// Power-up configurations with emojis


const powerupTypes = {
rapidFire: { emoji: '⚡', size: 20, type: 'rapidFire', duration: 5000 },
extraLife: { emoji: '❤️', size: 20, type: 'extraLife' },
shield: { emoji: '', size: 20, type: 'shield', duration: 8000 },
bomb: { emoji: '💣', size: 20, type: 'bomb' },
scoreMultiplier: { emoji: '⭐', size: 20, type: 'scoreMultiplier',
duration: 10000 }
};

// Particle colors for explosions


const explosionColors = ['#FF6347', '#FFD700', '#ADD8E6', '#98FB98'];

/**
* Initializes audio for the game.
* (Game ke liye audio shuru karta hai.)
*/
function initAudio() {
if (Tone.context.state !== 'running') {
Tone.start();
}
if (!shootSynth) {
shootSynth = new Tone.MetalSynth({ frequency: 150, envelope:
{ attack: 0.001, decay: 0.2, release: 0.1 } }).toDestination();
hitSynth = new Tone.MetalSynth({ frequency: 200, envelope:
{ attack: 0.001, decay: 0.2, release: 0.1 } }).toDestination();
powerUpSynth = new Tone.Synth({ oscillator: { type: 'sine' },
envelope: { attack: 0.01, decay: 0.1, sustain: 0.1, release:
0.3 } }).toDestination();
bombSynth = new Tone.NoiseSynth({ volume: -10, envelope: { attack:
0.001, decay: 0.2, release: 0.1 } }).toDestination();
bossHitSynth = new Tone.Synth({ oscillator: { type: 'square' },
envelope: { attack: 0.01, decay: 0.1, sustain: 0.1, release: 0.2 }, volume: -
15 }).toDestination();

backgroundMusic = new Tone.Oscillator('C3',


'sawtooth').toDestination().start();
backgroundMusic.volume.value = -20;
}
}

/**
* Initializes or resets the game state.
* (Game ko shuru ya reset karta hai.)
*/
function initGame() {
resizeCanvas();
gameStarted = true;
gameOver = false;
isPaused = false;
score = 0;
lives = 3;
bullets = [];
enemies = [];
powerups = [];
particles = [];
boss = null;
bossBullets = [];
bossHealthBarContainer.style.display = 'none';

// Clear all timers


if (rapidFireTimer) clearInterval(rapidFireTimer);
if (scoreMultiplierTimer) clearTimeout(scoreMultiplierTimer);
if (shieldTimer) clearTimeout(shieldTimer);
rapidFireActive = false;
scoreMultiplierActive = false;
shieldActive = false;

lastEnemySpawnTime = 0;
lastPowerupSpawnTime = 0;
bossLastFireTime = 0;

player.x = canvas.width / 2;
player.emoji = playerEmoji;

mainMenu.style.display = 'none';
messageBox.style.display = 'none';
pauseMenu.style.display = 'none';
uiContainer.style.display = 'flex';

// Set enemy spawn rate based on difficulty


enemySpawnInterval = difficultySettings[currentDifficulty].spawnRate;
enemyTypes.basic.speed = difficultySettings[currentDifficulty].speed;
enemyTypes.fast.speed = difficultySettings[currentDifficulty].speed *
1.5;

if (animationFrameId) cancelAnimationFrame(animationFrameId);
if (bgAnimationFrameId) cancelAnimationFrame(bgAnimationFrameId);

updateUI();
animate();
animateBackground();
}

/**
* Updates the UI displays.
* (UI display ko update karta hai.)
*/
function updateUI() {
scoreDisplay.textContent = `Score: ${score}`;
livesDisplay.textContent = `Lives: ${lives}`;
highScoreDisplay.textContent = `High Score: ${highScore}`;
document.getElementById('high-score-menu-display').textContent = `High
Score: ${highScore}`;

// Update boss health bar


if (boss) {
bossHealthBar.style.width = `${(boss.health / boss.maxHealth) *
100}%`;
}
}

/**
* Saves the high score to local storage.
* (High score ko local storage mein save karta hai.)
*/
function saveHighScore() {
if (score > highScore) {
highScore = score;
localStorage.setItem('seamShooterHighScore', highScore);
}
}

/**
* Spawns a new enemy at a random position.
* (Random position par ek naya dushman paida karta hai.)
*/
function spawnEnemy() {
const types = Object.keys(enemyTypes);
const randomType = types[Math.floor(Math.random() * types.length)];
const config = enemyTypes[randomType];

enemies.push({
x: Math.random() * (canvas.width - config.size),
y: -config.size,
size: config.size,
speed: config.speed,
emoji: config.emoji,
points: config.points
});
}
/**
* Spawns a new power-up at a random position.
* (Random position par ek naya power-up paida karta hai.)
*/
function spawnPowerup() {
const types = Object.keys(powerupTypes);
const randomType = types[Math.floor(Math.random() * types.length)];
const config = powerupTypes[randomType];

powerups.push({
x: Math.random() * (canvas.width - config.size),
y: -config.size,
size: config.size,
speed: 1.5,
emoji: config.emoji,
type: config.type,
duration: config.duration
});
}

/**
* Spawns the boss enemy.
* (Boss dushman ko paida karta hai.)
*/
function spawnBoss() {
boss = {
x: canvas.width / 2 - bossConfig.size / 2,
y: -bossConfig.size,
size: bossConfig.size,
health: bossConfig.health,
maxHealth: bossConfig.health,
emoji: bossConfig.emoji,
speed: bossConfig.speed,
points: bossConfig.points,
bulletSpeed: bossConfig.bulletSpeed
};
bossHealthBarContainer.style.display = 'block';
}

/**
* Handles bullet firing for the player.
* (Player ke liye goli chalane ka kaam karta hai.)
*/
function fireBullet() {
bullets.push({
x: player.x + player.width / 2,
y: player.y,
width: 5,
height: 15,
speed: -7,
color: '#fff'
});
if (shootSynth) {
shootSynth.triggerAttackRelease("C4", "32n");
}
}

/**
* Handles bullet firing for the boss.
* (Boss ke liye goli chalane ka kaam karta hai.)
*/
function bossFireBullet() {
if (boss) {
bossBullets.push({
x: boss.x + boss.size / 2 - 2,
y: boss.y + boss.size,
width: 4,
height: 12,
speed: boss.bulletSpeed,
color: '#FF6347'
});
}
}

/**
* Toggles the game's pause state.
* (Game ko pause ya resume karta hai.)
*/
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
cancelAnimationFrame(animationFrameId);
cancelAnimationFrame(bgAnimationFrameId);
pauseMenu.style.display = 'block';
uiContainer.style.display = 'none';
if (backgroundMusic) backgroundMusic.volume.value = -40; // Mute
music
} else {
pauseMenu.style.display = 'none';
uiContainer.style.display = 'flex';
animate();
animateBackground();
if (backgroundMusic) backgroundMusic.volume.value = -20; // Unmute
music
}
}

/**
* The main game loop.
* (Game ka mukhya loop.)
*/
function animate(timestamp) {
if (gameOver || isPaused || !gameStarted) return;

ctx.clearRect(0, 0, canvas.width, canvas.height);

// Spawning logic
if (!boss) {
if (score >= bossSpawnScore) {
spawnBoss();
} else if (timestamp - lastEnemySpawnTime > enemySpawnInterval) {
spawnEnemy();
lastEnemySpawnTime = timestamp;
}
}

if (timestamp - lastPowerupSpawnTime > powerupSpawnInterval) {


spawnPowerup();
lastPowerupSpawnTime = timestamp;
}

// Boss ka goli chalane ka logic


if (boss && timestamp - bossLastFireTime > bossFireInterval) {
bossFireBullet();
bossLastFireTime = timestamp;
}

// Update positions
bullets.forEach(b => b.y += b.speed);
enemies.forEach(e => e.y += e.speed);
powerups.forEach(p => p.y += p.speed);
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
p.alpha -= 0.01;
});
bossBullets.forEach(b => b.y += b.speed);

// Boss logic
if (boss) {
boss.y += boss.speed;
if (boss.y > 100) boss.y = 100;
}

// Draw objects with improved graphics


drawPlayer();
drawBullets();
drawEnemies();
drawPowerups();
drawParticles();
drawBossBullets();
if (boss) {
drawBoss();
}

// Collision detection
checkCollisions();

// Cleanup off-screen objects and old particles


bullets = bullets.filter(b => b.y > -b.height);
enemies = enemies.filter(e => e.y < canvas.height);
powerups = powerups.filter(p => p.y < canvas.height);
particles = particles.filter(p => p.alpha > 0);
bossBullets = bossBullets.filter(b => b.y < canvas.height);

if (lives <= 0) {
endGame();
}

animationFrameId = requestAnimationFrame(animate);
}

/**
* Creates and draws the starry background.
* (Taaron bhara background banata aur draw karta hai.)
*/
function animateBackground() {
bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);

// Create stars on first run


if (stars.length === 0) {
for(let i = 0; i < 500; i++) {
stars.push({
x: Math.random() * bgCanvas.width,
y: Math.random() * bgCanvas.height,
radius: Math.random() * 1.5,
speed: Math.random() * 0.5 + 0.1
});
}
}

// Draw and update stars with a parallax effect


bgCtx.fillStyle = '#fff';
stars.forEach(s => {
bgCtx.beginPath();
bgCtx.arc(s.x, s.y, s.radius, 0, Math.PI * 2);
bgCtx.fill();
s.y += s.speed;
if (s.y > bgCanvas.height) {
s.y = 0;
s.x = Math.random() * bgCanvas.width;
}
});

bgAnimationFrameId = requestAnimationFrame(animateBackground);
}

/**
* Draws the player with a gradient and glow.
* (Player ko gradient aur chamak ke saath draw karta hai.)
*/
function drawPlayer() {
// Player ki chamak set karna
ctx.shadowBlur = shieldActive ? 20 : 10;
ctx.shadowColor = shieldActive ? 'rgba(100, 200, 255, 1)' : 'rgba(255,
255, 255, 1)';

// Player ship ka shape


ctx.beginPath();
ctx.moveTo(player.x + player.width / 2, player.y);
ctx.lineTo(player.x + player.width, player.y + player.height);
ctx.lineTo(player.x, player.y + player.height);
ctx.closePath();

const playerGradient = ctx.createLinearGradient(player.x, player.y,


player.x, player.y + player.height);
playerGradient.addColorStop(0, '#6495ED'); // Light blue
playerGradient.addColorStop(1, '#191970'); // Dark blue
ctx.fillStyle = playerGradient;
ctx.fill();

// Player emoji ko ship ke upar draw karna


ctx.shadowBlur = 0; // Chamak hatana taaki emoji chamakdar na ho.
ctx.font = `${player.width * 0.7}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(player.emoji, player.x + player.width / 2, player.y +
player.height / 2);

// Shield ko draw karna, agar active ho


if (shieldActive) {
ctx.beginPath();
ctx.arc(player.x + player.width / 2, player.y + player.height / 2,
player.width, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(100, 200, 255, 0.7)';
ctx.lineWidth = 5;
ctx.stroke();
}
}

/**
* Draws the boss with a gradient and glow.
* (Boss ko gradient aur chamak ke saath draw karta hai.)
*/
function drawBoss() {
if (!boss) return;

ctx.shadowBlur = 20;
ctx.shadowColor = '#e74c3c';

// Boss ship ka shape


ctx.beginPath();
ctx.arc(boss.x + boss.size / 2, boss.y + boss.size / 2, boss.size / 2,
0, Math.PI * 2);
const bossGradient = ctx.createRadialGradient(
boss.x + boss.size / 2, boss.y + boss.size / 2, 0,
boss.x + boss.size / 2, boss.y + boss.size / 2, boss.size / 2
);
bossGradient.addColorStop(0, '#8B0000'); // Dark red
bossGradient.addColorStop(1, '#DC143C'); // Crimson
ctx.fillStyle = bossGradient;
ctx.fill();

ctx.shadowBlur = 0;
ctx.font = `${boss.size * 0.7}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(boss.emoji, boss.x + boss.size / 2, boss.y + boss.size /
2);
}

/**
* Draws enemies with a glowing outline.
* (Dushmano ko chamakdar outline ke saath draw karta hai.)
*/
function drawEnemies() {
enemies.forEach(e => {
ctx.shadowBlur = 10;
ctx.shadowColor = 'rgba(255, 0, 0, 0.8)';
ctx.font = `${e.size}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(e.emoji, e.x + e.size / 2, e.y + e.size / 2);
ctx.shadowBlur = 0;
});
}

/**
* Draws player bullets as glowing lasers.
* (Player ki goliyon ko chamakdar lasers ke roop mein draw karta hai.)
*/
function drawBullets() {
bullets.forEach(b => {
ctx.shadowBlur = 15;
ctx.shadowColor = '#fff';
ctx.fillStyle = '#fff';
ctx.fillRect(b.x, b.y, b.width, b.height);
ctx.shadowBlur = 0;
});
}

/**
* Draws boss bullets as glowing red lasers.
* (Boss ki goliyon ko chamakdar laal lasers ke roop mein draw karta hai.)
*/
function drawBossBullets() {
bossBullets.forEach(b => {
ctx.shadowBlur = 15;
ctx.shadowColor = '#FF6347';
ctx.fillStyle = b.color;
ctx.fillRect(b.x, b.y, b.width, b.height);
ctx.shadowBlur = 0;
});
}

/**
* Draws power-ups with a glowing effect.
* (Power-ups ko chamakdar prabhav ke saath draw karta hai.)
*/
function drawPowerups() {
powerups.forEach(p => {
ctx.shadowBlur = 10;
ctx.shadowColor = '#00FF00';
ctx.font = `${p.size}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(p.emoji, p.x + p.size / 2, p.y + p.size / 2);
ctx.shadowBlur = 0;
});
}

/**
* Draws all active particles.
* (Sabhi active particles ko draw karta hai.)
*/
function drawParticles() {
particles.forEach(p => {
ctx.fillStyle = `rgba(${p.color.r}, ${p.color.g}, ${p.color.b}, $
{p.alpha})`;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fill();
});
}

/**
* Creates a particle explosion with a flash.
* (Ek flash ke saath particle explosion banata hai.)
*/
function createExplosion(x, y) {
// Explosion flash
ctx.save();
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
ctx.restore();

// Particles
for (let i = 0; i < 20; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 5 + 1;
const color = explosionColors[Math.floor(Math.random() *
explosionColors.length)];
particles.push({
x: x,
y: y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
size: Math.random() * 3 + 1,
alpha: 1,
color: {
r: parseInt(color.slice(1, 3), 16),
g: parseInt(color.slice(3, 5), 16),
b: parseInt(color.slice(5, 7), 16)
}
});
}
}

/**
* Checks for all game collisions.
* (Game ke sabhi takkaron ki jaanch karta hai.)
*/
function checkCollisions() {
// Bullet-enemy collisions
for (let i = bullets.length - 1; i >= 0; i--) {
for (let j = enemies.length - 1; j >= 0; j--) {
if (isColliding(bullets[i], enemies[j])) {
createExplosion(enemies[j].x + enemies[j].size / 2,
enemies[j].y + enemies[j].size / 2);
score += enemies[j].points * (scoreMultiplierActive ? 2 :
1);
if (hitSynth) hitSynth.triggerAttackRelease("A4", "8n");

bullets.splice(i, 1);
enemies.splice(j, 1);

updateUI();
break; // Exit inner loop since bullet is gone
}
}
}

// Bullet-boss collision
if (boss) {
for (let i = bullets.length - 1; i >= 0; i--) {
if (isColliding(bullets[i], boss)) {
bullets.splice(i, 1);
boss.health -= 1;
if (bossHitSynth) bossHitSynth.triggerAttackRelease("G4",
"16n");
updateUI();
if (boss.health <= 0) {
createExplosion(boss.x + boss.size / 2, boss.y +
boss.size / 2);
score += boss.points;
boss = null;
bossHealthBarContainer.style.display = 'none';
updateUI();
}
break; // Exit loop after hitting the boss
}
}
}

// Player-enemy collisions
for (let i = enemies.length - 1; i >= 0; i--) {
if (isColliding(player, enemies[i])) {
if (shieldActive) {
shieldActive = false;
if (shieldTimer) clearTimeout(shieldTimer);
} else {
lives--;
}
createExplosion(enemies[i].x + enemies[i].size / 2,
enemies[i].y + enemies[i].size / 2);
enemies.splice(i, 1);
updateUI();
}
}

// Player-boss collision
if (boss && isColliding(player, boss)) {
if (shieldActive) {
shieldActive = false;
if (shieldTimer) clearTimeout(shieldTimer);
} else {
lives--;
}
createExplosion(boss.x + boss.size / 2, boss.y + boss.size / 2);
boss = null;
bossHealthBarContainer.style.display = 'none';
updateUI();
}

// Player-boss bullet collisions


for (let i = bossBullets.length - 1; i >= 0; i--) {
if (isColliding(player, bossBullets[i])) {
if (shieldActive) {
shieldActive = false;
if (shieldTimer) clearTimeout(shieldTimer);
} else {
lives--;
}
createExplosion(bossBullets[i].x, bossBullets[i].y);
bossBullets.splice(i, 1);
updateUI();
}
}

// Player-powerup collisions
for (let i = powerups.length - 1; i >= 0; i--) {
if (isColliding(player, powerups[i])) {
const powerup = powerups[i];
powerups.splice(i, 1);
if (powerUpSynth) powerUpSynth.triggerAttackRelease("C6",
"8n");

if (powerup.type === 'rapidFire') {


activateRapidFire();
} else if (powerup.type === 'extraLife') {
lives++;
updateUI();
} else if (powerup.type === 'shield') {
activateShield();
} else if (powerup.type === 'bomb') {
activateBomb();
} else if (powerup.type === 'scoreMultiplier') {
activateScoreMultiplier();
}
}
}
}

/**
* Simple AABB collision detection.
* (AABB collision detection.)
*/
function isColliding(rect1, rect2) {
const rect1Width = rect1.width || rect1.size;
const rect1Height = rect1.height || rect1.size;
const rect2Width = rect2.width || rect2.size;
const rect2Height = rect2.height || rect2.size;
return rect1.x < rect2.x + rect2Width &&
rect1.x + rect1Width > rect2.x &&
rect1.y < rect2.y + rect2Height &&
rect1.y + rect1Height > rect2.y;
}

/**
* Activates rapid fire mode.
* (Rapid fire mode shuru karta hai.)
*/
function activateRapidFire() {
if (rapidFireActive) return;
rapidFireActive = true;
if (rapidFireTimer) clearInterval(rapidFireTimer);
rapidFireTimer = setInterval(fireBullet, 100);
setTimeout(() => {
rapidFireActive = false;
clearInterval(rapidFireTimer);
}, 5000);
}

/**
* Activates shield mode.
* (Shield mode shuru karta hai.)
*/
function activateShield() {
shieldActive = true;
if (shieldTimer) clearTimeout(shieldTimer);
shieldTimer = setTimeout(() => {
shieldActive = false;
}, 8000);
}

/**
* Activates bomb effect.
* (Bomb effect shuru karta hai.)
*/
function activateBomb() {
enemies.forEach(e => {
createExplosion(e.x + e.size / 2, e.y + e.size / 2);
score += e.points * (scoreMultiplierActive ? 2 : 1);
});
if (bombSynth) bombSynth.triggerAttackRelease("4n");
enemies = [];
updateUI();
}

/**
* Activates score multiplier.
* (Score multiplier shuru karta hai.)
*/
function activateScoreMultiplier() {
scoreMultiplierActive = true;
if (scoreMultiplierTimer) clearTimeout(scoreMultiplierTimer);
scoreMultiplierTimer = setTimeout(() => {
scoreMultiplierActive = false;
}, 10000);
}

/**
* Ends the game and shows the game over message.
* (Game ko khatam karta hai aur game over message dikhata hai.)
*/
function endGame() {
gameOver = true;
gameStarted = false;
saveHighScore();
cancelAnimationFrame(animationFrameId);
cancelAnimationFrame(bgAnimationFrameId);

uiContainer.style.display = 'none';
bossHealthBarContainer.style.display = 'none';
document.getElementById('game-message').textContent = "Game Over!";
document.getElementById('final-stats').textContent = `Your final score
was ${score}.`;
messageBox.style.display = 'block';
if (backgroundMusic) backgroundMusic.stop();
}

/**
* Resizes the canvas to be responsive.
* (Canvas ko responsive banane ke liye resize karta hai.)
*/
function resizeCanvas() {
canvas.width = window.innerWidth * 0.8;
canvas.height = window.innerHeight * 0.8;
bgCanvas.width = window.innerWidth;
bgCanvas.height = window.innerHeight;
player.x = canvas.width / 2 - player.width / 2;
player.y = canvas.height - player.height - 20;
}

// Event listeners
startButton.addEventListener('click', () => { initAudio(); initGame(); });
restartButton.addEventListener('click', () => { initAudio();
initGame(); });
resumeButton.addEventListener('click', togglePause);
mainMenuButton.addEventListener('click', () => {
pauseMenu.style.display = 'none';
mainMenu.style.display = 'block';
if (backgroundMusic) backgroundMusic.stop();
});

difficultyButtons.forEach(btn => {
btn.addEventListener('click', () => {
currentDifficulty = btn.dataset.difficulty;
difficultyButtons.forEach(b => b.style.backgroundColor =
'#3498db');
btn.style.backgroundColor = '#2ecc71';
});
});

playerButtons.forEach(btn => {
btn.addEventListener('click', () => {
playerEmoji = btn.dataset.emoji;
playerButtons.forEach(b => b.style.backgroundColor = '#3498db');
btn.style.backgroundColor = '#2ecc71';
});
});

window.addEventListener('resize', resizeCanvas);

window.addEventListener('mousemove', (e) => {


if (!gameStarted || gameOver || isPaused) return;
player.x = e.clientX - canvas.offsetLeft - player.width / 2;
if (player.x < 0) player.x = 0;
if (player.x + player.width > canvas.width) player.x = canvas.width -
player.width;
});

window.addEventListener('mousedown', (e) => {


if (!gameStarted || gameOver || isPaused || rapidFireActive) return;
fireBullet();
});

window.addEventListener('keydown', (e) => {


if (e.key === 'p' || e.key === 'P') {
togglePause();
}
});

window.addEventListener('touchstart', (e) => {


e.preventDefault();
if (!gameStarted || gameOver || isPaused) return;
if (!rapidFireActive) fireBullet();

const touchX = e.touches[0].clientX - canvas.offsetLeft;


player.x = touchX - player.width / 2;
if (player.x < 0) player.x = 0;
if (player.x + player.width > canvas.width) player.x = canvas.width -
player.width;
});

window.addEventListener('touchmove', (e) => {


e.preventDefault();
if (!gameStarted || gameOver || isPaused) return;
const touchX = e.touches[0].clientX - canvas.offsetLeft;
player.x = touchX - player.width / 2;
if (player.x < 0) player.x = 0;
if (player.x + player.width > canvas.width) player.x = canvas.width -
player.width;
});

// Initial setup
window.onload = () => {
resizeCanvas();
animateBackground();
updateUI(); // Load high score and display
};
</script>
</body>
</html>

You might also like