-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndex.html
More file actions
768 lines (670 loc) · 25.6 KB
/
Copy pathIndex.html
File metadata and controls
768 lines (670 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ghost Dodger Game</title>
<link rel="manifest" href="manifest.json" />
<meta name="theme-color" content="#111111" />
<style>
* { box-sizing: border-box; }
body {
margin: 0;
font-family: 'Segoe UI', sans-serif;
background: linear-gradient(to bottom, #111, #333);
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
}
#startScreen, #gameOverScreen, #shopScreen {
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
animation: fadeIn 1s ease;
position: absolute;
background: rgba(0,0,0,0.85);
padding: 30px;
border-radius: 15px;
border: 2px solid #555;
z-index: 10;
}
#startScreen.active, #gameOverScreen.active, #shopScreen.active {
display: flex;
}
button {
padding: 12px 24px;
font-size: 1rem;
border: none;
border-radius: 10px;
cursor: pointer;
background: #ff4081;
color: white;
font-weight: bold;
transition: transform 0.2s;
margin: 5px;
}
button:hover {
transform: scale(1.05);
}
#gameCanvas {
background: black;
border: 2px solid white;
display: none;
}
#pauseOverlay {
position: absolute;
background: rgba(0, 0, 0, 0.7);
color: white;
font-size: 2rem;
display: none;
align-items: center;
justify-content: center;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 2;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.shop-item {
display: flex;
flex-direction: column;
align-items: center;
background: #333;
padding: 10px;
border-radius: 10px;
width: 80px;
}
.shop-item.locked { opacity: 0.6; }
.shop-item button { padding: 5px; font-size: 0.8rem; }
.shop-item span { font-size: 2rem; }
#toast {
visibility: hidden;
min-width: 200px;
margin-left: -100px;
background-color: #333;
border: 1px solid #555;
color: #fff;
text-align: center;
border-radius: 8px;
padding: 12px;
position: fixed;
z-index: 15;
left: 50%;
bottom: 30px;
font-size: 14px;
opacity: 0;
transition: opacity 0.5s, visibility 0.5s;
}
#toast.show {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body>
<div id="startScreen" class="active">
<h1>👻 Ghost Dodger</h1>
<p id="totalCoinsDisplay" style="color: gold; font-weight: bold;">Total Coins: 0 🪙</p>
<p>Select Skin:</p>
<div id="skinSelector" style="display:flex; flex-wrap:wrap; justify-content:center; max-width:300px;">
<!-- Generated by JS -->
</div>
<button onclick="openShop()" style="background: #f1c40f; color: black;">🛒 Open Shop</button>
<p>Select Difficulty</p>
<div>
<button onclick="startGame('easy')">Easy 😌</button>
<button onclick="startGame('medium')">Medium 😬</button>
<button onclick="startGame('hard')">Hard 😈</button>
</div>
</div>
<div id="shopScreen">
<h2>In-Game Shop 🛒</h2>
<p id="shopCoinsDisplay" style="color: gold; font-weight: bold;"></p>
<div id="shopItems" style="display:flex; flex-wrap:wrap; gap:10px; justify-content:center; max-width: 350px;">
<!-- Items generated dynamically -->
</div>
<button onclick="closeShop()" style="margin-top: 20px;">Back to Menu</button>
</div>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<div id="pauseOverlay">⏸️ Paused</div>
<div id="gameOverScreen">
<h2>Game Over! 💀</h2>
<p id="scoreDisplay"></p>
<p id="highScoreDisplay"></p>
<p id="sessionCoinsDisplay" style="color: gold;"></p>
<div style="display: flex; gap: 10px;">
<button onclick="restartGame()">Restart</button>
<button onclick="shareScore()">Share Score 🔗</button>
</div>
</div>
<div id="toast">Score copied to clipboard!</div>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const startScreen = document.getElementById("startScreen");
const gameOverScreen = document.getElementById("gameOverScreen");
const shopScreen = document.getElementById("shopScreen");
const pauseOverlay = document.getElementById("pauseOverlay");
const scoreDisplay = document.getElementById("scoreDisplay");
const highScoreDisplay = document.getElementById("highScoreDisplay");
const totalCoinsDisplay = document.getElementById("totalCoinsDisplay");
const sessionCoinsDisplay = document.getElementById("sessionCoinsDisplay");
const shopCoinsDisplay = document.getElementById("shopCoinsDisplay");
const skinSelector = document.getElementById("skinSelector");
const shopItems = document.getElementById("shopItems");
// Audio Context Synthesizer
let audioCtx = null;
function initAudio() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state === 'suspended') audioCtx.resume();
}
function playSound(type) {
if (!audioCtx) return;
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
if (type === 'coin') {
osc.type = 'sine';
osc.frequency.setValueAtTime(800, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(1200, audioCtx.currentTime + 0.1);
gainNode.gain.setValueAtTime(0.2, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
osc.start();
osc.stop(audioCtx.currentTime + 0.1);
} else if (type === 'powerup') {
osc.type = 'square';
osc.frequency.setValueAtTime(400, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(800, audioCtx.currentTime + 0.2);
gainNode.gain.setValueAtTime(0.2, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.2);
osc.start();
osc.stop(audioCtx.currentTime + 0.2);
} else if (type === 'hit') {
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(150, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(50, audioCtx.currentTime + 0.2);
gainNode.gain.setValueAtTime(0.3, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.2);
osc.start();
osc.stop(audioCtx.currentTime + 0.2);
} else if (type === 'boss_hit') {
osc.type = 'triangle';
osc.frequency.setValueAtTime(200, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(100, audioCtx.currentTime + 0.1);
gainNode.gain.setValueAtTime(0.3, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
osc.start();
osc.stop(audioCtx.currentTime + 0.1);
} else if (type === 'boss_dead') {
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(300, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(50, audioCtx.currentTime + 0.5);
gainNode.gain.setValueAtTime(0.5, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
osc.start();
osc.stop(audioCtx.currentTime + 0.5);
}
}
// Shop & Skins Logic
const allSkins = [
{ emoji: '🧙♂️', price: 0 },
{ emoji: '🧛♂️', price: 0 },
{ emoji: '🧟♂️', price: 0 },
{ emoji: '👽', price: 50 },
{ emoji: '🤖', price: 50 },
{ emoji: '🐱', price: 100 },
{ emoji: '🦸♂️', price: 150 },
{ emoji: '🦄', price: 200 }
];
let unlockedSkins = JSON.parse(localStorage.getItem('ghostDodgerSkins')) || ['🧙♂️', '🧛♂️', '🧟♂️'];
let totalCoins = parseInt(localStorage.getItem('ghostDodgerTotalCoins')) || 0;
function updateCoinDisplays() {
totalCoinsDisplay.textContent = `Total Coins: ${totalCoins} 🪙`;
shopCoinsDisplay.textContent = `Total Coins: ${totalCoins} 🪙`;
}
updateCoinDisplays();
function renderSkinSelectors() {
skinSelector.innerHTML = '';
allSkins.forEach(s => {
if (unlockedSkins.includes(s.emoji)) {
const btn = document.createElement('button');
btn.textContent = s.emoji;
btn.onclick = () => setPlayerEmoji(s.emoji);
if(player.emoji === s.emoji) btn.style.border = '2px solid gold';
skinSelector.appendChild(btn);
}
});
}
function renderShop() {
shopItems.innerHTML = '';
allSkins.forEach(s => {
const item = document.createElement('div');
item.className = 'shop-item ' + (unlockedSkins.includes(s.emoji) ? '' : 'locked');
item.innerHTML = `<span>${s.emoji}</span>`;
const btn = document.createElement('button');
if (unlockedSkins.includes(s.emoji)) {
btn.textContent = 'Owned';
btn.disabled = true;
btn.style.background = 'gray';
} else {
btn.textContent = `${s.price} 🪙`;
btn.onclick = () => buySkin(s.emoji, s.price);
}
item.appendChild(btn);
shopItems.appendChild(item);
});
}
function buySkin(emoji, price) {
if (totalCoins >= price) {
totalCoins -= price;
unlockedSkins.push(emoji);
localStorage.setItem('ghostDodgerTotalCoins', totalCoins);
localStorage.setItem('ghostDodgerSkins', JSON.stringify(unlockedSkins));
updateCoinDisplays();
renderShop();
renderSkinSelectors();
} else {
showToast("Not enough coins! 🪙");
}
}
function openShop() {
startScreen.classList.remove('active');
shopScreen.classList.add('active');
renderShop();
}
function closeShop() {
shopScreen.classList.remove('active');
startScreen.classList.add('active');
}
// Game Variables
let player = { x: 180, y: 550, width: 40, height: 40, emoji: '🧙♂️', shield: false, magnet: false, freeze: false, shrink: false, projectiles: [] };
let ghosts = [];
let powerups = [];
let coins = [];
let boss = null;
let keys = {};
let gameLoop, spawnLoop, timerLoop, powerupLoop, coinLoop;
let speed = 2;
let difficulty = 'easy';
let survivalTime = 0;
let paused = false;
let level = 1;
let sessionCoins = 0;
let comboCount = 0;
let comboTimer = 0;
let levelTimeLeft = 60; // Shorter levels to see boss faster
let isTransitioning = false;
// Dynamic Themes setup
let particles = [];
const themes = [
{ top: "#87ceeb", bottom: "#e0f6ff", type: 'sky' },
{ top: "#2c3e50", bottom: "#34495e", type: 'rain' },
{ top: "#0b0b2a", bottom: "#000000", type: 'space' }, // Boss
{ top: "#4a0e0e", bottom: "#ff4500", type: 'ember' },
{ top: "#1a2a1a", bottom: "#000000", type: 'fog' }
];
function drawEmoji(x, y, emoji, size = 32) {
ctx.font = `${size}px Arial`;
ctx.fillText(emoji, x, y);
}
function drawPlayer() {
let size = player.shrink ? 20 : 32;
let pWidth = player.shrink ? 20 : 40;
let offset = player.shrink ? 10 : 0;
if (player.shield) {
ctx.beginPath();
ctx.arc(player.x + pWidth/2 + offset, player.y - 10 + offset, player.shrink ? 15 : 25, 0, Math.PI * 2);
ctx.fillStyle = "rgba(0, 200, 255, 0.4)";
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "rgba(0, 200, 255, 0.8)";
ctx.stroke();
ctx.closePath();
}
if (player.magnet) {
ctx.beginPath();
ctx.arc(player.x + pWidth/2 + offset, player.y - 10 + offset, player.shrink ? 20 : 35, 0, Math.PI * 2);
ctx.strokeStyle = "rgba(255, 215, 0, 0.3)";
ctx.stroke();
ctx.closePath();
}
drawEmoji(player.x + offset, player.y + offset, player.emoji, size);
// Draw player projectiles (when fighting boss)
ctx.fillStyle = "yellow";
player.projectiles.forEach(p => {
ctx.beginPath();
ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
ctx.fill();
});
}
function drawBackground() {
let theme = themes[(level - 1) % themes.length];
if (boss) theme = themes[2]; // space theme for boss
let grad = ctx.createLinearGradient(0, 0, 0, canvas.height);
grad.addColorStop(0, theme.top);
grad.addColorStop(1, theme.bottom);
ctx.fillStyle = grad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(255, 255, 255, 0.4)";
if (theme.type === 'rain') {
if (Math.random() < 0.3) particles.push({x: Math.random()*canvas.width, y: -10, speedY: 10 + Math.random()*5, speedX: -1 + Math.random()*2});
particles.forEach((p, i) => { p.x += p.speedX; p.y += p.speedY; ctx.fillRect(p.x, p.y, 2, 10); if (p.y > canvas.height) particles.splice(i, 1); });
} else if (theme.type === 'space') {
if(particles.length < 50) particles.push({x: Math.random()*canvas.width, y: Math.random()*canvas.height, radius: Math.random()*1.5});
ctx.fillStyle = "white";
particles.forEach(p => { ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, Math.PI*2); ctx.fill(); });
} else if (theme.type === 'ember') {
if (Math.random() < 0.2) particles.push({x: Math.random()*canvas.width, y: canvas.height+10, speedY: -2 - Math.random()*3, speedX: -2 + Math.random()*4});
ctx.fillStyle = "rgba(255, 69, 0, 0.7)";
particles.forEach((p, i) => { p.x += p.speedX; p.y += p.speedY; ctx.fillRect(p.x, p.y, 3, 3); if (p.y < 0) particles.splice(i, 1); });
}
}
function drawHUD() {
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText(`Lvl: ${level}`, 10, 30);
if(!boss) ctx.fillText(`${levelTimeLeft}s`, 10, 60);
else {
ctx.fillStyle = "red";
ctx.fillText(`BOSS HP`, 10, 60);
}
ctx.fillStyle = "gold";
ctx.fillText(`Coins: ${sessionCoins} 🪙`, canvas.width - 130, 30);
if (comboCount > 1) {
ctx.fillStyle = "orange";
ctx.font = "bold 24px Arial";
ctx.fillText(`Combo x${Math.min(comboCount, 5)}!`, canvas.width/2 - 60, 50);
}
if (isTransitioning) {
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.font = "bold 40px Arial";
let text = boss ? "BOSS STAGE" : `LEVEL ${level}`;
ctx.fillText(text, canvas.width/2 - (boss? 120 : 80), canvas.height/2);
}
}
function updateEntities() {
if (!player.freeze) {
ghosts.forEach(g => {
g.y += g.speed;
if (g.type === 'zigzag') g.x += Math.sin(g.y / 20) * 2;
else if (g.type === 'chaser') {
if (g.x < player.x) g.x += 1.5;
if (g.x > player.x) g.x -= 1.5;
}
});
}
ghosts = ghosts.filter(g => g.y < canvas.height);
coins.forEach(c => {
if (player.magnet) {
const dx = player.x - c.x;
const dy = player.y - c.y;
const dist = Math.sqrt(dx*dx + dy*dy);
if (dist < 150) {
c.x -= (dx/dist) * 5; // Should be minus since we want to move towards player
c.y -= (dy/dist) * 5;
} else {
c.y += 3;
}
} else {
c.y += 3;
}
});
coins = coins.filter(c => c.y < canvas.height);
powerups.forEach(p => p.y += 2);
powerups = powerups.filter(p => p.y < canvas.height);
if (boss) {
boss.x += boss.moveDir;
if (boss.x <= 0 || boss.x + boss.width >= canvas.width) boss.moveDir *= -1;
if (Math.random() < 0.05 && !player.freeze) {
boss.projectiles.push({ x: boss.x + 40, y: boss.y + 80, speed: 4 });
}
boss.projectiles.forEach(p => p.y += p.speed);
boss.projectiles = boss.projectiles.filter(p => p.y < canvas.height);
if (Math.random() < 0.2) {
player.projectiles.push({x: player.x + (player.shrink?10:20), y: player.y - 20, speed: -7});
}
player.projectiles.forEach(p => {
p.y += p.speed;
if (p.y < boss.y + 60 && p.x > boss.x && p.x < boss.x + boss.width) {
boss.hp--;
p.hit = true;
playSound('boss_hit');
}
});
player.projectiles = player.projectiles.filter(p => p.y > 0 && !p.hit);
if (boss.hp <= 0) {
playSound('boss_dead');
boss = null;
player.projectiles = [];
for(let i=0; i<10; i++) spawnCoin();
triggerLevelTransition();
}
}
if (comboTimer > 0) {
comboTimer--;
if (comboTimer <= 0) comboCount = 0;
}
}
function spawnGhost() {
if (isTransitioning || boss) return; // Don't spawn ghosts during boss
const x = Math.random() * (canvas.width - 30);
let type = 'normal';
let emoji = '👾';
if (level >= 2 && Math.random() > 0.6) { type = 'zigzag'; emoji = '👻'; }
if (level >= 4 && Math.random() > 0.7) { type = 'chaser'; emoji = '💀'; }
ghosts.push({ x, y: -30, speed, type, emoji });
}
function spawnCoin() {
if (isTransitioning) return;
const x = Math.random() * (canvas.width - 30);
coins.push({ x, y: -30 });
}
function spawnPowerup() {
if (isTransitioning) return;
const x = Math.random() * (canvas.width - 30);
const types = ['shield', 'slow', 'magnet', 'freeze', 'shrink'];
const emojis = {'shield':'🛡️', 'slow':'🐢', 'magnet':'🧲', 'freeze':'❄️', 'shrink':'🍄'};
const type = types[Math.floor(Math.random() * types.length)];
powerups.push({ x, y: -30, type, emoji: emojis[type] });
}
function checkCollisions() {
let pW = player.shrink ? 20 : 40;
// Ghosts
let hit = ghosts.some(g => g.y + 30 > player.y && g.x < player.x + pW && g.x + 30 > player.x);
// Boss Projectiles
if (boss) {
hit = hit || boss.projectiles.some(p => p.y + 10 > player.y && p.y < player.y + pW && p.x > player.x && p.x < player.x + pW);
}
if (hit) {
if (player.shield) {
playSound('hit');
ghosts = ghosts.filter(g => !(g.y + 30 > player.y && g.x < player.x + pW && g.x + 30 > player.x));
if(boss) boss.projectiles = boss.projectiles.filter(p => !(p.y + 10 > player.y && p.x > player.x && p.x < player.x + pW));
} else {
endGame();
}
}
// Powerups
powerups.forEach((p, index) => {
if (p.y + 30 > player.y && p.x < player.x + pW && p.x + 30 > player.x) {
playSound('powerup');
if (p.type === 'shield') { player.shield = true; setTimeout(() => player.shield = false, 5000); }
else if (p.type === 'slow') { speed = Math.max(1, speed - 2); setTimeout(() => speed += 2, 5000); }
else if (p.type === 'magnet') { player.magnet = true; setTimeout(() => player.magnet = false, 7000); }
else if (p.type === 'freeze') { player.freeze = true; setTimeout(() => player.freeze = false, 4000); }
else if (p.type === 'shrink') { player.shrink = true; setTimeout(() => player.shrink = false, 5000); }
powerups.splice(index, 1);
}
});
// Coins
coins.forEach((c, index) => {
if (c.y + 30 > player.y && c.x < player.x + pW && c.x + 30 > player.x) {
playSound('coin');
comboCount++;
comboTimer = 90; // 3 seconds at 30fps
let multiplier = Math.min(comboCount, 5);
sessionCoins += multiplier;
coins.splice(index, 1);
}
});
}
function handleKeys() {
let moveSpeed = 5;
let pW = player.shrink ? 20 : 40;
if (keys['ArrowLeft']) player.x -= moveSpeed;
if (keys['ArrowRight']) player.x += moveSpeed;
if (player.x < 0) player.x = 0;
if (player.x + pW > canvas.width) player.x = canvas.width - pW;
}
function triggerLevelTransition() {
isTransitioning = true;
level++;
ghosts = [];
coins = [];
powerups = [];
particles = [];
speed += 0.5;
if (level % 3 === 0) {
boss = { x: canvas.width/2 - 40, y: 50, width: 80, height: 80, hp: 20 + (level*5), emoji: '👹', moveDir: 2, projectiles: [] };
}
setTimeout(() => {
levelTimeLeft = 60;
isTransitioning = false;
}, 2000);
}
function gameTick() {
if (paused) return;
drawBackground();
if (isTransitioning) { drawHUD(); return; }
handleKeys();
updateEntities();
drawPlayer();
ghosts.forEach(g => drawEmoji(g.x, g.y, g.emoji));
powerups.forEach(p => drawEmoji(p.x, p.y, p.emoji));
coins.forEach(c => drawEmoji(c.x, c.y, '🪙'));
if (boss) {
drawEmoji(boss.x, boss.y, boss.emoji, 80);
ctx.fillStyle = "red";
boss.projectiles.forEach(p => { ctx.beginPath(); ctx.arc(p.x, p.y, 6, 0, Math.PI*2); ctx.fill(); });
// Boss HP Bar
ctx.fillStyle = "red";
ctx.fillRect(boss.x, boss.y - 20, 80, 5);
ctx.fillStyle = "lime";
ctx.fillRect(boss.x, boss.y - 20, 80 * (boss.hp / (20 + (level*5))), 5);
}
drawHUD();
checkCollisions();
}
function setPlayerEmoji(emoji) {
player.emoji = emoji;
renderSkinSelectors();
}
function startGame(selectedDifficulty) {
initAudio();
difficulty = selectedDifficulty;
speed = difficulty === 'easy' ? 2 : difficulty === 'medium' ? 3 : 4;
survivalTime = 0;
level = 1;
levelTimeLeft = 60;
isTransitioning = false;
sessionCoins = 0;
comboCount = 0;
player.x = 180;
player.shield = player.magnet = player.freeze = player.shrink = false;
player.projectiles = [];
ghosts = [];
powerups = [];
coins = [];
particles = [];
boss = null;
paused = false;
startScreen.classList.remove('active');
canvas.style.display = 'block';
pauseOverlay.style.display = 'none';
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
gameLoop = setInterval(gameTick, 30);
spawnLoop = setInterval(spawnGhost, 800);
powerupLoop = setInterval(spawnPowerup, 8000);
coinLoop = setInterval(spawnCoin, 2000);
timerLoop = setInterval(() => {
if (!paused && !isTransitioning) {
survivalTime++;
if (!boss) {
levelTimeLeft--;
if (levelTimeLeft <= 0) triggerLevelTransition();
}
}
}, 1000);
}
function handleKeyDown(e) { keys[e.key] = true; if (e.key === 'Escape') togglePause(); }
function handleKeyUp(e) { keys[e.key] = false; }
function togglePause() {
paused = !paused;
pauseOverlay.style.display = paused ? 'flex' : 'none';
}
function endGame() {
playSound('hit');
clearInterval(gameLoop);
clearInterval(spawnLoop);
clearInterval(timerLoop);
clearInterval(powerupLoop);
clearInterval(coinLoop);
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('keyup', handleKeyUp);
canvas.style.display = 'none';
pauseOverlay.style.display = 'none';
gameOverScreen.classList.add('active');
scoreDisplay.textContent = `⏱ You survived for ${survivalTime} seconds. (Level ${level})`;
sessionCoinsDisplay.textContent = `Coins Collected: ${sessionCoins} 🪙`;
totalCoins += sessionCoins;
localStorage.setItem('ghostDodgerTotalCoins', totalCoins);
updateCoinDisplays();
let best = localStorage.getItem('ghostDodgerHighScore') || 0;
if (survivalTime > best) {
best = survivalTime;
localStorage.setItem('ghostDodgerHighScore', best);
}
highScoreDisplay.textContent = `🏆 High Score: ${best} seconds`;
}
function restartGame() {
gameOverScreen.classList.remove('active');
startScreen.classList.add('active');
}
function showToast(msg) {
const toast = document.getElementById("toast");
toast.textContent = msg;
toast.className = "show";
setTimeout(() => { toast.className = toast.className.replace("show", ""); }, 3000);
}
function shareScore() {
const diffEmoji = difficulty === 'hard' ? '😈' : difficulty === 'medium' ? '😬' : '😌';
const text = `Ghost Dodger 👻 | Score: ${survivalTime}s | Level: ${level} | Difficulty: ${difficulty} ${diffEmoji}`;
if (navigator.share) {
navigator.share({ title: 'Ghost Dodger Score', text: text }).catch(err => console.error(err));
} else {
navigator.clipboard.writeText(text).then(() => showToast("Score copied to clipboard!"));
}
}
renderSkinSelectors();
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js').catch(err => console.error('SW failed:', err));
});
}
</script>
</body>
</html>