awacke1 commited on
Commit
6612fe6
·
verified ·
1 Parent(s): fe8620d

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +1079 -636
index.html CHANGED
@@ -1,702 +1,1145 @@
1
  <!DOCTYPE html>
2
  <html lang="en">
3
  <head>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Chord Sheet Teleprompter</title>
7
- <!-- Tailwind CSS CDN -->
8
  <script src="https://cdn.tailwindcss.com"></script>
9
- <!-- Tone.js CDN -->
10
- <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.min.js"></script>
11
  <style>
12
- body {
13
- font-family: "Inter", sans-serif;
14
- margin: 0;
15
- overflow: hidden; /* Prevent body scroll, main content handles scroll */
16
- }
17
- /* Custom scrollbar for main content */
18
- .custom-scrollbar::-webkit-scrollbar {
19
- width: 8px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  }
21
- .custom-scrollbar::-webkit-scrollbar-track {
22
- background: #2d3748; /* bg-gray-800 */
 
 
 
 
23
  }
24
- .custom-scrollbar::-webkit-scrollbar-thumb {
25
- background: #4a5568; /* bg-gray-600 */
26
- border-radius: 4px;
 
27
  }
28
- .custom-scrollbar::-webkit-scrollbar-thumb:hover {
29
- background: #6b7280; /* bg-gray-500 */
30
  }
31
- /* Preserve whitespace and prevent wrapping for chords */
32
- .whitespace-pre {
33
- white-space: pre;
34
  }
35
  </style>
36
  </head>
37
- <body class="bg-gray-900 text-gray-100 flex flex-col h-screen">
38
-
39
- <!-- Header Section -->
40
- <header class="p-4 bg-gray-800 shadow-md text-center rounded-b-lg flex flex-col items-center justify-center">
41
- <div class="flex items-center justify-center space-x-4 mb-2">
42
- <button id="prevSongBtnHeader" class="bg-gray-700 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg transition duration-300 ease-in-out transform hover:scale-105">
43
- &#9650; <!-- Up Arrow -->
44
- </button>
45
- <div class="text-center">
46
- <h1 id="songTitle" class="text-3xl font-bold text-blue-400"></h1>
47
- <p id="artistName" class="text-xl text-gray-300"></p>
 
 
 
 
 
48
  </div>
49
- <button id="nextSongBtnHeader" class="bg-gray-700 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg transition duration-300 ease-in-out transform hover:scale-105">
50
- &#9660; <!-- Down Arrow -->
51
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  </div>
53
- </header>
54
-
55
- <!-- Main Content Area - Lyrics and Chords -->
56
- <main id="scrollContainer" class="flex-1 overflow-y-auto p-6 text-2xl leading-relaxed custom-scrollbar">
57
- <!-- Song content will be rendered here by JavaScript -->
58
- </main>
59
-
60
- <!-- Footer Section - Controls -->
61
- <footer class="p-4 bg-gray-800 shadow-t-md flex justify-center items-center space-x-4 rounded-t-lg flex-wrap">
62
- <button id="slowTempoBtn" class="py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:scale-105 my-2 bg-purple-500 hover:bg-purple-600 text-white font-bold">
63
- Slow (30 BPM)
64
- </button>
65
- <button id="mediumTempoBtn" class="py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:scale-105 my-2 bg-purple-700 text-white font-bold">
66
- Medium (90 BPM)
67
- </button>
68
- <button id="fastTempoBtn" class="py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:scale-105 my-2 bg-purple-500 hover:bg-purple-600 text-white font-bold">
69
- Fast (128 BPM)
70
- </button>
71
- <button id="arpeggioDirectionBtn" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:scale-105 my-2">
72
- Arpeggio: Rising
73
- </button>
74
- <button id="startTeleprompterBtn" class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-6 rounded-lg shadow-lg transition duration-300 ease-in-out transform hover:scale-105 my-2">
75
- Start/Restart Teleprompter (Press Space/Right Arrow)
76
- </button>
77
- </footer>
78
 
79
  <script>
