-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
2164 lines (1888 loc) · 57.5 KB
/
game.js
File metadata and controls
2164 lines (1888 loc) · 57.5 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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ERROR DISPLAY SYSTEM
function displayError(msg, url, lineNo, columnNo, error) {
const errorDisplay = document.getElementById('errorDisplay');
if (errorDisplay) {
errorDisplay.style.display = 'block';
const errorMsg = document.createElement('div');
errorMsg.style.marginBottom = '8px';
errorMsg.style.borderBottom = '1px solid rgba(255,255,255,0.3)';
errorMsg.style.paddingBottom = '4px';
let text = '❌ ' + msg;
if (url) text += '\nAt: ' + url + ':' + lineNo + ':' + columnNo;
if (error && error.stack) text += '\nStack: ' + error.stack;
errorMsg.innerText = text;
errorDisplay.appendChild(errorMsg);
}
return false;
}
window.onerror = displayError;
window.addEventListener('unhandledrejection', function(event) {
displayError('Unhandled Promise Rejection: ' + event.reason, null, null, null, event.reason);
});
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
// Audio context and sound system
let audioCtx = null;
let soundEnabled = true;
function initAudio() {
if (audioCtx) return;
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
} catch (e) {
soundEnabled = false;
}
}
function playTone(frequency, duration, type = "square", volume = 0.15, ramp = true) {
if (!audioCtx || !soundEnabled) return;
if (audioCtx.state === "suspended") {
audioCtx.resume();
}
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequency, audioCtx.currentTime);
gainNode.gain.setValueAtTime(volume, audioCtx.currentTime);
if (ramp) {
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
}
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + duration);
}
function playJumpSound() {
if (!audioCtx || !soundEnabled) return;
// Rising tone for jump
playTone(280, 0.08, "square", 0.12);
setTimeout(() => playTone(420, 0.1, "square", 0.1), 40);
}
function playPunchSound() {
if (!audioCtx || !soundEnabled) return;
// Punchy noise burst
const duration = 0.12;
const bufferSize = audioCtx.sampleRate * duration;
const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / bufferSize, 2);
}
if (audioCtx.state === "suspended") audioCtx.resume();
const noise = audioCtx.createBufferSource();
const gainNode = audioCtx.createGain();
const filter = audioCtx.createBiquadFilter();
noise.buffer = buffer;
filter.type = "lowpass";
filter.frequency.setValueAtTime(800, audioCtx.currentTime);
gainNode.gain.setValueAtTime(0.25, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
noise.connect(filter);
filter.connect(gainNode);
gainNode.connect(audioCtx.destination);
noise.start();
}
function playOrbSound() {
if (!audioCtx || !soundEnabled) return;
// Pleasant chime for orb collection
playTone(880, 0.08, "sine", 0.1);
setTimeout(() => playTone(1100, 0.12, "sine", 0.08), 50);
}
function playHurtSound() {
if (!audioCtx || !soundEnabled) return;
// Descending buzzy tone
if (audioCtx.state === "suspended") audioCtx.resume();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = "sawtooth";
oscillator.frequency.setValueAtTime(300, audioCtx.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(100, audioCtx.currentTime + 0.2);
gainNode.gain.setValueAtTime(0.15, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.25);
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.start();
oscillator.stop(audioCtx.currentTime + 0.25);
}
function playLevelCompleteSound() {
if (!audioCtx || !soundEnabled) return;
// Victory fanfare
const notes = [523, 659, 784, 1047];
notes.forEach((freq, i) => {
setTimeout(() => playTone(freq, 0.2, "sine", 0.12), i * 100);
});
}
function playGameOverSound() {
if (!audioCtx || !soundEnabled) return;
// Sad descending tones
const notes = [400, 350, 300, 250];
notes.forEach((freq, i) => {
setTimeout(() => playTone(freq, 0.25, "triangle", 0.1), i * 120);
});
}
// Background music system
let musicEnabled = true;
let musicPlaying = false;
let musicGain = null;
let musicInterval = null;
// Chip-tune style background music
const musicPatterns = {
// Bass line (root notes)
bass: [
{ note: 110, duration: 0.2 }, // A2
{ note: 110, duration: 0.2 },
{ note: 147, duration: 0.2 }, // D3
{ note: 147, duration: 0.2 },
{ note: 165, duration: 0.2 }, // E3
{ note: 165, duration: 0.2 },
{ note: 147, duration: 0.2 }, // D3
{ note: 131, duration: 0.2 }, // C3
],
// Melody (higher notes)
melody: [
{ note: 440, duration: 0.1 }, // A4
{ note: 0, duration: 0.1 }, // rest
{ note: 523, duration: 0.1 }, // C5
{ note: 0, duration: 0.1 },
{ note: 587, duration: 0.2 }, // D5
{ note: 523, duration: 0.1 }, // C5
{ note: 440, duration: 0.1 }, // A4
{ note: 392, duration: 0.2 }, // G4
{ note: 440, duration: 0.1 }, // A4
{ note: 0, duration: 0.1 },
{ note: 523, duration: 0.2 }, // C5
{ note: 587, duration: 0.1 }, // D5
{ note: 659, duration: 0.1 }, // E5
{ note: 587, duration: 0.2 }, // D5
{ note: 523, duration: 0.1 }, // C5
{ note: 440, duration: 0.1 }, // A4
],
};
let musicBassIndex = 0;
let musicMelodyIndex = 0;
let musicBeatTime = 0;
function playMusicNote(frequency, duration, type, volume) {
if (!audioCtx || !musicEnabled || frequency === 0) return;
if (audioCtx.state === "suspended") audioCtx.resume();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequency, audioCtx.currentTime);
gainNode.gain.setValueAtTime(volume, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration * 0.9);
oscillator.connect(gainNode);
if (musicGain) {
gainNode.connect(musicGain);
} else {
gainNode.connect(audioCtx.destination);
}
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + duration);
}
function musicTick() {
if (!musicPlaying || !musicEnabled) return;
// Play bass note
const bassNote = musicPatterns.bass[musicBassIndex];
playMusicNote(bassNote.note, bassNote.duration, "triangle", 0.06);
musicBassIndex = (musicBassIndex + 1) % musicPatterns.bass.length;
// Play melody note every other beat
if (musicBeatTime % 2 === 0) {
const melodyNote = musicPatterns.melody[musicMelodyIndex];
playMusicNote(melodyNote.note, melodyNote.duration, "square", 0.04);
musicMelodyIndex = (musicMelodyIndex + 1) % musicPatterns.melody.length;
}
musicBeatTime++;
}
function startMusic() {
if (!audioCtx || musicPlaying) return;
// Create master gain for music
musicGain = audioCtx.createGain();
musicGain.gain.setValueAtTime(0.5, audioCtx.currentTime);
musicGain.connect(audioCtx.destination);
musicPlaying = true;
musicBassIndex = 0;
musicMelodyIndex = 0;
musicBeatTime = 0;
// 150 BPM = 400ms per beat
musicInterval = setInterval(musicTick, 200);
}
function stopMusic() {
musicPlaying = false;
if (musicInterval) {
clearInterval(musicInterval);
musicInterval = null;
}
}
function toggleMusic() {
musicEnabled = !musicEnabled;
if (musicEnabled && state.running && !state.paused) {
startMusic();
} else {
stopMusic();
}
updateMusicButton();
}
function updateMusicButton() {
const musicBtn = document.getElementById("musicBtn");
if (musicBtn) {
musicBtn.textContent = musicEnabled ? "♪" : "♪̸";
musicBtn.classList.toggle("muted", !musicEnabled);
}
}
// Menu elements
const startMenu = document.getElementById("startMenu");
const pauseMenu = document.getElementById("pauseMenu");
const gameOverMenu = document.getElementById("gameOverMenu");
const levelComplete = document.getElementById("levelComplete");
const hud = document.getElementById("hud");
const mobileControls = document.getElementById("mobileControls");
const pcControls = document.getElementById("pcControls");
// Mode selection elements
const pcModeBtn = document.getElementById("pcModeBtn");
const mobileModeBtn = document.getElementById("mobileModeBtn");
const pcTutorialHints = document.getElementById("pcTutorialHints");
const mobileTutorialHints = document.getElementById("mobileTutorialHints");
// Game mode state
let gameMode = 'pc'; // 'pc' or 'mobile'
const playBtn = document.getElementById("playBtn");
const resumeBtn = document.getElementById("resumeBtn");
const quitBtn = document.getElementById("quitBtn");
const retryBtn = document.getElementById("retryBtn");
const nextLevelBtn = document.getElementById("nextLevelBtn");
const toast = document.getElementById("toast");
const mobileJump = document.getElementById("mobileJump");
const mobilePunch = document.getElementById("mobilePunch");
const mobilePause = document.getElementById("mobilePause");
const scoreEl = document.getElementById("score");
const comboEl = document.getElementById("combo");
const comboDisplay = document.getElementById("comboDisplay");
const levelEl = document.getElementById("level");
const livesDisplay = document.getElementById("livesDisplay");
const menuBest = document.getElementById("menuBest");
const finalScore = document.getElementById("finalScore");
const finalBest = document.getElementById("finalBest");
const gameOverTitle = document.getElementById("gameOverTitle");
const levelTitle = document.getElementById("levelTitle");
const levelScore = document.getElementById("levelScore");
const levelProgressBar = document.getElementById("levelProgressBar");
const levelProgressText = document.getElementById("levelProgressText");
const levelNameEl = document.getElementById("levelName");
const BASE_WIDTH = 960;
const BASE_HEIGHT = 540;
const groundY = BASE_HEIGHT - 70;
const spriteSets = {
idle: ["sprites/mac_idle.png", "sprites/mac_idle_blink.png"],
run: [
"sprites/mac_run_1.png",
"sprites/mac_run_2.png",
"sprites/mac_run_3.png",
"sprites/mac_run_4.png"
],
jump: ["sprites/mac_jump_1.png", "sprites/mac_jump_2.png", "sprites/mac_jump_3.png"],
attack: ["sprites/mac_attack_1.png", "sprites/mac_attack_2.png"],
hurt: ["sprites/mac_hurt.png"],
victory: ["sprites/mac_victory.png"],
super: ["sprites/mac_super.png"],
defeated: ["sprites/mac_defeated.jpg"],
magnus_idle: ["sprites/magnus/magnus_idle.png"],
magnus_run: [
"sprites/magnus/magnus_run_1.png",
"sprites/magnus/magnus_run_2.png",
"sprites/magnus/magnus_run_3.png",
"sprites/magnus/magnus_run_4.png"
],
magnus_jump: ["sprites/magnus/magnus_jump_1.png", "sprites/magnus/magnus_jump_2.png"],
magnus_tired: ["sprites/magnus/magnus_tired.png"],
};
const sprites = {};
let spritesReady = false;
const LEVEL_BASE_LENGTH = 2500;
const LEVEL_LENGTH_STEP = 400;
const LEVEL_NAMES = [
"Donovan's Landing",
"Magnus's Chase",
"Neon Harbor",
"Skyline Bounce",
"Turbo Plaza",
"Starlight Circuit",
];
// Improved level design with more varied patterns
const segmentTemplates = [
// Easy patterns - single obstacles with generous spacing
{
difficulty: 1,
length: 550,
obstacles: [{ at: 250, type: "ground" }],
orbs: [{ at: 350, height: 140 }, { at: 420, height: 140 }, { at: 490, height: 140 }],
},
{
difficulty: 1,
length: 600,
obstacles: [{ at: 280, type: "ground", width: 60, height: 80 }],
orbs: [{ at: 400, height: 180 }, { at: 500, height: 120 }],
},
// Medium patterns - two obstacles, varied heights
{
difficulty: 1,
length: 700,
obstacles: [{ at: 250, type: "ground" }, { at: 500, type: "ground" }],
orbs: [{ at: 375, height: 200 }],
},
{
difficulty: 2,
length: 750,
obstacles: [
{ at: 280, type: "air", y: groundY - 180 },
{ at: 550, type: "ground" },
],
orbs: [{ at: 400, height: 100 }, { at: 650, height: 180 }],
},
{
difficulty: 2,
length: 800,
obstacles: [
{ at: 300, type: "ground", width: 80, height: 100 },
{ at: 580, type: "air", y: groundY - 200 },
],
orbs: [{ at: 440, height: 200 }, { at: 700, height: 140 }],
},
// Hard patterns - three obstacles, require skill
{
difficulty: 3,
length: 900,
obstacles: [
{ at: 250, type: "ground" },
{ at: 480, type: "air", y: groundY - 190 },
{ at: 720, type: "ground" },
],
orbs: [{ at: 360, height: 200 }, { at: 600, height: 100 }, { at: 820, height: 180 }],
},
{
difficulty: 3,
length: 950,
obstacles: [
{ at: 280, type: "ground", width: 70, height: 90 },
{ at: 520, type: "ground" },
{ at: 760, type: "air", y: groundY - 210 },
],
orbs: [{ at: 400, height: 220 }, { at: 640, height: 180 }],
},
// Orb bonanza - fewer obstacles, lots of orbs
{
difficulty: 1,
length: 650,
obstacles: [{ at: 320, type: "ground" }],
orbs: [
{ at: 180, height: 120 },
{ at: 240, height: 160 },
{ at: 420, height: 140 },
{ at: 480, height: 180 },
{ at: 540, height: 200 },
],
},
];
const state = {
running: false,
paused: false,
gameOver: false,
gameOverTime: 0,
score: 0,
best: Number(localStorage.getItem("macgame_best")) || 0,
bestBefore: 0,
combo: 1,
comboTimer: 0, // Timer for combo decay visual
fun: 0,
health: 3,
time: 0,
animTime: 0,
speed: 260,
shake: 0,
hitFlash: 0, // Red flash on hit
toastTimer: 0,
level: 1,
distance: 0,
levelTarget: LEVEL_BASE_LENGTH,
spawnPlan: [],
spawnIndex: 0,
awaitingNextLevel: false,
showTutorial: !localStorage.getItem("macgame_played"), // First time player
pendingUpdate: false, // PWA update pending
};
const player = {
x: 170,
y: groundY,
vy: 0,
width: 170,
height: 240,
jumpPower: 820,
gravity: 1800,
onGround: true,
attackTimer: 0,
attackCooldown: 0,
hurtTimer: 0,
invincible: 0,
jumpBuffer: 0,
coyoteTimer: 0,
};
const JUMP_BUFFER_TIME = 0.12;
const COYOTE_TIME = 0.12;
const ATTACK_DURATION = 0.35;
const obstacles = [];
const orbs = [];
const particles = [];
const floatingTexts = []; // Floating score popups
const confetti = []; // Celebration confetti
// Magnus the cute puppy chase mechanic - BIGGER and better positioned
const magnus = {
x: -200,
y: groundY - 45,
width: 160,
height: 120,
active: false,
state: 'idle', // idle, chasing, tired, happy
chaseTimer: 0,
tiredTimer: 0,
happyTimer: 0,
frame: 0,
frameTimer: 0,
velocity: 0,
acceleration: 400,
maxSpeed: 280, // Slightly faster max speed
barkTimer: 0,
visible: false,
hasLicked: false,
};
// Canvas scaling with letterboxing for proper aspect ratio
let canvasScale = 1;
let canvasOffsetX = 0;
let canvasOffsetY = 0;
function resizeCanvas() {
const dpr = window.devicePixelRatio || 1;
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
// Calculate scale to fit while maintaining aspect ratio
const targetRatio = BASE_WIDTH / BASE_HEIGHT;
const screenRatio = screenWidth / screenHeight;
let drawWidth, drawHeight;
if (screenRatio > targetRatio) {
// Screen is wider than game - letterbox sides
drawHeight = screenHeight;
drawWidth = screenHeight * targetRatio;
} else {
// Screen is taller than game - letterbox top/bottom
drawWidth = screenWidth;
drawHeight = screenWidth / targetRatio;
}
// Center the canvas
canvasOffsetX = (screenWidth - drawWidth) / 2;
canvasOffsetY = (screenHeight - drawHeight) / 2;
canvasScale = drawWidth / BASE_WIDTH;
// Set canvas size
canvas.style.width = drawWidth + 'px';
canvas.style.height = drawHeight + 'px';
canvas.style.left = canvasOffsetX + 'px';
canvas.style.top = canvasOffsetY + 'px';
canvas.width = drawWidth * dpr;
canvas.height = drawHeight * dpr;
ctx.setTransform(canvas.width / BASE_WIDTH, 0, 0, canvas.height / BASE_HEIGHT, 0, 0);
}
window.addEventListener("resize", resizeCanvas);
function loadSprites() {
const entries = Object.entries(spriteSets);
let loaded = 0;
let total = 0;
entries.forEach(([, frames]) => {
total += frames.length;
});
entries.forEach(([key, frames]) => {
sprites[key] = frames.map((src) => {
const img = new Image();
img.onload = () => {
img.__meta = computeSpriteMeta(img);
loaded += 1;
if (loaded === total) {
spritesReady = true;
// Update menu with best score
if (menuBest) menuBest.textContent = state.best;
}
};
img.onerror = () => {
console.error("Failed to load sprite:", src);
};
img.src = src;
return img;
});
});
}
function computeSpriteMeta(img) {
const w = img.width;
const h = img.height;
const temp = document.createElement("canvas");
temp.width = w;
temp.height = h;
const tctx = temp.getContext("2d");
tctx.drawImage(img, 0, 0);
const data = tctx.getImageData(0, 0, w, h).data;
let minX = w;
let minY = h;
let maxX = 0;
let maxY = 0;
let found = false;
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
const alpha = data[(y * w + x) * 4 + 3];
if (alpha > 10) {
found = true;
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
}
if (!found) {
return { width: w, height: h, centerX: w / 2, footY: h };
}
return {
width: w,
height: h,
centerX: (minX + maxX) / 2,
footY: maxY,
};
}
function configureOverlay({ title, text, showStart = false, showResume = false, resumeLabel = "Resume" }) {
// Legacy function - kept for compatibility but now using new menus
}
// New menu system
function showMenu(menuElement) {
hideAllMenus();
if (menuElement) menuElement.classList.remove("hidden");
}
function hideAllMenus() {
if (startMenu) startMenu.classList.add("hidden");
if (pauseMenu) pauseMenu.classList.add("hidden");
if (gameOverMenu) gameOverMenu.classList.add("hidden");
if (levelComplete) levelComplete.classList.add("hidden");
}
function showHUD() {
if (hud) hud.classList.remove("hidden");
// Show controls based on selected mode
if (gameMode === 'mobile') {
if (mobileControls) mobileControls.classList.remove("hidden");
if (pcControls) pcControls.classList.add("hidden");
} else {
// PC mode - show keyboard hints
if (mobileControls) mobileControls.classList.add("hidden");
if (pcControls) pcControls.classList.remove("hidden");
}
}
function hideHUD() {
if (hud) hud.classList.add("hidden");
if (mobileControls) mobileControls.classList.add("hidden");
if (pcControls) pcControls.classList.add("hidden");
}
function updateLivesDisplay() {
if (livesDisplay) {
livesDisplay.textContent = "❤".repeat(state.health);
}
}
function resetGame() {
state.running = true;
state.paused = false;
state.gameOver = false;
state.score = 0;
state.combo = 1;
state.fun = 0;
state.health = 3;
state.time = 0;
state.animTime = 0;
state.speed = 260;
state.shake = 0;
state.toastTimer = 0;
state.bestBefore = state.best;
state.awaitingNextLevel = false;
player.y = groundY;
player.vy = 0;
player.onGround = true;
player.attackTimer = 0;
player.attackCooldown = 0;
player.hurtTimer = 0;
player.invincible = 0;
player.jumpBuffer = 0;
player.coyoteTimer = 0;
// Reset Magnus
magnus.state = 'idle';
magnus.visible = false;
magnus.active = false;
magnus.hasLicked = false;
magnus.chaseTimer = 0;
magnus.tiredTimer = 0;
magnus.happyTimer = 0;
magnus.velocity = 0;
magnus.x = -200;
setupLevel(1, true);
updateLivesDisplay();
hideAllMenus();
showHUD();
// Show level start notification
const levelIndex = Math.min(state.level - 1, LEVEL_NAMES.length - 1);
showToast(`${LEVEL_NAMES[levelIndex]}!`);
// Start background music
if (musicEnabled) startMusic();
}
function hideOverlay() {
hideAllMenus();
}
function maxDifficultyForLevel(level) {
if (level <= 1) return 1;
if (level <= 3) return 2;
return 3;
}
function pickSegmentTemplate(level) {
const maxDifficulty = maxDifficultyForLevel(level);
const pool = segmentTemplates.filter((template) => template.difficulty <= maxDifficulty);
return pool[Math.floor(Math.random() * pool.length)];
}
function buildLevelPlan(level) {
const target = LEVEL_BASE_LENGTH + (level - 1) * LEVEL_LENGTH_STEP;
const spawns = [];
let cursor = 0;
while (cursor < target) {
const template = pickSegmentTemplate(level);
template.obstacles.forEach((obs) => {
spawns.push({
at: cursor + obs.at,
kind: "obstacle",
data: obs,
});
});
template.orbs.forEach((orb) => {
spawns.push({
at: cursor + orb.at,
kind: "orb",
data: orb,
});
});
cursor += template.length;
}
spawns.sort((a, b) => a.at - b.at);
return { spawns, target };
}
function setupLevel(level, resetScore) {
// Validate level number
level = Math.max(1, Math.floor(level));
state.level = level;
state.distance = 0;
state.spawnIndex = 0;
state.awaitingNextLevel = false;
// Build level plan with proper target distance
const plan = buildLevelPlan(level);
state.spawnPlan = plan.spawns;
state.levelTarget = plan.target;
// Scale speed with level (starts at 260, increases by 14 per level)
state.speed = 260 + (level - 1) * 14;
// Clear all game entities
obstacles.length = 0;
orbs.length = 0;
particles.length = 0;
floatingTexts.length = 0;
confetti.length = 0;
// Reset Magnus when changing levels
magnus.state = 'idle';
magnus.visible = false;
magnus.hasLicked = false;
magnus.chaseTimer = 0;
magnus.tiredTimer = 0;
magnus.happyTimer = 0;
magnus.velocity = 0;
magnus.x = -200;
if (resetScore) {
state.score = 0;
state.combo = 1;
state.fun = 0;
state.health = 3;
}
console.log(`Level ${level} started: ${LEVEL_NAMES[Math.min(level - 1, LEVEL_NAMES.length - 1)] || 'Unknown'} - Target: ${state.levelTarget}m`);
}
function completeLevel() {
state.running = false;
state.paused = false;
state.awaitingNextLevel = true;
state.gameOver = false;
playLevelCompleteSound();
stopMusic();
// Add celebration confetti
addConfetti(BASE_WIDTH / 2, BASE_HEIGHT / 3, 40);
hideHUD();
if (levelTitle) levelTitle.textContent = `LEVEL ${state.level} COMPLETE!`;
if (levelScore) levelScore.textContent = Math.floor(state.score);
// Show victory image for high scores or perfect runs
const victoryImg = document.getElementById("victoryImage");
if (victoryImg) {
const isHighScore = state.score > state.best * 0.8;
const isPerfect = state.health === 3;
victoryImg.style.display = (isHighScore || isPerfect) ? "block" : "none";
if (isHighScore || isPerfect) {
if (levelTitle) levelTitle.textContent = `LEVEL ${state.level} COMPLETE! 🦸♂️`;
}
}
// Update next level button text
const nextLevelBtn = document.getElementById("nextLevelBtn");
if (nextLevelBtn) {
const nextLevelName = LEVEL_NAMES[Math.min(state.level, LEVEL_NAMES.length - 1)] || `Level ${state.level + 1}`;
nextLevelBtn.textContent = `NEXT: ${nextLevelName}`;
}
showMenu(levelComplete);
}
function showToast(message) {
// Don't show toasts if game is ending (so score is visible)
if (state.health <= 0) return;
toast.textContent = message;
toast.classList.remove("hidden");
state.toastTimer = 1.2;
}
function hideToast() {
toast.classList.add("hidden");
state.toastTimer = 0;
}
function updateToast(dt) {
if (state.toastTimer > 0) {
state.toastTimer -= dt;
if (state.toastTimer <= 0) {
toast.classList.add("hidden");
}
}
}
function createObstacle(options = {}) {
const type = options.type || (Math.random() < 0.7 ? "ground" : "air");
const height =
options.height !== undefined
? options.height
: type === "ground"
? 70 + Math.random() * 40
: 80;
const width =
options.width !== undefined ? options.width : type === "ground" ? 50 + Math.random() * 30 : 60;
const y =
options.y !== undefined
? options.y
: type === "ground"
? groundY
: groundY - 180 - Math.random() * 80;
obstacles.push({
x: BASE_WIDTH + 60,
y,
width,
height,
type,
hit: false,
});
}
function createOrb(options = {}) {
const height = options.height !== undefined ? options.height : 120 + Math.random() * 140;
orbs.push({
x: BASE_WIDTH + 60,
y: options.y !== undefined ? options.y : groundY - height,
radius: 14,
collected: false,
});
}
function addParticles(x, y, color) {
for (let i = 0; i < 10; i += 1) {
particles.push({
x,
y,
vx: (Math.random() - 0.5) * 220,
vy: -80 - Math.random() * 220,
life: 0.6 + Math.random() * 0.5,
color,
});
}
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i -= 1) {
const p = particles[i];
p.life -= dt;
p.vy += 520 * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
if (p.life <= 0) {
particles.splice(i, 1);
}
}
}
// Floating score text popups
function addFloatingText(x, y, text, color = "#fff") {
floatingTexts.push({
x,
y,
text,
color,
life: 1.0,
vy: -80,
});
}
function updateFloatingTexts(dt) {
for (let i = floatingTexts.length - 1; i >= 0; i -= 1) {
const ft = floatingTexts[i];
ft.life -= dt;
ft.y += ft.vy * dt;
ft.vy *= 0.95; // Slow down
if (ft.life <= 0) {
floatingTexts.splice(i, 1);
}
}
}
function drawFloatingTexts() {
floatingTexts.forEach((ft) => {
ctx.globalAlpha = Math.max(0, ft.life);
ctx.fillStyle = ft.color;
ctx.font = "bold 24px Outfit, sans-serif";
ctx.textAlign = "center";
ctx.fillText(ft.text, ft.x, ft.y);
});
ctx.globalAlpha = 1;
}
// Confetti for celebrations
function addConfetti(x, y, count = 30) {
const colors = ["#ff7a2f", "#30d6ff", "#ffe15d", "#ff5599", "#44ff88"];
for (let i = 0; i < count; i++) {
confetti.push({
x,
y,
vx: (Math.random() - 0.5) * 400,
vy: -200 - Math.random() * 300,
rotation: Math.random() * 360,
rotationSpeed: (Math.random() - 0.5) * 720,
width: 8 + Math.random() * 8,
height: 4 + Math.random() * 4,
color: colors[Math.floor(Math.random() * colors.length)],
life: 2 + Math.random(),
});
}
}
function updateMagnus(dt) {
if (!magnus.active) return;
// Update frame timer for smooth animation
magnus.frameTimer += dt;
if (magnus.barkTimer > 0) magnus.barkTimer -= dt;
switch (magnus.state) {
case 'chasing':
// Accelerate towards player but stay visible on screen
const targetX = player.x - 120; // Target position behind player
const dx = targetX - magnus.x;
if (dx > 0) {
magnus.velocity += magnus.acceleration * dt;