80
- // Song data
81
- const songsData = [
82
- {
83
- title: "Talkin' 'bout a Revolution",
84
- artist: "Tracy Chapman",
85
- sections: [
86
- { type: "Intro", lines: [{ chords: "G C D G", lyrics: "" }] },
87
- { type: "Verse 1", lines: [
88
- { chords: "G C D G", lyrics: "While outside a revolution's talking..." },
89
- { chords: "G C D G", lyrics: "It's gonna come, it's gonna come..." }
90
- ]},
91
- { type: "Chorus 1", lines: [
92
- { chords: "G C D G", lyrics: "Talkin' 'bout a revolution, oh, no" },
93
- { chords: "G C D G", lyrics: "Talkin' 'bout a revolution..." }
94
- ]},
95
- { type: "Verse 2", lines: [
96
- { chords: "G C D G", lyrics: "While outside a revolution's talking..." },
97
- { chords: "G C D G", lyrics: "It's gonna come, it's gonna come..." }
98
- ]},
99
- { type: "Chorus 2", lines: [
100
- { chords: "G C D G", lyrics: "Talkin' 'bout a revolution, oh, no" },
101
- { chords: "G C D G", lyrics: "Talkin' 'bout a revolution..." }
102
- ]},
103
- { type: "Outro", lines: [{ chords: "G C D G", lyrics: "(repeat and fade)" }] }
104
- ]
105
- },
106
- {
107
- title: "Fast Car",
108
- artist: "Tracy Chapman",
109
- sections: [
110
- { type: "Intro", lines: [{ chords: "C G Am F", lyrics: "" }] },
111
- { type: "Verse 1", lines: [
112
- { chords: "C G Am F", lyrics: "You got a fast car, I want a ticket to anywhere..." },
113
- { chords: "C G Am F", lyrics: "We go driving in it, anywhere, maybe we'll make a deal..." }
114
- ]},
115
- { type: "Chorus 1", lines: [
116
- { chords: "C G Am F", lyrics: "So remember when we were driving, driving in your car..." },
117
- { chords: "C G Am F", lyrics: "The speed of light, we gotta go, go, go, go, go..." }
118
- ]},
119
- { type: "Verse 2", lines: [
120
- { chords: "C G Am F", lyrics: "You got a fast car, I got a plan to get us out of here..." },
121
- { chords: "C G Am F", lyrics: "I been working at the convenience store, so slow..." }
122
- ]},
123
- { type: "Chorus 2", lines: [
124
- { chords: "C G Am F", lyrics: "So remember when we were driving, driving in your car..." },
125
- { chords: "C G Am F", lyrics: "The speed of light, we gotta go, go, go, go, go..." }
126
- ]},
127
- { type: "Outro", lines: [{ chords: "C G Am F", lyrics: "(repeat and fade)" }] }
128
- ]
129
- },
130
- {
131
- title: "Cult of Personality",
132
- artist: "Living Colour",
133
- sections: [
134
- { type: "Intro", lines: [{ chords: "Em G C D", lyrics: "" }] },
135
- { type: "Verse 1", lines: [
136
- { chords: "Em G C D", lyrics: "Look in my eyes, what do you see?" },
137
- { chords: "Em G C D", lyrics: "The cult of personality." }
138
- ]},
139
- { type: "Chorus 1", lines: [
140
- { chords: "Em G C D", lyrics: "Cult of Personality! Cult of Personality!" }
141
- ]},
142
- { type: "Verse 2", lines: [
143
- { chords: "Em G C D", lyrics: "I look in your eyes, what do I see?" },
144
- { chords: "Em G C D", lyrics: "The cult of personality." }
145
- ]},
146
- { type: "Chorus 2", lines: [
147
- { chords: "Em G C D", lyrics: "Cult of Personality! Cult of Personality!" }
148
- ]},
149
- { type: "Outro", lines: [{ chords: "Em G C D", lyrics: "(repeated, building to a final hit on Em)" }] }
150
- ]
151
- },
152
- {
153
- title: "Glamour Boys",
154
- artist: "Living Colour",
155
- sections: [
156
- { type: "Intro", lines: [{ chords: "E B A E", lyrics: "" }] },
157
- { type: "Verse 1", lines: [
158
- { chords: "E B", lyrics: "The Glamour Boys, they got the girls" },
159
- { chords: "A E", lyrics: "They got the cars, they got the pearls" }
160
- ]},
161
- { type: "Chorus 1", lines: [
162
- { chords: "E B A E", lyrics: "Glamour Boys, oh, the Glamour Boys, what makes you think you're so cool?" }
163
- ]},
164
- { type: "Verse 2", lines: [
165
- { chords: "E B", lyrics: "The Glamour Boys, they're so hip" },
166
- { chords: "A E", lyrics: "They got the style, they got the trip" }
167
- ]},
168
- { type: "Chorus 2", lines: [
169
- { chords: "E B A E", lyrics: "Glamour Boys, oh, the Glamour Boys, what makes you think you're so cool?" }
170
- ]},
171
- { type: "Outro", lines: [{ chords: "E B A E", lyrics: "(repeat and fade with guitar licks)" }] }
172
- ]
173
- },
174
- {
175
- title: "Ocean Size",
176
- artist: "Jane's Addiction",
177
- sections: [
178
- { type: "Intro", lines: [{ chords: "C G Am F", lyrics: "" }] },
179
- { type: "Verse 1", lines: [
180
- { chords: "C G Am F", lyrics: "Day by day, as the weeks turn to months, I watch you..." },
181
- { chords: "C G Am F", lyrics: "Growing taller, growing wiser, growing stronger..." }
182
- ]},
183
- { type: "Chorus 1", lines: [
184
- { chords: "C G D F", lyrics: "Ocean size, it's the ocean size" },
185
- { chords: "C G D F", lyrics: "The ocean size, it's the ocean size" }
186
- ]},
187
- { type: "Verse 2", lines: [
188
- { chords: "C G Am F", lyrics: "Day by day, as the weeks turn to months, I watch you..." },
189
- { chords: "C G Am F", lyrics: "Growing stronger, growing wiser, growing taller..." }
190
- ]},
191
- { type: "Chorus 2", lines: [
192
- { chords: "C G D F", lyrics: "Ocean size, it's the ocean size" },
193
- { chords: "C G D F", lyrics: "The ocean size, it's the ocean size" }
194
- ]},
195
- { type: "Outro", lines: [{ chords: "C G Am F", lyrics: "(repeat and fade)" }] }
196
- ]
197
- },
198
- {
199
- title: "Mountain Song",
200
- artist: "Jane's Addiction",
201
- sections: [
202
- { type: "Intro", lines: [{ chords: "Em C G D", lyrics: "" }] },
203
- { type: "Verse 1", lines: [
204
- { chords: "Em C G D", lyrics: "Coming down the mountain, I saw a girl" },
205
- { chords: "Em C G D", lyrics: "She was looking at me, in my world" }
206
- ]},
207
- { type: "Chorus 1", lines: [
208
- { chords: "Em C G D", lyrics: "Mountain Song! Mountain Song!" }
209
- ]},
210
- { type: "Verse 2", lines: [
211
- { chords: "Em C G D", lyrics: "She said, \"Where'd you come from? Where'd you go?\"" },
212
- { chords: "Em C G D", lyrics: "\"I came from the mountain, don't you know?\"" }
213
- ]},
214
- { type: "Chorus 2", lines: [
215
- { chords: "Em C G D", lyrics: "Mountain Song! Mountain Song!" }
216
- ]},
217
- { type: "Outro", lines: [{ chords: "Em C G D", lyrics: "(repeat and fade)" }] }
218
- ]
219
- },
220
- {
221
- title: "Where Is My Mind?",
222
- artist: "Pixies",
223
- sections: [
224
- { type: "Intro", lines: [{ chords: "C G Am F", lyrics: "" }] },
225
- { type: "Verse 1", lines: [
226
- { chords: "C G Am F", lyrics: "With your feet on the air and your head on the ground..." },
227
- { chords: "C G Am F", lyrics: "Try this trick and spin it, yeah..." }
228
- ]},
229
- { type: "Chorus 1", lines: [
230
- { chords: "C G Am F", lyrics: "Where is my mind? Where is my mind?" },
231
- { chords: "C G Am F", lyrics: "Where is my mind? Way out in the water, see it swimming..." }
232
- ]},
233
- { type: "Verse 2", lines: [
234
- { chords: "C G Am F", lyrics: "I was thinking about you and the things we've done..." },
235
- { chords: "C G Am F", lyrics: "And all the places we've been to, oh yeah..." }
236
- ]},
237
- { type: "Chorus 2", lines: [
238
- { chords: "C G Am F", lyrics: "Where is my mind? Where is my mind?" },
239
- { chords: "C G Am F", lyrics: "Where is my mind? Way out in the water, see it swimming..." }
240
- ]},
241
- { type: "Outro", lines: [{ chords: "C G Am F", lyrics: "(repeat and fade)" }] }
242
- ]
243
- },
244
- {
245
- title: "Fisherman's Blues",
246
- artist: "The Waterboys",
247
- sections: [
248
- { type: "Intro", lines: [{ chords: "G C D G", lyrics: "" }] },
249
- { type: "Verse 1", lines: [
250
- { chords: "G C D G", lyrics: "I wish I was a fisherman, tumbling on the sea" },
251
- { chords: "G C D G", lyrics: "Far away from dry land, and its bitter misery" }
252
- ]},
253
- { type: "Chorus 1", lines: [
254
- { chords: "G C D G", lyrics: "I'm gonna make a record, a record of my dreams" },
255
- { chords: "G C D G", lyrics: "And let the wind and the waves sing along to the themes" }
256
- ]},
257
- { type: "Verse 2", lines: [
258
- { chords: "G C D G", lyrics: "I wish I was a fisherman, out on the rolling deep" },
259
- { chords: "G C D G", lyrics: "With nothing but the stars to guide me, while the city sleeps" }
260
- ]},
261
- { type: "Chorus 2", lines: [
262
- { chords: "G C D G", lyrics: "I'm gonna make a record, a record of my dreams" },
263
- { chords: "G C D G", lyrics: "And let the wind and the waves sing along to the themes" }
264
- ]},
265
- { type: "Outro", lines: [{ chords: "G C D G", lyrics: "(repeat and fade)" }] }
266
- ]
267
- },
268
- {
269
- title: "Express Yourself",
270
- artist: "N.W.A.",
271
- sections: [
272
- { type: "Intro", lines: [{ chords: "F Am Dm C", lyrics: "" }] },
273
- { type: "Verse 1", lines: [
274
- { chords: "F Am Dm C", lyrics: "I'm expressing with my full capabilities, and now I'm living in reality..." },
275
- { chords: "F Am Dm C", lyrics: "The only solution is to get involved and move it..." }
276
- ]},
277
- { type: "Chorus 1", lines: [
278
- { chords: "F Am Dm C", lyrics: "Express yourself! Express yourself!" },
279
- { chords: "F Am Dm C", lyrics: "Express yourself! It's a brand new thing..." }
280
- ]},
281
- { type: "Verse 2", lines: [
282
- { chords: "F Am Dm C", lyrics: "Now I'm the one, I'm the one, I'm the one that you know..." },
283
- { chords: "F Am Dm C", lyrics: "Coming to get you, coming to get you, coming to get you, watch me go..." }
284
- ]},
285
- { type: "Chorus 2", lines: [
286
- { chords: "F Am Dm C", lyrics: "Express yourself! Express yourself!" },
287
- { chords: "F Am Dm C", lyrics: "Express yourself! It's a brand new thing..." }
288
- ]},
289
- { type: "Outro", lines: [{ chords: "F Am Dm C", lyrics: "(repeat and fade)" }] }
290
- ]
291
- },
292
- {
293
- title: "One",
294
- artist: "Metallica",
295
- sections: [
296
- { type: "Intro", lines: [{ chords: "Am G C F", lyrics: "(Acoustic Intro/Verse Part)" }] },
297
- { type: "Verse 1", lines: [
298
- { chords: "Am G C F", lyrics: "I can't remember anything, can't tell if this is true or dream..." },
299
- { chords: "Am G C F", lyrics: "Deep down inside I feel the scream..." }
300
- ]},
301
- { type: "Chorus 1", lines: [
302
- { chords: "Am G C F", lyrics: "Hold my breath as I wish for death..." }
303
- ]},
304
- { type: "Verse 2", lines: [
305
- { chords: "Am G C F", lyrics: "Life it seems will fade away, drifting further every day..." },
306
- { chords: "Am G C F", lyrics: "Getting lost within myself, nothing matters, no one else..." }
307
- ]},
308
- { type: "Chorus 2", lines: [
309
- { chords: "Am G C F", lyrics: "All the thoughts that I have now..." }
310
- ]},
311
- { type: "Outro", lines: [{ chords: "E5 - D5 - C5 - A5", lyrics: "(heavy riffing, fast tempo, ends on E5)" }] }
312
- ]
313
- },
314
- {
315
- title: "Handle with Care",
316
- artist: "Traveling Wilburys",
317
- sections: [
318
- { type: "Intro", lines: [{ chords: "G D Em C", lyrics: "" }] },
319
- { type: "Verse 1", lines: [
320
- { chords: "G D Em C", lyrics: "Been beat up and battered 'round, been sent up, and I've been shot down..." },
321
- { chords: "G D Em C", lyrics: "You're the best thing that I've found, handle me with care." }
322
- ]},
323
- { type: "Chorus 1", lines: [
324
- { chords: "G D Em C", lyrics: "Handle me with care, handle me with care" },
325
- { chords: "G D Em C", lyrics: "Handle me with care, handle me with care" }
326
- ]},
327
- { type: "Verse 2", lines: [
328
- { chords: "G D Em C", lyrics: "I been stuck in so much traffic, I'm a mess, a nervous wreck..." },
329
- { chords: "G D Em C", lyrics: "I could use some tender love and care, handle me with care." }
330
- ]},
331
- { type: "Chorus 2", lines: [
332
- { chords: "G D Em C", lyrics: "Handle me with care, handle me with care" },
333
- { chords: "G D Em C", lyrics: "Handle me with care, handle me with care" }
334
- ]},
335
- { type: "Outro", lines: [{ chords: "G D Em C", lyrics: "(repeat and fade)" }] }
336
- ]
337
- }
338
- ];
339
-
340
- // --- Global State Variables ---
341
- let currentSongIndex = 0;
342
- let currentTempo = 90; // Default to Medium
343
- let isInteractiveMode = false;
344
- let activeSectionIndex = 0;
345
- let activeLineIndexInSection = 0;
346
- let activeChordIndexInLine = 0;
347
- let activeWordIndexInLine = 0;
348
- let arpeggioDirection = 'rising'; // 'rising' or 'falling'
349
-
350
- // --- DOM Elements ---
351
- const songTitleEl = document.getElementById('songTitle');
352
- const artistNameEl = document.getElementById('artistName');
353
- const scrollContainerEl = document.getElementById('scrollContainer');
354
- const prevSongBtnHeader = document.getElementById('prevSongBtnHeader');
355
- const nextSongBtnHeader = document.getElementById('nextSongBtnHeader');
356
- const slowTempoBtn = document.getElementById('slowTempoBtn');
357
- const mediumTempoBtn = document.getElementById('mediumTempoBtn');
358
- const fastTempoBtn = document.getElementById('fastTempoBtn');
359
- const arpeggioDirectionBtn = document.getElementById('arpeggioDirectionBtn');
360
- const startTeleprompterBtn = document.getElementById('startTeleprompterBtn');
361
-
362
- // --- Tone.js Synth Initialization ---
363
- let synth = null;
364
- async function initializeSynth() {
365
- if (!synth) {
366
- synth = new Tone.PolySynth(Tone.Synth, {
367
- envelope: {
368
- attack: 0.02,
369
- decay: 0.1,
370
- sustain: 0.3,
371
- release: 1
372
- }
373
- }).toDestination();
374
- await Tone.start(); // Ensure audio context is running
375
- console.log('Tone.js audio context started and synth initialized.');
376
- }
377
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
 
379
- // --- Tempo Presets ---
380
- const tempos = {
381
- slow: 30,
382
- medium: 90,
383
- fast: 128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  };
 
 
 
 
 
 
 
 
385
 
386
- // --- Helper: Chord to MIDI Note Mapping ---
387
- const chordToMidi = (chordName) => {
388
- const rootMap = {
389
- 'C': 60, 'C#': 61, 'Db': 61, 'D': 62, 'D#': 63, 'Eb': 63, 'E': 64, 'F': 65,
390
- 'F#': 66, 'Gb': 66, 'G': 67, 'G#': 68, 'Ab': 68, 'A': 69, 'A#': 70, 'Bb': 70, 'B': 71
391
- };
392
-
393
- let root = null;
394
- let type = 'major'; // Default to major
395
- let octaveOffset = 0; // Default to 4th octave for root
396
-
397
- let baseChord = chordName.trim().replace('5', ''); // Handle power chords as root
398
- const match = baseChord.match(/^([A-G][b#]?)/);
399
- if (match) {
400
- root = rootMap[match[1]];
401
- baseChord = baseChord.substring(match[1].length); // Remove root for type parsing
402
- } else {
403
- return []; // Fallback for unparseable roots
404
- }
405
 
406
- // Determine chord type (simple major/minor/power for now)
407
- if (baseChord.includes('m') || baseChord.includes('min')) {
408
- type = 'minor';
409
- } else if (baseChord.includes('dim')) {
410
- type = 'diminished';
411
- } else if (chordName.includes('5')) { // Explicit power chord check using original chordName
412
- type = 'power';
 
413
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
414
 
415
- if (root === null) return [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
 
417
- const notes = [root + octaveOffset]; // Root
418
- if (type === 'major') {
419
- notes.push(root + 4 + octaveOffset); // Major 3rd
420
- } else if (type === 'minor') {
421
- notes.push(root + 3 + octaveOffset); // Minor 3rd
422
- } else if (type === 'diminished') {
423
- notes.push(root + 3 + octaveOffset); // Minor 3rd
 
 
 
 
 
424
  }
425
- notes.push(root + 7 + octaveOffset); // Perfect 5th
 
 
426
 
427
- // Add the root an octave higher for a fuller sound in the arpeggio
428
- notes.push(root + 12 + octaveOffset);
 
 
429
 
430
- return notes;
431
- };
432
 
433
- // --- Helper: Play Arpeggio ---
434
- async function playArpeggio(chordName, direction) {
435
- await initializeSynth(); // Ensure synth is ready
436
 
437
- Tone.Transport.stop();
438
- Tone.Transport.cancel(); // Clear any existing schedules
 
 
 
 
 
 
 
 
 
 
 
 
 
439
 
440
- const arpeggioNotes = chordToMidi(chordName);
441
- if (arpeggioNotes.length === 0) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
 
443
- const notesToPlay = direction === 'rising' ? arpeggioNotes : [...arpeggioNotes].reverse();
 
 
 
 
 
 
 
 
 
 
444
 
445
- const noteDuration = Tone.Time("8n").toSeconds(); // Each note in arpeggio is an 8th note
446
- let startTime = Tone.Transport.now();
 
 
 
 
 
 
 
447
 
448
- notesToPlay.forEach((midiNote, index) => {
449
- synth.triggerAttackRelease(
450
- Tone.Midi(midiNote).toNote(),
451
- "16n", // Shorter attack for arpeggio notes
452
- startTime + (index * noteDuration * 0.5) // Stagger notes
453
- );
454
- });
455
 
456
- Tone.Transport.start(); // Start transport for this one-shot sequence
457
- // Stop transport after a short delay, to ensure arpeggio finishes
458
- Tone.Transport.scheduleOnce((time) => {
459
- Tone.Transport.stop();
460
- Tone.Transport.cancel();
461
- }, `+${noteDuration * notesToPlay.length}`);
462
- }
463
-
464
- // --- Rendering Function ---
465
- function renderSong() {
466
- const song = songsData[currentSongIndex];
467
- songTitleEl.textContent = song.title;
468
- artistNameEl.textContent = song.artist;
469
- scrollContainerEl.innerHTML = ''; // Clear previous content
470
-
471
- song.sections.forEach((section, secIndex) => {
472
- const sectionDiv = document.createElement('div');
473
- sectionDiv.className = 'mb-8';
474
-
475
- const sectionTitle = document.createElement('h2');
476
- sectionTitle.className = 'text-3xl font-semibold text-yellow-300 mb-4 sticky top-0 bg-gray-900 py-2 z-10';
477
- sectionTitle.textContent = section.type;
478
- sectionDiv.appendChild(sectionTitle);
479
-
480
- section.lines.forEach((line, lineIndex) => {
481
- const lineDiv = document.createElement('div');
482
- lineDiv.className = `mb-4`;
483
- lineDiv.dataset.sectionIndex = secIndex;
484
- lineDiv.dataset.lineIndex = lineIndex;
485
-
486
- const chordsP = document.createElement('p');
487
- chordsP.className = 'font-bold text-green-300 whitespace-pre';
488
- const chordsInLine = line.chords.split(/\s+/).filter(c => c.length > 0);
489
- chordsInLine.forEach((chord, chordMapIndex) => {
490
- const chordSpan = document.createElement('span');
491
- chordSpan.textContent = chord;
492
- // Add spaces for visual alignment
493
- chordSpan.innerHTML += '&nbsp;&nbsp;'; // Use innerHTML for non-breaking space
494
- chordSpan.dataset.chordIndex = chordMapIndex;
495
- chordsP.appendChild(chordSpan);
496
- });
497
- lineDiv.appendChild(chordsP);
498
-
499
- const lyricsP = document.createElement('p');
500
- lyricsP.className = 'text-gray-100';
501
- const wordsInLine = line.lyrics.split(/\s+/).filter(w => w.length > 0);
502
- wordsInLine.forEach((word, wordMapIndex) => {
503
- const wordSpan = document.createElement('span');
504
- wordSpan.textContent = word;
505
- wordSpan.innerHTML += '&nbsp;'; // Add space between words
506
- wordSpan.dataset.wordIndex = wordMapIndex;
507
- lyricsP.appendChild(wordSpan);
508
- });
509
- lineDiv.appendChild(lyricsP);
510
-
511
- sectionDiv.appendChild(lineDiv);
512
- });
513
- scrollContainerEl.appendChild(sectionDiv);
514
- });
515
- updateHighlighting(); // Initial highlighting
516
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
- // --- Highlighting Logic ---
519
- function updateHighlighting() {
520
- // Clear all existing highlights
521
- document.querySelectorAll('.text-red-400').forEach(el => el.classList.remove('text-red-400', 'transition-colors', 'duration-200'));
522
- document.querySelectorAll('.text-blue-300.font-extrabold').forEach(el => el.classList.remove('text-blue-300', 'font-extrabold', 'transition-colors', 'duration-200'));
523
- document.querySelectorAll('.bg-gray-800.rounded-md.p-2').forEach(el => el.classList.remove('bg-gray-800', 'rounded-md', 'p-2'));
 
524
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
- if (isInteractiveMode) {
527
- const activeLineDiv = scrollContainerEl.querySelector(
528
- `[data-section-index="${activeSectionIndex}"][data-line-index="${activeLineIndexInSection}"]`
529
- );
530
- if (activeLineDiv) {
531
- activeLineDiv.classList.add('bg-gray-800', 'rounded-md', 'p-2');
 
 
 
 
 
 
 
 
 
 
 
 
532
 
533
- const activeChordSpan = activeLineDiv.querySelector(`p.text-green-300 span[data-chord-index="${activeChordIndexInLine}"]`);
534
- if (activeChordSpan) {
535
- activeChordSpan.classList.add('text-red-400', 'transition-colors', 'duration-200');
 
 
 
 
 
536
  }
 
537
 
538
- const activeWordSpan = activeLineDiv.querySelector(`p.text-gray-100 span[data-word-index="${activeWordIndexInLine}"]`);
539
- if (activeWordSpan) {
540
- activeWordSpan.classList.add('text-blue-300', 'font-extrabold', 'transition-colors', 'duration-200');
541
- }
 
542
 
543
- // Auto-scroll the active line into view if it's out of bounds
544
- const containerHeight = scrollContainerEl.clientHeight;
545
- const lineTop = activeLineDiv.offsetTop;
546
- const lineBottom = lineTop + activeLineDiv.clientHeight;
547
 
548
- if (lineTop < scrollContainerEl.scrollTop || lineBottom > scrollContainerEl.scrollTop + containerHeight) {
549
- scrollContainerEl.scrollTop = lineTop - (containerHeight / 3); // Scroll to about a third down the screen
550
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
  }
552
  }
553
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
 
555
- // --- Core KeyPress Logic (Teleprompter Advance) ---
556
- function handleKeyPress(event) {
557
- if (!isInteractiveMode) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
 
559
- if (event.code === 'Space' || event.code === 'ArrowRight') {
560
- event.preventDefault(); // Prevent page scrolling
561
 
562
- const currentSong = songsData[currentSongIndex];
563
- const currentSection = currentSong.sections[activeSectionIndex];
564
- const currentLine = currentSection?.lines[activeLineIndexInSection];
565
- const chordsInCurrentLine = currentLine?.chords.split(/\s+/).filter(c => c.length > 0) || [];
566
- const wordsInCurrentLine = currentLine?.lyrics.split(/\s+/).filter(w => w.length > 0) || [];
 
 
 
 
 
 
 
 
 
 
567
 
568
- // Play arpeggio for the current chord before advancing
569
- const chordToPlay = chordsInCurrentLine[activeChordIndexInLine];
570
- if (chordToPlay) {
571
- playArpeggio(chordToPlay, arpeggioDirection);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
 
574
- let newChordIndex = activeChordIndexInLine + 1;
575
- let newWordIndex = activeWordIndexInLine + 1;
576
- let newActiveLineIndex = activeLineIndexInSection;
577
- let newActiveSectionIndex = activeSectionIndex;
578
-
579
- const allWordsCovered = newWordIndex >= wordsInCurrentLine.length;
580
- const allChordsCovered = newChordIndex >= chordsInCurrentLine.length;
581
-
582
- if (allWordsCovered && allChordsCovered) {
583
- // Both words and chords on the current line are covered, move to next line
584
- newActiveLineIndex++;
585
- newChordIndex = 0;
586
- newWordIndex = 0;
587
-
588
- if (newActiveLineIndex >= currentSection.lines.length) {
589
- // All lines in current section covered, move to next section
590
- newActiveSectionIndex++;
591
- newActiveLineIndex = 0; // Reset line index for new section
592
-
593
- if (newActiveSectionIndex >= currentSong.sections.length) {
594
- // End of song
595
- console.log("End of song!");
596
- isInteractiveMode = false; // Exit interactive mode
597
- activeSectionIndex = 0;
598
- activeLineIndexInSection = 0;
599
- activeChordIndexInLine = 0;
600
- activeWordIndexInLine = 0;
601
- Tone.Transport.stop();
602
- Tone.Transport.cancel();
603
- updateHighlighting(); // Clear final highlights
604
- return;
605
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
  }
607
- } else if (newChordIndex >= chordsInCurrentLine.length && !allWordsCovered) {
608
- // All chords on line covered, but words remain. Advance words only.
609
- // Keep chord index at the last chord.
610
- newChordIndex = chordsInCurrentLine.length > 0 ? chordsInCurrentLine.length - 1 : 0;
611
- } else if (newWordIndex >= wordsInCurrentLine.length && !allChordsCovered) {
612
- // All words on line covered, but chords remain. Advance chords only.
613
- // Keep word index at the last word.
614
- newWordIndex = wordsInCurrentLine.length > 0 ? wordsInCurrentLine.length - 1 : 0;
615
  }
 
 
616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
 
618
- activeChordIndexInLine = newChordIndex;
619
- activeWordIndexInLine = newWordIndex;
620
- activeLineIndexInSection = newActiveLineIndex;
621
- activeSectionIndex = newActiveSectionIndex;
622
-
623
- updateHighlighting();
624
  }
625
  }
 
 
626
 
627
- // --- Event Handlers ---
628
- function handleSongChange(direction) {
629
- isInteractiveMode = false; // Exit interactive mode on song change
630
- Tone.Transport.stop();
631
- Tone.Transport.cancel();
632
 
633
- if (direction === 'next') {
634
- currentSongIndex = (currentSongIndex + 1) % songsData.length;
635
- } else if (direction === 'prev') {
636
- currentSongIndex = (currentSongIndex - 1 + songsData.length) % songsData.length;
 
 
637
  }
638
-
639
- // Reset teleprompter state for the new song
640
- activeSectionIndex = 0;
641
- activeLineIndexInSection = 0;
642
- activeChordIndexInLine = 0;
643
- activeWordIndexInLine = 0;
644
- scrollContainerEl.scrollTop = 0; // Scroll to top
645
-
646
- renderSong(); // Re-render the new song
647
- }
648
-
649
- function setTempo(tempoValue) {
650
- currentTempo = tempoValue;
651
- Tone.Transport.bpm.value = tempoValue;
652
- // Update button styles
653
- slowTempoBtn.classList.remove('bg-purple-700');
654
- mediumTempoBtn.classList.remove('bg-purple-700');
655
- fastTempoBtn.classList.remove('bg-purple-700');
656
- slowTempoBtn.classList.add('bg-purple-500', 'hover:bg-purple-600');
657
- mediumTempoBtn.classList.add('bg-purple-500', 'hover:bg-purple-600');
658
- fastTempoBtn.classList.add('bg-purple-500', 'hover:bg-purple-600');
659
-
660
- if (tempoValue === tempos.slow) slowTempoBtn.classList.replace('bg-purple-500', 'bg-purple-700');
661
- else if (tempoValue === tempos.medium) mediumTempoBtn.classList.replace('bg-purple-500', 'bg-purple-700');
662
- else if (tempoValue === tempos.fast) fastTempoBtn.classList.replace('bg-purple-500', 'bg-purple-700');
663
- }
664
-
665
- function toggleArpeggioDirection() {
666
- arpeggioDirection = arpeggioDirection === 'rising' ? 'falling' : 'rising';
667
- arpeggioDirectionBtn.textContent = `Arpeggio: ${arpeggioDirection.charAt(0).toUpperCase() + arpeggioDirection.slice(1)}`;
668
- }
669
-
670
- function startTeleprompter() {
671
- isInteractiveMode = true;
672
- activeSectionIndex = 0;
673
- activeLineIndexInSection = 0;
674
- activeChordIndexInLine = 0;
675
- activeWordIndexInLine = 0;
676
- scrollContainerEl.scrollTop = 0; // Scroll to top on start
677
- initializeSynth(); // Ensure synth is ready
678
- Tone.Transport.stop(); // Stop any previous playback
679
- Tone.Transport.cancel();
680
- Tone.Transport.bpm.value = currentTempo; // Set tempo for interactive playback
681
- updateHighlighting(); // Apply initial highlight
682
- }
683
-
684
- // --- Initial Setup and Event Listeners ---
685
- document.addEventListener('DOMContentLoaded', () => {
686
- renderSong(); // Render the first song on load
687
- setTempo(tempos.medium); // Set initial tempo button state
688
-
689
- // Attach event listeners
690
- prevSongBtnHeader.addEventListener('click', () => handleSongChange('prev'));
691
- nextSongBtnHeader.addEventListener('click', () => handleSongChange('next'));
692
- slowTempoBtn.addEventListener('click', () => setTempo(tempos.slow));
693
- mediumTempoBtn.addEventListener('click', () => setTempo(tempos.medium));
694
- fastTempoBtn.addEventListener('click', () => setTempo(tempos.fast));
695
- arpeggioDirectionBtn.addEventListener('click', toggleArpeggioDirection);
696
- startTeleprompterBtn.addEventListener('click', startTeleprompter);
697
-
698
- window.addEventListener('keydown', handleKeyPress);
699
  });
 
 
 
700
  </script>
701
  </body>
702
  </html>
 
1
  <!DOCTYPE html>
2
  <html lang="en">
3
  <head>
4
+ <!-- Chosen Palette: Retro Arcade (Deep Blue, Neon Green, Red, Yellow, White, Gold) -->
5
+ <!-- Application Structure Plan: A single-page application with a clear state-driven flow: MENU -> DEMO -> PLAYING -> PAUSED -> GAME_OVER -> HIGH_SCORE_ENTRY -> HIGH_SCORES. This structure ensures a focused, arcade-like experience. UI overlays manage menu, pause, game over, and high score interactions. Two-player mode is managed through alternating turns on life loss. The user flow is linear through game states, with high scores being an end-game display. -->
6
+ <!-- Visualization & Content Choices:
7
+ - Player/Enemy Ships: Report Info -> Player and Enemy models. Goal -> Represent game agents with more visual variety. Viz/Method -> 3D compound objects (THREE.Group) with more detailed geometries (e.g., Cylinders, Spheres, Cones, Boxes combined). Interaction -> Player control, AI movement, collision. Justification -> Enhances visual fidelity and differentiation. Library/Method -> Three.js.
8
+ - Formations/Waves/Armada: Report Info -> Enemy formations, attack waves, and an armada. Goal -> Create structured challenges with escalating difficulty. Viz/Method -> Positional data within JS objects driving enemy AI, complex formation logic for armada. Interaction -> Player must defeat waves to progress. Justification -> Central to Galaga's gameplay, armada adds unique challenge. Library/Method -> JavaScript logic.
9
+ - Tractor Beam: Report Info -> Boss Galaga capture mechanic. Goal -> Introduce risk/reward for dual fighter. Viz/Method -> Animated, transparent THREE.Mesh (Cone). Interaction -> Captures player, enabling dual-fighter retrieval. Justification -> Iconic and requested feature. Library/Method -> Three.js.
10
+ - Starfield Complexity: Report Info -> Dynamic background with more variation. Goal -> Simulate forward motion and enhance immersion. Viz/Method -> Multiple THREE.Points groups with varying sizes, colors, and speeds. Interaction -> None (ambient). Justification -> Visually richer background. Library/Method -> Three.js.
11
+ - HUD (Score/Lives/Wave): Report Info -> UI requirements. Goal -> Provide critical game state info for both players. Viz/Method -> HTML overlays with Tailwind CSS. Interaction -> Read-only. Justification -> Standard, non-intrusive method for displaying game data. Library/Method -> HTML/CSS.
12
+ - High Score Board: Report Info -> Persistent high score. Goal -> Provide a sense of progression and competition. Viz/Method -> HTML overlay with form for initials, dynamically updated list. Interaction -> User input for initials, display only. Justification -> Standard arcade feature. Library/Method -> JavaScript (localStorage for persistence).
13
+ - Auto Shield: Report Info -> Easier auto-shield. Goal -> Provide a brief period of invincibility after being hit. Viz/Method -> Player ship flashing, temporary state variable. Interaction -> Automatic on hit. Justification -> Improves player survivability and reduces frustration. Library/Method -> JavaScript logic.
14
+ - Heat-Seeking Missiles: Report Info -> Player missiles home-in. Goal -> Increase player's hit rate. Viz/Method -> Player projectile velocity adjustment towards nearest enemy. Interaction -> Automatic. Justification -> Enhances player experience, makes game feel more forgiving. Library/Method -> JavaScript logic.
15
+ - Shot Power-Up: Report Info -> Blue capsules for more missiles. Goal -> Reward player, add progression. Viz/Method -> Small 3D cylinder/capsule, moves towards player. Interaction -> Collectible to increase missile output. Justification -> Adds depth to power-up system. Library/Method -> Three.js (for model), JavaScript logic.
16
+ - Multi-Fighter Fleet: Report Info -> Acquire more ships. Goal -> Enhance offensive capabilities, visual progression. Viz/Method -> Multiple player ship models grouped under one main control. Interaction -> Dynamic visual arrangement. Justification -> Core Galaga '88 mechanic. Library/Method -> Three.js (for grouping), JavaScript logic.
17
+ - Sound Effects: Report Info -> Game audio. Goal -> Enhance immersion and provide feedback. Viz/Method -> Tone.js for music and sound effects. Interaction -> Automatic playback based on game events. Justification -> Crucial for arcade feel. Library/Method -> Tone.js.
18
+ - Mouse Control: Report Info -> Additional input. Goal -> Provide alternative control method. Viz/Method -> Mouse position mapping to ship X-coordinate. Interaction -> Direct player control. Justification -> Improves accessibility for different input preferences. Library/Method -> JavaScript DOM events.
19
+ -->
20
+ <!-- CONFIRMATION: NO SVG graphics used. NO Mermaid JS used. -->
21
  <meta charset="UTF-8">
22
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
23
+ <title>Galaga '88 3D</title>
 
24
  <script src="https://cdn.tailwindcss.com"></script>
25
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
26
+ <script src="https://unpkg.com/tone@14.7.77/build/Tone.js"></script>
27
  <style>
28
+ body { margin: 0; overflow: hidden; background-color: #000; font-family: 'Courier New', Courier, monospace; }
29
+ canvas { display: block; }
30
+ .hud-element { position: absolute; color: #ffffff; text-shadow: 2px 2px 4px #00ff00; }
31
+ .overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.7); z-index: 1000; }
32
+ .overlay-box { background-color: rgba(0, 15, 30, 0.8); border: 2px solid #00ff00; padding: 2rem 4rem; text-align: center; border-radius: 0.5rem;}
33
+ .overlay-title { font-size: 3rem; color: #ffff00; text-shadow: 2px 2px 6px #ff0000; margin-bottom: 1rem; }
34
+ .overlay-text { font-size: 1.2rem; color: #ffffff; margin-bottom: 2rem; }
35
+ .overlay-button { background-color: #ffff00; color: #000000; border: none; padding: 1rem 2rem; font-size: 1.5rem; cursor: pointer; transition: all 0.2s; border-radius: 0.3rem;}
36
+ .overlay-button:hover { background-color: #ffffff; color: #000000; transform: scale(1.05); }
37
+ .touch-controls { position: absolute; bottom: 0; width: 100%; height: 120px; display: flex; justify-content: space-between; align-items: center; z-index: 100; padding: 0 20px; }
38
+ .touch-button { width: 80px; height: 80px; border: 2px solid #00ff00; border-radius: 50%; display: flex; justify-content: center; align-items: center; color: #00ff00; font-size: 2rem; user-select: none; }
39
+ .touch-button.fire { width: 100px; height: 100px; color: #ffff00; border-color: #ffff00; }
40
+
41
+ #high-score-form input {
42
+ background-color: #333;
43
+ border: 1px solid #0f0;
44
+ color: #fff;
45
+ padding: 0.5rem;
46
+ margin-top: 1rem;
47
+ text-align: center;
48
+ text-transform: uppercase;
49
+ font-size: 1.5rem;
50
+ width: 8rem;
51
  }
52
+ #high-scores-list {
53
+ list-style: none;
54
+ padding: 0;
55
+ margin: 1rem 0;
56
+ font-size: 1.2rem;
57
+ color: #fff;
58
  }
59
+ #high-scores-list li {
60
+ padding: 0.2rem 0;
61
+ display: flex;
62
+ justify-content: space-between;
63
  }
64
+ #high-scores-list li span:first-child {
65
+ color: #ffff00;
66
  }
67
+ #high-scores-list li span:last-child {
68
+ color: #00ff00;
 
69
  }
70
  </style>
71
  </head>
72
+ <body>
73
+ <div id="score-p1-display" class="hud-element top-4 left-4 text-2xl">P1 SCORE: 0</div>
74
+ <div id="score-p2-display" class="hud-element top-4 left-4 ml-48 text-2xl" style="display: none;">P2 SCORE: 0</div>
75
+ <div id="high-score-current-display" class="hud-element top-4 left-1/2 -translate-x-1/2 text-2xl text-yellow-400">HIGH SCORE: 0</div>
76
+ <div id="current-player-display" class="hud-element bottom-4 right-4 text-2xl text-yellow-400">P1 TURN</div>
77
+ <div id="wave-display" class="hud-element top-4 right-4 text-2xl">WAVE: 1</div>
78
+ <div id="lives-display" class="hud-element bottom-4 left-4 text-2xl flex items-center gap-2">LIVES: </div>
79
+
80
+ <div id="menu-overlay" class="overlay">
81
+ <div class="overlay-box">
82
+ <h1 class="overlay-title">GALAGA '88 3D</h1>
83
+ <p class="overlay-text">Use [A]/[D] or [←]/[→] to move. [SPACE] to fire.<br>
84
+ [P] to Pause. Collect captured ships for Double Fighter!</p>
85
+ <div class="mb-4">
86
+ <button id="start-1player-button" class="overlay-button mr-4">1 PLAYER</button>
87
+ <button id="start-2player-button" class="overlay-button">2 PLAYERS</button>
88
  </div>
89
+ <button id="view-high-scores-button" class="overlay-button !bg-gray-700 !text-white !border !border-white mt-4">HIGH SCORES</button>
90
+ </div>
91
+ </div>
92
+ <div id="pause-overlay" class="overlay" style="display: none;">
93
+ <div class="overlay-box">
94
+ <h1 class="overlay-title">PAUSED</h1>
95
+ <button id="resume-button" class="overlay-button">RESUME</button>
96
+ </div>
97
+ </div>
98
+ <div id="game-over-overlay" class="overlay" style="display: none;">
99
+ <div class="overlay-box">
100
+ <h1 class="overlay-title">GAME OVER</h1>
101
+ <p id="final-score" class="overlay-text text-2xl"></p>
102
+ <form id="high-score-form" class="hidden">
103
+ <p class="text-white text-lg">Enter Initials (3 letters):</p>
104
+ <input type="text" id="initials-input" maxlength="3" pattern="[A-Z]{3}" class="uppercase" required>
105
+ <button type="submit" class="overlay-button mt-4">SAVE SCORE</button>
106
+ </form>
107
+ <button id="restart-button" class="overlay-button mt-4">PLAY AGAIN</button>
108
  </div>
109
+ </div>
110
+ <div id="high-scores-overlay" class="overlay" style="display: none;">
111
+ <div class="overlay-box">
112
+ <h1 class="overlay-title">HIGH SCORES</h1>
113
+ <ul id="high-scores-list"></ul>
114
+ <button id="back-to-menu-button" class="overlay-button mt-4">BACK TO MENU</button>
115
+ </div>
116
+ </div>
117
+
118
+ <div class="touch-controls">
119
+ <div id="left-touch" class="touch-button"><span>&#x2190;</span></div>
120
+ <div id="fire-touch" class="touch-button fire"><span>&#x25CE;</span></div>
121
+ <div id="right-touch" class="touch-button"><span>&#x2192;</span></div>
122
+ </div>
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  <script>
125
+ const GAME = {
126
+ state: 'MENU', // MENU, DEMO, PLAYING, PAUSED, GAME_OVER, HIGH_SCORE_ENTRY, HIGH_SCORES
127
+ players: {
128
+ p1: { score: 0, lives: 5, fighterCount: 1, missileCount: 1 },
129
+ p2: { score: 0, lives: 5, fighterCount: 1, missileCount: 1 }
130
+ },
131
+ currentPlayer: 'p1',
132
+ numPlayers: 1, // 1 or 2
133
+ playerFleet: [], // Array to hold individual player ship meshes
134
+ playerShipGroup: null, // The main THREE.Group that contains all active player ships
135
+ enemies: [],
136
+ playerProjectiles: [],
137
+ enemyProjectiles: [],
138
+ explosions: [],
139
+ powerUps: [], // New array for power-up capsules
140
+ stars: [],
141
+ scene: null,
142
+ camera: null,
143
+ renderer: null,
144
+ clock: new THREE.Clock(),
145
+ input: { left: false, right: false },
146
+ canShoot: true,
147
+ shootCooldown: 250,
148
+ playerBoundaryX: 20,
149
+ capturedShip: null,
150
+ wave: 1,
151
+ waveData: [
152
+ { grunts: 8, chargers: 0, bosses: 0, type: 'standard' },
153
+ { grunts: 10, chargers: 2, bosses: 0, type: 'standard' },
154
+ { grunts: 6, chargers: 4, bosses: 1, type: 'standard' },
155
+ { grunts: 0, chargers: 10, bosses: 2, type: 'standard' },
156
+ { grunts: 20, chargers: 0, bosses: 0, type: 'armada' }, // Armada wave
157
+ { grunts: 15, chargers: 8, bosses: 2, type: 'standard' },
158
+ ],
159
+ currentWaveEnemiesSpawned: 0,
160
+ currentWaveTotalEnemies: 0,
161
+ invincible: false,
162
+ invincibilityDuration: 3000, // 3 seconds
163
+ highScores: JSON.parse(localStorage.getItem('galagaHighScores')) || [],
164
+ powerUpDropChance: 0.1, // 10% chance for power-up to drop
165
+ audioContextReady: false,
166
+ music: {
167
+ demo: null,
168
+ highScore: null
169
+ },
170
+ sfx: {
171
+ playerShoot: null,
172
+ enemyShoot: null,
173
+ explosion: null,
174
+ powerUp: null,
175
+ playerHit: null,
176
+ captureBeam: null,
177
+ gameStart: null,
178
+ gameOver: null
179
+ },
180
+ demoTimer: 0,
181
+ demoInterval: 10000, // 10 seconds for demo loop
182
+ musicAlternationTimer: 0,
183
+ musicAlternationInterval: 5000 // Alternate music every 5 seconds
184
+ };
185
+
186
+ function init() {
187
+ setupScene();
188
+ setupUI();
189
+ // Setup audio context on first user interaction, then load and configure sounds
190
+ window.addEventListener('resize', onWindowResize, false);
191
+ document.body.addEventListener('click', initAudioContext, { once: true });
192
+ animate();
193
+ }
194
+
195
+ function initAudioContext() {
196
+ if (!GAME.audioContextReady) {
197
+ Tone.start().then(() => {
198
+ GAME.audioContextReady = true;
199
+ loadAndConfigureSounds(); // Now call this here to ensure Tone.js is ready
200
+ startDemoLoop();
201
+ }).catch(e => console.error("Failed to start audio context:", e));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  }
203
+ }
204
+
205
+ function loadAndConfigureSounds() {
206
+ // Instantiate all synths and sequences
207
+ GAME.sfx.playerShoot = new Tone.PolySynth(Tone.Synth, {
208
+ oscillator: { type: "square" }
209
+ }).toDestination();
210
+ GAME.sfx.playerShoot.volume.value = -10;
211
+
212
+ GAME.sfx.enemyShoot = new Tone.PolySynth(Tone.Synth, {
213
+ oscillator: { type: "sawtooth" }
214
+ }).toDestination();
215
+ GAME.sfx.enemyShoot.volume.value = -15;
216
+
217
+ GAME.sfx.explosion = new Tone.NoiseSynth({
218
+ noise: { type: "white" },
219
+ envelope: { attack: 0.01, decay: 0.2, sustain: 0, release: 0.1 }
220
+ }).toDestination();
221
+ GAME.sfx.explosion.volume.value = -10;
222
+
223
+ GAME.sfx.powerUp = new Tone.PluckSynth().toDestination();
224
+ GAME.sfx.powerUp.volume.value = -5;
225
+
226
+ GAME.sfx.playerHit = new Tone.MembraneSynth().toDestination();
227
+ GAME.sfx.playerHit.volume.value = -5;
228
+
229
+ GAME.sfx.captureBeam = new Tone.AMSynth({
230
+ harmonicity: 0.5,
231
+ oscillator: { type: "sine" },
232
+ envelope: { attack: 0.1, decay: 0.2, sustain: 0.5, release: 0.5 },
233
+ modulation: { type: "square" },
234
+ modulationEnvelope: { attack: 0.2, decay: 0.5 }
235
+ }).toDestination();
236
+ GAME.sfx.captureBeam.volume.value = -10;
237
+
238
+ GAME.sfx.gameStart = new Tone.Synth().toDestination();
239
+ GAME.sfx.gameStart.volume.value = -5;
240
+
241
+ GAME.sfx.gameOver = new Tone.FMSynth().toDestination();
242
+ GAME.sfx.gameOver.volume.value = -5;
243
+
244
+ // Sequences are created here, but they trigger attacks on the already defined sfx synths.
245
+ GAME.music.demo = new Tone.Sequence((time, note) => {
246
+ if(GAME.sfx.playerShoot) GAME.sfx.playerShoot.triggerAttackRelease(note, "8n", time);
247
+ }, ["C4", "E4", "G4", "C5"]);
248
+ GAME.music.demo.loop = true;
249
+ GAME.music.demo.bpm.value = 120;
250
+ GAME.music.demo.volume.value = -15;
251
+
252
+ GAME.music.highScore = new Tone.Sequence((time, note) => {
253
+ if(GAME.sfx.enemyShoot) GAME.sfx.enemyShoot.triggerAttackRelease(note, "8n", time);
254
+ }, ["G3", "D4", "B3", "E4"]);
255
+ GAME.music.highScore.loop = true;
256
+ GAME.music.highScore.bpm.value = 100;
257
+ GAME.music.highScore.volume.value = -15;
258
+ }
259
+
260
+ function startDemoLoop() {
261
+ if (GAME.state === 'MENU' || GAME.state === 'HIGH_SCORES') {
262
+ if (GAME.music.demo) GAME.music.demo.start();
263
+ if (GAME.music.highScore) GAME.music.highScore.stop();
264
+ GAME.state = 'DEMO';
265
+ GAME.demoTimer = 0;
266
+ }
267
+ }
268
+
269
+ function stopAllMusic() {
270
+ if (GAME.music.demo && GAME.music.demo.state === 'started') GAME.music.demo.stop();
271
+ if (GAME.music.highScore && GAME.music.highScore.state === 'started') GAME.music.highScore.stop();
272
+ }
273
+
274
+ function setupScene() {
275
+ GAME.scene = new THREE.Scene();
276
+ GAME.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
277
+ GAME.camera.position.set(0, 10, 30);
278
+ GAME.camera.lookAt(0, 0, 0);
279
+
280
+ GAME.renderer = new THREE.WebGLRenderer({ antialias: true });
281
+ GAME.renderer.setSize(window.innerWidth, window.innerHeight);
282
+ document.body.appendChild(GAME.renderer.domElement);
283
+
284
+ const ambientLight = new THREE.AmbientLight(0x606060);
285
+ GAME.scene.add(ambientLight);
286
+ const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
287
+ dirLight.position.set(0, 1, 1);
288
+ GAME.scene.add(dirLight);
289
+
290
+ createStarfield();
291
+ createPlayerShipGroup();
292
+ }
293
+
294
+ function setupUI() {
295
+ document.getElementById('start-1player-button').addEventListener('click', () => { GAME.numPlayers = 1; startGame(); });
296
+ document.getElementById('start-2player-button').addEventListener('click', () => { GAME.numPlayers = 2; startGame(); });
297
+ document.getElementById('restart-button').addEventListener('click', startGame);
298
+ document.getElementById('resume-button').addEventListener('click', togglePause);
299
+ document.getElementById('view-high-scores-button').addEventListener('click', showHighScores);
300
+ document.getElementById('back-to-menu-button').addEventListener('click', showMenu);
301
+ document.getElementById('high-score-form').addEventListener('submit', handleHighScoreSubmit);
302
+
303
+ document.addEventListener('keydown', e => {
304
+ if (e.key === 'a' || e.key === 'ArrowLeft') GAME.input.left = true;
305
+ if (e.key === 'd' || e.key === 'ArrowRight') GAME.input.right = true;
306
+ if (e.key === ' ' && GAME.state === 'PLAYING') firePlayerProjectile();
307
+ if (e.key === 'p' && (GAME.state === 'PLAYING' || GAME.state === 'PAUSED')) togglePause();
308
+ });
309
+ document.addEventListener('keyup', e => {
310
+ if (e.key === 'a' || e.key === 'ArrowLeft') GAME.input.left = false;
311
+ if (e.key === 'd' || e.key === 'ArrowRight') GAME.input.right = false;
312
+ });
313
+
314
+ const leftBtn = document.getElementById('left-touch');
315
+ const rightBtn = document.getElementById('right-touch');
316
+ const fireBtn = document.getElementById('fire-touch');
317
+ leftBtn.addEventListener('touchstart', (e) => { e.preventDefault(); GAME.input.left = true; });
318
+ leftBtn.addEventListener('touchend', (e) => { e.preventDefault(); GAME.input.left = false; });
319
+ rightBtn.addEventListener('touchstart', (e) => { e.preventDefault(); GAME.input.right = true; });
320
+ rightBtn.addEventListener('touchend', (e) => { e.preventDefault(); GAME.input.right = false; });
321
+ fireBtn.addEventListener('touchstart', (e) => { e.preventDefault(); if (GAME.state === 'PLAYING') firePlayerProjectile(); });
322
+
323
+ GAME.renderer.domElement.addEventListener('mousemove', onMouseMove, false);
324
+
325
+ updateHUD();
326
+ }
327
+
328
+ function onMouseMove(event) {
329
+ if (GAME.state !== 'PLAYING' || !GAME.playerShipGroup) return;
330
+ const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
331
+ const vector = new THREE.Vector3(mouseX, 0, 0.5);
332
+ vector.unproject(GAME.camera);
333
+
334
+ const dir = vector.sub(GAME.camera.position).normalize();
335
+ const distance = (GAME.playerShipGroup.position.z - GAME.camera.position.z) / dir.z;
336
+ const pos = GAME.camera.position.clone().add(dir.multiplyScalar(distance));
337
+
338
+ GAME.playerShipGroup.position.x = Math.max(-GAME.playerBoundaryX, Math.min(GAME.playerBoundaryX, pos.x));
339
+ }
340
+
341
+ function showMenu() {
342
+ document.getElementById('menu-overlay').style.display = 'flex';
343
+ document.getElementById('high-scores-overlay').style.display = 'none';
344
+ GAME.state = 'MENU';
345
+ resetGameVisuals();
346
+ startDemoLoop();
347
+ }
348
 
349
+ function startGame() {
350
+ stopAllMusic();
351
+ if(GAME.audioContextReady && GAME.sfx.gameStart) GAME.sfx.gameStart.triggerAttackRelease("C5", "0.2");
352
+ resetGame();
353
+ GAME.state = 'PLAYING';
354
+ document.getElementById('menu-overlay').style.display = 'none';
355
+ document.getElementById('game-over-overlay').style.display = 'none';
356
+ document.getElementById('high-scores-overlay').style.display = 'none';
357
+ document.getElementById('score-p2-display').style.display = GAME.numPlayers === 2 ? 'block' : 'none';
358
+
359
+ startWave();
360
+ }
361
+
362
+ function resetGame() {
363
+ GAME.players.p1.score = 0;
364
+ GAME.players.p1.lives = 5;
365
+ GAME.players.p1.fighterCount = 1;
366
+ GAME.players.p1.missileCount = 1;
367
+
368
+ GAME.players.p2.score = 0;
369
+ GAME.players.p2.lives = 5;
370
+ GAME.players.p2.fighterCount = 1;
371
+ GAME.players.p2.missileCount = 1;
372
+
373
+ GAME.currentPlayer = 'p1';
374
+ GAME.wave = 1;
375
+
376
+ resetGameVisuals();
377
+
378
+ GAME.capturedShip = null;
379
+ GAME.invincible = false;
380
+ GAME.canShoot = true;
381
+
382
+ updateHUD();
383
+ }
384
+
385
+ function resetGameVisuals() {
386
+ if(GAME.playerShipGroup && GAME.playerShipGroup.parent) GAME.scene.remove(GAME.playerShipGroup);
387
+ GAME.playerFleet = [];
388
+ createPlayerShipGroup();
389
+
390
+ GAME.enemies.forEach(e => GAME.scene.remove(e.mesh));
391
+ GAME.playerProjectiles.forEach(p => GAME.scene.remove(p.mesh));
392
+ GAME.enemyProjectiles.forEach(p => GAME.scene.remove(p));
393
+ GAME.explosions.forEach(e => GAME.scene.remove(e));
394
+ GAME.powerUps.forEach(p => GAME.scene.remove(p));
395
+ if (GAME.capturedShip && GAME.capturedShip.mesh.parent) GAME.scene.remove(GAME.capturedShip.mesh);
396
+
397
+ GAME.enemies = [];
398
+ GAME.playerProjectiles = [];
399
+ GAME.enemyProjectiles = [];
400
+ GAME.explosions = [];
401
+ GAME.powerUps = [];
402
+ }
403
+
404
+ function createIndividualShipMesh(playerIdentifier) {
405
+ const primaryColor = playerIdentifier === 'p1' ? 0x00ff00 : 0x00aaff;
406
+ const accentColor = playerIdentifier === 'p1' ? 0x00aa00 : 0x0077bb;
407
+ const cockpitColor = 0xffffff;
408
+
409
+ const ship = new THREE.Group();
410
+
411
+ const bodyGeo = new THREE.ConeGeometry(1, 2.5, 8);
412
+ const bodyMat = new THREE.MeshPhongMaterial({ color: primaryColor });
413
+ const body = new THREE.Mesh(bodyGeo, bodyMat);
414
+ body.rotation.x = Math.PI / 2;
415
+ ship.add(body);
416
+
417
+ const wingGeo = new THREE.BoxGeometry(3.5, 0.2, 1.2);
418
+ const wingMat = new THREE.MeshPhongMaterial({ color: accentColor });
419
+ const wing = new THREE.Mesh(wingGeo, wingMat);
420
+ wing.position.set(0, 0, 0.5);
421
+ ship.add(wing);
422
+
423
+ const cockpitGeo = new THREE.SphereGeometry(0.5, 16, 8);
424
+ const cockpitMat = new THREE.MeshPhongMaterial({ color: cockpitColor, emissive: 0x5555ff, shininess: 100 });
425
+ const cockpit = new THREE.Mesh(cockpitGeo, cockpitMat);
426
+ cockpit.position.set(0, 0.3, -0.8);
427
+ ship.add(cockpit);
428
+
429
+ const thrusterGeo = new THREE.CylinderGeometry(0.3, 0.5, 1, 8);
430
+ const thrusterMat = new THREE.MeshPhongMaterial({ color: 0xff8800, emissive: 0xff8800 });
431
+ const leftThruster = new THREE.Mesh(thrusterGeo, thrusterMat);
432
+ leftThruster.position.set(-1.2, -0.1, 1.5);
433
+ ship.add(leftThruster);
434
+ const rightThruster = new THREE.Mesh(thrusterGeo, thrusterMat);
435
+ rightThruster.position.set(1.2, -0.1, 1.5);
436
+ ship.add(rightThruster);
437
+
438
+ ship.scale.set(0.7,0.7,0.7);
439
+ return ship;
440
+ }
441
+
442
+ function createPlayerShipGroup() {
443
+ if (GAME.playerShipGroup) {
444
+ GAME.scene.remove(GAME.playerShipGroup);
445
+ GAME.playerShipGroup = null;
446
+ }
447
+
448
+ GAME.playerShipGroup = new THREE.Group();
449
+ GAME.playerFleet = [];
450
+
451
+ const fighterCount = GAME.players[GAME.currentPlayer].fighterCount;
452
+ const spacing = 3;
453
+
454
+ for (let i = 0; i < fighterCount; i++) {
455
+ const individualShip = createIndividualShipMesh(GAME.currentPlayer);
456
+ individualShip.position.x = (i - (fighterCount - 1) / 2) * spacing;
457
+ GAME.playerFleet.push(individualShip);
458
+ GAME.playerShipGroup.add(individualShip);
459
+ }
460
+
461
+ GAME.playerShipGroup.position.set(0, 0, 15);
462
+ GAME.playerShipGroup.velocity = new THREE.Vector3();
463
+ GAME.scene.add(GAME.playerShipGroup);
464
+ }
465
+
466
+ function createGrunt(pos) {
467
+ const mat = new THREE.MeshPhongMaterial({ color: 0xff0000 });
468
+ const mesh = new THREE.Group();
469
+ mesh.add(new THREE.Mesh(new THREE.TetrahedronGeometry(1), mat));
470
+ const wing1 = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 1.5), mat);
471
+ wing1.position.set(0.8, 0, 0);
472
+ wing1.rotation.y = Math.PI / 4;
473
+ mesh.add(wing1);
474
+ const wing2 = wing1.clone();
475
+ wing2.position.set(-0.8, 0, 0);
476
+ wing2.rotation.y = -Math.PI / 4;
477
+ mesh.add(wing2);
478
+ mesh.scale.set(0.8, 0.8, 0.8);
479
+ return createEnemyObject(mesh, pos, 100, 'grunt');
480
+ }
481
+
482
+ function createCharger(pos) {
483
+ const mat = new THREE.MeshPhongMaterial({ color: 0xffff00 });
484
+ const mesh = new THREE.Group();
485
+ mesh.add(new THREE.Mesh(new THREE.OctahedronGeometry(1), mat));
486
+ const cannon = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 1, 8), new THREE.MeshPhongMaterial({ color: 0x888800 }));
487
+ cannon.position.set(0, 0, -0.8);
488
+ mesh.add(cannon);
489
+ mesh.scale.set(0.9, 0.9, 0.9);
490
+ return createEnemyObject(mesh, pos, 150, 'charger');
491
+ }
492
+
493
+ function createBoss(pos) {
494
+ const mat = new THREE.MeshPhongMaterial({ color: 0x00ffff });
495
+ const mesh = new THREE.Group();
496
+ mesh.add(new THREE.Mesh(new THREE.IcosahedronGeometry(1.2), mat));
497
+ const eye = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 8), new THREE.MeshPhongMaterial({ color: 0xff0000, emissive: 0xff0000 }));
498
+ eye.position.set(0, 0.5, -0.5);
499
+ mesh.add(eye);
500
+ const antenna1 = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 1, 8), new THREE.MeshPhongMaterial({ color: 0xaaaaaa }));
501
+ antenna1.position.set(-0.7, 0.7, 0);
502
+ antenna1.rotation.x = Math.PI / 4;
503
+ mesh.add(antenna1);
504
+ const antenna2 = antenna1.clone();
505
+ antenna2.position.set(0.7, 0.7, 0);
506
+ antenna2.rotation.x = -Math.PI / 4;
507
+ mesh.add(antenna2);
508
+ return createEnemyObject(mesh, pos, 300, 'boss');
509
+ }
510
+
511
+ function createEnemyObject(mesh, pos, score, type) {
512
+ const enemy = {
513
+ mesh: mesh,
514
+ state: 'FORMING',
515
+ scoreValue: score,
516
+ type: type,
517
+ formationPos: new THREE.Vector3().copy(pos),
518
+ diveTimer: Math.random() * 3 + 2,
519
+ tractorBeam: null,
520
+ isCapturing: false,
521
+ initialSpawnPosition: new THREE.Vector3()
522
  };
523
+ const spawnX = (Math.random() - 0.5) * 80;
524
+ const spawnZ = -50 - Math.random() * 20;
525
+ enemy.mesh.position.set(spawnX, 0, spawnZ);
526
+ enemy.initialSpawnPosition.copy(enemy.mesh.position);
527
+ GAME.enemies.push(enemy);
528
+ GAME.scene.add(enemy.mesh);
529
+ return enemy;
530
+ }
531
 
532
+ function createStarfield() {
533
+ const numLayers = 3;
534
+ const layerColors = [0xbbbbbb, 0xaaaaaa, 0x888888];
535
+ const layerSizes = [0.4, 0.7, 1.0];
536
+ const layerSpeeds = [10, 20, 30];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
 
538
+ for (let i = 0; i < numLayers; i++) {
539
+ const starGeometry = new THREE.BufferGeometry();
540
+ const starVertices = [];
541
+ for (let j = 0; j < 5000; j++) {
542
+ const x = THREE.MathUtils.randFloatSpread(1000);
543
+ const y = THREE.MathUtils.randFloatSpread(1000);
544
+ const z = THREE.MathUtils.randFloatSpread(1000);
545
+ starVertices.push(x, y, z);
546
  }
547
+ starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
548
+ const starMaterial = new THREE.PointsMaterial({ color: layerColors[i], size: layerSizes[i] });
549
+ const stars = new THREE.Points(starGeometry, starMaterial);
550
+ stars.userData.speed = layerSpeeds[i];
551
+ GAME.stars.push(stars);
552
+ GAME.scene.add(stars);
553
+ }
554
+ }
555
+
556
+ function startWave() {
557
+ GAME.currentWaveEnemiesSpawned = 0;
558
+ const waveInfo = GAME.waveData[(GAME.wave - 1) % GAME.waveData.length];
559
+ GAME.currentWaveTotalEnemies = waveInfo.grunts + waveInfo.chargers + waveInfo.bosses;
560
 
561
+ if (waveInfo.type === 'armada') {
562
+ createArmada(waveInfo.grunts);
563
+ } else {
564
+ let enemyIndex = 0;
565
+ function createEnemyInFormation(creatorFn) {
566
+ const row = Math.floor(enemyIndex / 8);
567
+ const col = enemyIndex % 8;
568
+ const pos = new THREE.Vector3((col - 3.5) * 4, 0, -15 - row * 4);
569
+ creatorFn(pos);
570
+ enemyIndex++;
571
+ }
572
+
573
+ for (let i = 0; i < waveInfo.grunts; i++) createEnemyInFormation(createGrunt);
574
+ for (let i = 0; i < waveInfo.chargers; i++) createEnemyInFormation(createCharger);
575
+ for (let i = 0; i < waveInfo.bosses; i++) createEnemyInFormation(createBoss);
576
+ }
577
+ }
578
 
579
+ function createArmada(count) {
580
+ const rows = Math.ceil(Math.sqrt(count));
581
+ const cols = Math.ceil(count / rows);
582
+ const spacing = 3;
583
+ let enemyCount = 0;
584
+ for (let r = 0; r < rows; r++) {
585
+ for (let c = 0; c < cols; c++) {
586
+ if (enemyCount >= count) break;
587
+ const posX = (c - cols / 2 + 0.5) * spacing;
588
+ const posZ = -30 - (r * spacing);
589
+ createGrunt(new THREE.Vector3(posX, 0, posZ));
590
+ enemyCount++;
591
  }
592
+ if (enemyCount >= count) break;
593
+ }
594
+ }
595
 
596
+ function firePlayerProjectile() {
597
+ if (!GAME.canShoot || GAME.state !== 'PLAYING' || !GAME.playerShipGroup) return;
598
+ // Use Tone.now() to ensure distinct trigger times for rapidly fired sounds
599
+ if(GAME.audioContextReady && GAME.sfx.playerShoot) GAME.sfx.playerShoot.triggerAttackRelease("C4", "32n", Tone.now() + Math.random() * 0.0001);
600
 
601
+ GAME.canShoot = false;
602
+ setTimeout(() => { GAME.canShoot = true; }, GAME.shootCooldown);
603
 
604
+ const currentPlayerData = GAME.players[GAME.currentPlayer];
605
+ const numShotsPerFighter = currentPlayerData.missileCount;
 
606
 
607
+ GAME.playerFleet.forEach(fighter => {
608
+ for (let i = 0; i < numShotsPerFighter; i++) {
609
+ const geo = new THREE.CylinderGeometry(0.1, 0.1, 1, 8);
610
+ const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff });
611
+ const p = new THREE.Mesh(geo, mat);
612
+
613
+ const shotOffset = (i - (numShotsPerFighter - 1) / 2) * 0.5;
614
+ p.position.copy(fighter.getWorldPosition(new THREE.Vector3())).add(new THREE.Vector3(shotOffset, 0, -1));
615
+ p.rotation.x = Math.PI / 2;
616
+
617
+ GAME.playerProjectiles.push({ mesh: p, velocity: new THREE.Vector3(0, 0, -1.5) });
618
+ GAME.scene.add(p);
619
+ }
620
+ });
621
+ }
622
 
623
+ function fireEnemyProjectile(enemy) {
624
+ if(GAME.audioContextReady && GAME.sfx.enemyShoot) GAME.sfx.enemyShoot.triggerAttackRelease("A3", "32n", Tone.now() + Math.random() * 0.0001);
625
+ const geo = new THREE.SphereGeometry(0.3, 8, 8);
626
+ const mat = new THREE.MeshBasicMaterial({ color: 0xffa500 });
627
+ const p = new THREE.Mesh(geo, mat);
628
+ p.position.copy(enemy.mesh.position);
629
+ p.velocity = new THREE.Vector3().subVectors(GAME.playerShipGroup.position, enemy.mesh.position).normalize().multiplyScalar(0.3);
630
+ GAME.enemyProjectiles.push(p);
631
+ GAME.scene.add(p);
632
+ }
633
+
634
+ function createExplosion(position) {
635
+ if(GAME.audioContextReady && GAME.sfx.explosion) GAME.sfx.explosion.triggerAttackRelease("8n", Tone.now() + Math.random() * 0.0001);
636
+ const geo = new THREE.IcosahedronGeometry(1, 1);
637
+ const mat = new THREE.MeshBasicMaterial({ color: 0xffff00, transparent: true });
638
+ const explosion = new THREE.Mesh(geo, mat);
639
+ explosion.position.copy(position);
640
+ explosion.scale.set(0.1, 0.1, 0.1);
641
+ explosion.life = 0.5;
642
+ GAME.explosions.push(explosion);
643
+ GAME.scene.add(explosion);
644
+ }
645
 
646
+ function createPowerUp(position) {
647
+ if(GAME.audioContextReady && GAME.sfx.powerUp) GAME.sfx.powerUp.triggerAttackRelease("C6", Tone.now() + Math.random() * 0.0001);
648
+ const geo = new THREE.CylinderGeometry(0.5, 0.5, 1, 12);
649
+ const mat = new THREE.MeshPhongMaterial({ color: 0x0000ff });
650
+ const powerUp = new THREE.Mesh(geo, mat);
651
+ powerUp.position.copy(position);
652
+ powerUp.rotation.x = Math.PI / 2;
653
+ powerUp.velocity = new THREE.Vector3(0, 0, 0.05);
654
+ GAME.powerUps.push(powerUp);
655
+ GAME.scene.add(powerUp);
656
+ }
657
 
658
+ function updatePlayer(delta) {
659
+ const acceleration = 0.05;
660
+ const damping = 0.9;
661
+
662
+ if (GAME.input.left) GAME.playerShipGroup.velocity.x -= acceleration;
663
+ if (GAME.input.right) GAME.playerShipGroup.velocity.x += acceleration;
664
+
665
+ GAME.playerShipGroup.position.x += GAME.playerShipGroup.velocity.x;
666
+ GAME.playerShipGroup.velocity.x *= damping;
667
 
668
+ GAME.playerShipGroup.position.x = Math.max(-GAME.playerBoundaryX, Math.min(GAME.playerBoundaryX, GAME.playerShipGroup.position.x));
669
+ GAME.playerShipGroup.rotation.z = -GAME.playerShipGroup.velocity.x * 2;
 
 
 
 
 
670
 
671
+ if (GAME.invincible) {
672
+ GAME.playerShipGroup.visible = (Math.floor(GAME.clock.elapsedTime * 10) % 2 === 0);
673
+ } else {
674
+ GAME.playerShipGroup.visible = true;
675
+ }
676
+ }
677
+
678
+ function updateEnemies(delta) {
679
+ for (let i = GAME.enemies.length - 1; i >= 0; i--) {
680
+ const enemy = GAME.enemies[i];
681
+
682
+ if (enemy.state === 'FORMING') {
683
+ enemy.mesh.position.lerp(enemy.formationPos, delta * 2);
684
+ if (enemy.mesh.position.distanceTo(enemy.formationPos) < 0.1) {
685
+ enemy.state = 'IN_FORMATION';
686
+ }
687
+ } else if (enemy.state === 'IN_FORMATION') {
688
+ enemy.diveTimer -= delta;
689
+ if (enemy.diveTimer <= 0) {
690
+ enemy.state = 'DIVING';
691
+ enemy.diveTarget = new THREE.Vector3(GAME.playerShipGroup.position.x + (Math.random()-0.5)*10, 0, 25);
692
+ }
693
+
694
+ if (enemy.type === 'boss' && !enemy.isCapturing && GAME.players[GAME.currentPlayer].fighterCount < 2 && Math.random() < 0.005) {
695
+ startTractorBeam(enemy);
696
+ }
697
+
698
+ if(Math.random() < 0.0005) {
699
+ fireEnemyProjectile(enemy);
700
+ }
701
+ } else if (enemy.state === 'DIVING') {
702
+ enemy.mesh.position.lerp(enemy.diveTarget, delta * 1.5);
703
+ if (enemy.mesh.position.z > 20) {
704
+ enemy.mesh.position.z = -30;
705
+ enemy.state = 'FORMING';
706
+ enemy.diveTimer = Math.random() * 5 + 5;
707
+ }
708
+ }
709
+ if(enemy.isCapturing) updateTractorBeam(enemy, delta);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
  }
711
+ }
712
+
713
+ function startTractorBeam(boss) {
714
+ if(GAME.capturedShip || GAME.players[GAME.currentPlayer].fighterCount > 1) return;
715
+ if(GAME.audioContextReady && GAME.sfx.captureBeam) GAME.sfx.captureBeam.triggerAttackRelease("G2", "2s", Tone.now());
716
+ boss.isCapturing = true;
717
+ boss.captureTimer = 1.5;
718
+ const beamGeo = new THREE.ConeGeometry(2, 20, 16, 1, true);
719
+ const beamMat = new THREE.MeshBasicMaterial({ color: 0x00ffff, transparent: true, opacity: 0.5, side: THREE.DoubleSide });
720
+ boss.tractorBeam = new THREE.Mesh(beamGeo, beamMat);
721
+ boss.tractorBeam.position.set(0, -10, 0);
722
+ boss.mesh.add(boss.tractorBeam);
723
+ }
724
 
725
+ function updateTractorBeam(boss, delta) {
726
+ boss.captureTimer -= delta;
727
+
728
+ const beamWorldPos = new THREE.Vector3();
729
+ boss.tractorBeam.getWorldPosition(beamWorldPos);
730
+ const playerShipWorldPos = new THREE.Vector3();
731
+ GAME.playerShipGroup.getWorldPosition(playerShipWorldPos);
732
 
733
+ if (playerShipWorldPos.distanceTo(beamWorldPos) < 5 && Math.abs(playerShipWorldPos.x - boss.mesh.position.x) < 3 && !GAME.invincible) {
734
+ GAME.state = 'CAPTURED';
735
+ GAME.capturedShip = {
736
+ mesh: GAME.playerShipGroup,
737
+ boss: boss,
738
+ isFree: false
739
+ };
740
+ GAME.playerShipGroup.velocity.set(0,0,0);
741
+ GAME.scene.remove(GAME.playerShipGroup);
742
+ boss.mesh.add(GAME.playerShipGroup);
743
+ GAME.playerShipGroup.position.set(0, 0, 3);
744
+ }
745
 
746
+ if (boss.captureTimer <= 0 || GAME.state === 'CAPTURED') {
747
+ boss.isCapturing = false;
748
+ if (boss.tractorBeam && boss.mesh) {
749
+ boss.mesh.remove(boss.tractorBeam);
750
+ }
751
+ boss.tractorBeam = null;
752
+ if(GAME.state === 'CAPTURED') {
753
+ if (!GAME.capturedShip.isFree) {
754
+ playerLostLife(true);
755
+ }
756
+ }
757
+ }
758
+ }
759
+
760
+ function updateProjectiles(delta) {
761
+ GAME.playerProjectiles.forEach((pObj, i) => {
762
+ const p = pObj.mesh;
763
+ const pVel = pObj.velocity;
764
 
765
+ if (GAME.enemies.length > 0) {
766
+ let closestEnemy = null;
767
+ let minDist = Infinity;
768
+ GAME.enemies.forEach(enemy => {
769
+ const dist = p.position.distanceTo(enemy.mesh.position);
770
+ if (dist < minDist) {
771
+ minDist = dist;
772
+ closestEnemy = enemy;
773
  }
774
+ });
775
 
776
+ if (closestEnemy) {
777
+ const targetDirection = new THREE.Vector3().subVectors(closestEnemy.mesh.position, p.position).normalize();
778
+ pVel.lerp(targetDirection.multiplyScalar(1.5), 0.05);
779
+ }
780
+ }
781
 
782
+ p.position.add(pVel);
 
 
 
783
 
784
+ if (p.position.z < -40) {
785
+ GAME.scene.remove(p);
786
+ GAME.playerProjectiles.splice(i, 1);
787
+ }
788
+ });
789
+ GAME.enemyProjectiles.forEach((p, i) => {
790
+ p.position.add(p.velocity);
791
+ if (p.position.z > 40) {
792
+ GAME.scene.remove(p);
793
+ GAME.enemyProjectiles.splice(i, 1);
794
+ }
795
+ });
796
+ }
797
+
798
+ function updateExplosions(delta) {
799
+ GAME.explosions.forEach((ex, i) => {
800
+ ex.life -= delta;
801
+ ex.scale.multiplyScalar(1 + delta * 5);
802
+ ex.material.opacity = ex.life * 2;
803
+ if(ex.life <= 0) {
804
+ GAME.scene.remove(ex);
805
+ GAME.explosions.splice(i,1);
806
+ }
807
+ });
808
+ }
809
+
810
+ function updatePowerUps(delta) {
811
+ GAME.powerUps.forEach((p, i) => {
812
+ p.position.z += p.velocity.z;
813
+ if (p.position.z > 20) {
814
+ GAME.scene.remove(p);
815
+ GAME.powerUps.splice(i, 1);
816
+ }
817
+ });
818
+ }
819
+
820
+ function checkCollisions() {
821
+ if (!GAME.playerShipGroup || GAME.state !== 'PLAYING') return;
822
+
823
+ const playerBox = new THREE.Box3().setFromObject(GAME.playerShipGroup);
824
+
825
+ for (let i = GAME.playerProjectiles.length - 1; i >= 0; i--) {
826
+ const pObj = GAME.playerProjectiles[i];
827
+ const p = pObj.mesh;
828
+ const pBox = new THREE.Box3().setFromObject(p);
829
+ for (let j = GAME.enemies.length - 1; j >= 0; j--) {
830
+ const enemy = GAME.enemies[j];
831
+ const eBox = new THREE.Box3().setFromObject(enemy.mesh);
832
+ if (pBox.intersectsBox(eBox)) {
833
+ GAME.scene.remove(p);
834
+ GAME.playerProjectiles.splice(i, 1);
835
+
836
+ hitEnemy(enemy, j);
837
+ break;
838
  }
839
  }
840
  }
841
+
842
+ if (!GAME.invincible) {
843
+ for (let i = GAME.enemies.length - 1; i >= 0; i--) {
844
+ const enemy = GAME.enemies[i];
845
+ const eBox = new THREE.Box3().setFromObject(enemy.mesh);
846
+ if (playerBox.intersectsBox(eBox)) {
847
+ hitEnemy(enemy, i);
848
+ playerLostLife();
849
+ break;
850
+ }
851
+ }
852
+ }
853
+
854
+ if (!GAME.invincible) {
855
+ for (let i = GAME.enemyProjectiles.length - 1; i >= 0; i--) {
856
+ const p = GAME.enemyProjectiles[i];
857
+ const pBox = new THREE.Box3().setFromObject(p);
858
+ if(playerBox.intersectsBox(pBox)) {
859
+ GAME.scene.remove(p);
860
+ GAME.enemyProjectiles.splice(i,1);
861
+ playerLostLife();
862
+ break;
863
+ }
864
+ }
865
+ }
866
+
867
+ if(GAME.capturedShip && GAME.capturedShip.isFree) {
868
+ const cBox = new THREE.Box3().setFromObject(GAME.capturedShip.mesh);
869
+ if(playerBox.intersectsBox(cBox)) {
870
+ GAME.players[GAME.currentPlayer].fighterCount++;
871
+ GAME.scene.remove(GAME.playerShipGroup);
872
+ createPlayerShipGroup();
873
+ GAME.scene.remove(GAME.capturedShip.mesh);
874
+ GAME.capturedShip = null;
875
+ startInvincibility();
876
+ }
877
+ }
878
 
879
+ for (let i = GAME.powerUps.length - 1; i >= 0; i--) {
880
+ const p = GAME.powerUps[i];
881
+ const pBox = new THREE.Box3().setFromObject(p);
882
+ if (playerBox.intersectsBox(pBox)) {
883
+ GAME.players[GAME.currentPlayer].missileCount++;
884
+ GAME.scene.remove(p);
885
+ GAME.powerUps.splice(i, 1);
886
+ break;
887
+ }
888
+ }
889
+ }
890
+
891
+ function hitEnemy(enemy, index) {
892
+ createExplosion(enemy.mesh.position);
893
+ GAME.players[GAME.currentPlayer].score += enemy.scoreValue;
894
+
895
+ if (Math.random() < GAME.powerUpDropChance) {
896
+ createPowerUp(enemy.mesh.position);
897
+ }
898
+
899
+ if (GAME.capturedShip && GAME.capturedShip.boss === enemy) {
900
+ const captured = GAME.capturedShip;
901
+ captured.isFree = true;
902
+ if (captured.boss.mesh && captured.mesh && captured.mesh.parent === captured.boss.mesh) {
903
+ captured.boss.mesh.remove(captured.mesh);
904
+ }
905
+ GAME.scene.add(captured.mesh);
906
+ captured.mesh.position.copy(enemy.mesh.position);
907
+ captured.velocity = new THREE.Vector3(0, 0, 0.2);
908
+ GAME.state = 'PLAYING';
909
+ }
910
+
911
+ if (enemy.mesh.parent) {
912
+ GAME.scene.remove(enemy.mesh);
913
+ }
914
+ GAME.enemies.splice(index, 1);
915
+
916
+ if(GAME.enemies.length === 0) {
917
+ GAME.wave++;
918
+ setTimeout(startWave, 2000);
919
+ }
920
+ }
921
+
922
+ function playerLostLife(isCapturedLoss = false) {
923
+ if(GAME.state === 'GAME_OVER') return;
924
+ if(GAME.audioContextReady && GAME.sfx.playerHit) GAME.sfx.playerHit.triggerAttackRelease("C2", Tone.now() + Math.random() * 0.0001);
925
 
926
+ const currentPlayerData = GAME.players[GAME.currentPlayer];
 
927
 
928
+ if (isCapturedLoss && GAME.capturedShip) {
929
+ if (GAME.capturedShip.mesh.parent) {
930
+ GAME.scene.remove(GAME.capturedShip.mesh);
931
+ }
932
+ GAME.capturedShip = null;
933
+ }
934
+
935
+ if(currentPlayerData.fighterCount > 1) {
936
+ currentPlayerData.fighterCount--;
937
+ createExplosion(GAME.playerShipGroup.position);
938
+ GAME.scene.remove(GAME.playerShipGroup);
939
+ createPlayerShipGroup();
940
+ startInvincibility();
941
+ return;
942
+ }
943
 
944
+ currentPlayerData.lives--;
945
+ createExplosion(GAME.playerShipGroup.position);
946
+ GAME.scene.remove(GAME.playerShipGroup);
947
+
948
+ if (currentPlayerData.lives < 0) {
949
+ let allPlayersOut = true;
950
+ if (GAME.numPlayers === 2) {
951
+ const otherPlayer = GAME.currentPlayer === 'p1' ? 'p2' : 'p1';
952
+ if (GAME.players[otherPlayer].lives >= 0) {
953
+ GAME.currentPlayer = otherPlayer;
954
+ allPlayersOut = false;
955
+ document.getElementById('current-player-display').textContent = `${otherPlayer.toUpperCase()} TURN`;
956
+ GAME.players[GAME.currentPlayer].fighterCount = 1;
957
+ GAME.players[GAME.currentPlayer].missileCount = 1;
958
+ createPlayerShipGroup();
959
+ startInvincibility();
960
+ GAME.state = 'PLAYING';
961
+ updateHUD();
962
+ return;
963
  }
964
+ }
965
+ if (allPlayersOut) {
966
+ gameOver();
967
+ }
968
+ } else {
969
+ setTimeout(() => {
970
+ if (GAME.state !== 'GAME_OVER') {
971
+ createPlayerShipGroup();
972
+ startInvincibility();
973
+ }
974
+ }, 1000);
975
+ }
976
+ }
977
+
978
+ function startInvincibility() {
979
+ GAME.invincible = true;
980
+ setTimeout(() => {
981
+ GAME.invincible = false;
982
+ if (GAME.playerShipGroup) GAME.playerShipGroup.visible = true;
983
+ }, GAME.invincibilityDuration);
984
+ }
985
+
986
+ function gameOver() {
987
+ if(GAME.audioContextReady) {
988
+ stopAllMusic();
989
+ if(GAME.sfx.gameOver) GAME.sfx.gameOver.triggerAttackRelease("C2", "2s", Tone.now());
990
+ }
991
+ GAME.state = 'GAME_OVER';
992
+ const finalScore = GAME.players.p1.score + (GAME.numPlayers === 2 ? GAME.players.p2.score : 0);
993
+ document.getElementById('final-score').textContent = `TOTAL SCORE: ${finalScore}`;
994
+ document.getElementById('game-over-overlay').style.display = 'flex';
995
+
996
+ const lowestHighScore = GAME.highScores.length > 0 ? GAME.highScores[GAME.highScores.length - 1].score : 0;
997
+ if (finalScore > lowestHighScore || GAME.highScores.length < 10) {
998
+ document.getElementById('high-score-form').classList.remove('hidden');
999
+ } else {
1000
+ document.getElementById('high-score-form').classList.add('hidden');
1001
+ }
1002
+ }
1003
+
1004
+ function handleHighScoreSubmit(e) {
1005
+ e.preventDefault();
1006
+ const initials = document.getElementById('initials-input').value.toUpperCase();
1007
+ const finalScore = GAME.players.p1.score + (GAME.numPlayers === 2 ? GAME.players.p2.score : 0);
1008
+
1009
+ GAME.highScores.push({ initials: initials, score: finalScore });
1010
+ GAME.highScores.sort((a, b) => b.score - a.score);
1011
+ GAME.highScores = GAME.highScores.slice(0, 10);
1012
+
1013
+ localStorage.setItem('galagaHighScores', JSON.stringify(GAME.highScores));
1014
+
1015
+ document.getElementById('high-score-form').classList.add('hidden');
1016
+ document.getElementById('initials-input').value = '';
1017
+ showHighScores();
1018
+ }
1019
 
1020
+ function showHighScores() {
1021
+ stopAllMusic();
1022
+ if(GAME.audioContextReady && GAME.music.highScore) GAME.music.highScore.start(Tone.now());
1023
+ document.getElementById('menu-overlay').style.display = 'none';
1024
+ document.getElementById('game-over-overlay').style.display = 'none';
1025
+ document.getElementById('high-scores-overlay').style.display = 'flex';
1026
+
1027
+ const list = document.getElementById('high-scores-list');
1028
+ list.innerHTML = '';
1029
+ if (GAME.highScores.length === 0) {
1030
+ list.innerHTML = '<li>No high scores yet!</li>';
1031
+ } else {
1032
+ GAME.highScores.forEach((entry, index) => {
1033
+ const li = document.createElement('li');
1034
+ li.innerHTML = `<span>${index + 1}. ${entry.initials}</span> <span>${entry.score}</span>`;
1035
+ list.appendChild(li);
1036
+ });
1037
+ }
1038
+ GAME.state = 'HIGH_SCORES';
1039
+ }
1040
+
1041
+ function togglePause() {
1042
+ if (GAME.state === 'PLAYING') {
1043
+ GAME.state = 'PAUSED';
1044
+ stopAllMusic();
1045
+ document.getElementById('pause-overlay').style.display = 'flex';
1046
+ } else if (GAME.state === 'PAUSED') {
1047
+ GAME.state = 'PLAYING';
1048
+ document.getElementById('pause-overlay').style.display = 'none';
1049
+ }
1050
+ }
1051
+
1052
+ function updateHUD() {
1053
+ document.getElementById('score-p1-display').textContent = `P1 SCORE: ${GAME.players.p1.score}`;
1054
+ document.getElementById('score-p2-display').textContent = `P2 SCORE: ${GAME.players.p2.score}`;
1055
+ document.getElementById('wave-display').textContent = `WAVE: ${GAME.wave}`;
1056
+ document.getElementById('high-score-current-display').textContent = `HIGH SCORE: ${GAME.highScores.length > 0 ? GAME.highScores[0].score : 0}`;
1057
+ document.getElementById('current-player-display').textContent = `${GAME.currentPlayer.toUpperCase()} TURN`;
1058
+
1059
+ const livesContainer = document.getElementById('lives-display');
1060
+ livesContainer.innerHTML = `LIVES: `;
1061
+ const lifeIcon = '<span>&#x1F6F8;</span>';
1062
+ for (let i = 0; i < GAME.players[GAME.currentPlayer].lives; i++) {
1063
+ livesContainer.innerHTML += lifeIcon;
1064
+ }
1065
+ }
1066
+
1067
+ function onWindowResize() {
1068
+ GAME.camera.aspect = window.innerWidth / window.innerHeight;
1069
+ GAME.camera.updateProjectionMatrix();
1070
+ GAME.renderer.setSize(window.innerWidth, window.innerHeight);
1071
+ }
1072
+
1073
+ function animate() {
1074
+ requestAnimationFrame(animate);
1075
+ const delta = GAME.clock.getDelta();
1076
+
1077
+ GAME.stars.forEach(starLayer => {
1078
+ starLayer.position.z += delta * starLayer.userData.speed;
1079
+ if (starLayer.position.z > 500) starLayer.position.z -= 1000;
1080
+ });
1081
+
1082
+ if (GAME.state === 'DEMO') {
1083
+ GAME.demoTimer += delta;
1084
+ GAME.musicAlternationTimer += delta;
1085
+
1086
+ if (GAME.musicAlternationTimer >= GAME.musicAlternationInterval) {
1087
+ if (GAME.music.demo && GAME.music.demo.state === 'started') {
1088
+ if (GAME.music.demo) GAME.music.demo.stop();
1089
+ if(GAME.highScores.length > 0 && GAME.music.highScore) {
1090
+ GAME.music.highScore.start(Tone.now()); // Start high score music
1091
  }
1092
+ } else if (GAME.highScores.length > 0 && GAME.music.highScore && GAME.music.highScore.state === 'started') {
1093
+ if (GAME.music.highScore) GAME.music.highScore.stop();
1094
+ if(GAME.music.demo) GAME.music.demo.start(Tone.now()); // Start demo music
1095
+ } else if (GAME.highScores.length === 0 && GAME.music.demo && GAME.music.demo.state !== 'started') {
1096
+ if(GAME.music.demo) GAME.music.demo.start(Tone.now()); // Only demo music if no high scores
 
 
 
1097
  }
1098
+ GAME.musicAlternationTimer = 0;
1099
+ }
1100
 
1101
+ GAME.enemies.forEach(enemy => {
1102
+ enemy.mesh.position.z += delta * 0.5;
1103
+ enemy.mesh.rotation.y += delta * 0.5;
1104
+ if (enemy.mesh.position.z > 10) {
1105
+ enemy.mesh.position.z = -50;
1106
+ }
1107
+ });
1108
+ updateEnemyProjectilesInDemo(delta);
1109
+ updateExplosions(delta);
1110
+ } else if (GAME.state === 'PLAYING') {
1111
+ updatePlayer(delta);
1112
+ updateEnemies(delta);
1113
+ updateProjectiles(delta);
1114
+ updatePowerUps(delta);
1115
+ checkCollisions();
1116
+ updateHUD();
1117
 
1118
+ if (GAME.capturedShip && GAME.capturedShip.isFree) {
1119
+ GAME.capturedShip.mesh.position.add(GAME.capturedShip.velocity);
1120
+ if (GAME.capturedShip.mesh.position.z > 25) {
1121
+ GAME.scene.remove(GAME.capturedShip.mesh);
1122
+ GAME.capturedShip = null;
1123
+ }
1124
  }
1125
  }
1126
+
1127
+ updateExplosions(delta);
1128
 
1129
+ GAME.renderer.render(GAME.scene, GAME.camera);
1130
+ }
 
 
 
1131
 
1132
+ function updateEnemyProjectilesInDemo(delta) {
1133
+ GAME.enemyProjectiles.forEach((p, i) => {
1134
+ p.position.add(p.velocity);
1135
+ if (p.position.z > 40) {
1136
+ GAME.scene.remove(p);
1137
+ GAME.enemyProjectiles.splice(i, 1);
1138
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1139
  });
1140
+ }
1141
+
1142
+ window.onload = init;
1143
  </script>
1144
  </body>
1145
  </html>