-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
865 lines (704 loc) · 32 KB
/
script.js
File metadata and controls
865 lines (704 loc) · 32 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
// Game State
class TypeKartGame {
constructor() {
this.selectedCharacter = null;
this.currentText = '';
this.currentIndex = 0;
this.startTime = null;
this.endTime = null;
this.correctChars = 0;
this.incorrectChars = 0;
this.isRacing = false;
this.cpuProgress = 0;
this.cpuSpeed = 30; // WPM
this.powerUpInterval = null;
// Racing texts with Mario Kart themes
this.racingTexts = [
{
title: "Rainbow Road Challenge",
difficulty: "🌟 Easy",
text: "Mario jumped into his red kart and zoomed down Rainbow Road. The colorful track sparkled with stars as he collected coins and power-ups. Princess Peach waved from her pink kart while Bowser roared behind them. The finish line was just ahead, and Mario pressed the accelerator with determination."
},
{
title: "Mushroom Kingdom Grand Prix",
difficulty: "⭐⭐ Medium",
text: "The green shell whizzed past Luigi as he navigated the twisting turns of Mushroom Kingdom. Goombas and Koopa Troopas cheered from the sidelines while Toad announced the race progress. Luigi grabbed a mushroom power-up and felt his kart surge forward with incredible speed. Victory was within reach as he approached the final lap."
},
{
title: "Bowser's Castle Speedway",
difficulty: "⭐⭐⭐ Hard",
text: "Lava bubbled beneath the treacherous stone bridges of Bowser's Castle. The air shimmered with heat as racers dodged falling fireballs and spinning flame wheels. Princess Peach expertly maneuvered her kart through the narrow passages while collecting precious coins scattered throughout the perilous course. The championship trophy awaited the bravest racer."
},
{
title: "Wario Stadium Thunder Cup",
difficulty: "⭐⭐⭐⭐ Expert",
text: "Thunder crackled overhead as Wario's massive stadium hosted the most challenging race of the season. Mud splattered across windshields while racers struggled to maintain control on the slippery track. Lightning struck dangerously close as competitors used every trick in the book. Blue shells flew through the stormy sky while determined racers pushed their engines to the absolute limit in pursuit of glory."
}
];
this.powerUpEmojis = ['🍄', '🌟', '⚡', '🎯', '💥', '🏃♂️', '🚀', '💎'];
this.characters = {
mario: { name: 'Mario', icon: '🏎️', color: '#FF6B6B' },
luigi: { name: 'Luigi', icon: '🏎️', color: '#4ECDC4' },
peach: { name: 'Peach', icon: '🏎️', color: '#FFB6C1' },
bowser: { name: 'Bowser', icon: '🏎️', color: '#FF8C00' }
};
// Powerup System
this.powerups = [];
this.powerupWords = [];
this.cpuStunned = false;
this.cpuSlowed = false;
this.cpuStunTimer = null;
this.cpuSlowTimer = null;
this.powerupTypes = {
shell: { icon: '🐢', name: 'Blue Shell', effect: 'stun', description: 'Stuns CPU for 3 seconds' },
redShell: { icon: '🔴', name: 'Red Shell', effect: 'slow', description: 'Slows CPU for 5 seconds' },
mushroom: { icon: '🍄', name: 'Mushroom', effect: 'boost', description: 'Boost your speed' },
star: { icon: '⭐', name: 'Star', effect: 'invincible', description: 'Temporary invincibility' },
lightning: { icon: '⚡', name: 'Lightning', effect: 'lightning', description: 'Slows all opponents' },
banana: { icon: '🍌', name: 'Banana', effect: 'banana', description: 'Slows CPU briefly' }
};
this.init();
}
init() {
this.bindEvents();
this.setupCharacterSelection();
}
bindEvents() {
// Character selection
document.querySelectorAll('.character').forEach(char => {
char.addEventListener('click', (e) => this.selectCharacter(e));
});
// Start race button
document.getElementById('startRace').addEventListener('click', () => this.startGame());
// Typing input
const typingInput = document.getElementById('typingInput');
typingInput.addEventListener('input', (e) => this.handleTyping(e));
typingInput.addEventListener('focus', () => this.startRace());
// Results buttons
document.getElementById('raceAgain').addEventListener('click', () => this.resetGame());
document.getElementById('newCharacter').addEventListener('click', () => this.showCharacterSelection());
// Prevent context menu on racing characters
document.addEventListener('contextmenu', (e) => {
if (e.target.closest('.character') || e.target.closest('.racer')) {
e.preventDefault();
}
});
// Powerup activation
document.addEventListener('keydown', (e) => {
if (this.isRacing) {
if (e.key === '1') this.usePowerup(0);
else if (e.key === '2') this.usePowerup(1);
else if (e.key === '3') this.usePowerup(2);
}
});
// Powerup slot clicks
document.getElementById('powerupSlot1').addEventListener('click', () => this.usePowerup(0));
document.getElementById('powerupSlot2').addEventListener('click', () => this.usePowerup(1));
document.getElementById('powerupSlot3').addEventListener('click', () => this.usePowerup(2));
}
setupCharacterSelection() {
const startButton = document.getElementById('startRace');
startButton.disabled = true;
startButton.textContent = 'Choose a Character First!';
}
selectCharacter(e) {
// Remove previous selection
document.querySelectorAll('.character').forEach(char => {
char.classList.remove('selected');
});
// Add selection to clicked character
const character = e.currentTarget;
character.classList.add('selected');
// Store selected character
this.selectedCharacter = character.dataset.character;
// Enable start button
const startButton = document.getElementById('startRace');
startButton.disabled = false;
startButton.textContent = 'Start Race!';
// Add selection effect
this.createSparkles(character);
}
startGame() {
if (!this.selectedCharacter) return;
// Hide character selection
document.getElementById('characterSelection').style.display = 'none';
// Show race track and typing area
document.getElementById('raceTrack').style.display = 'block';
document.getElementById('powerupInventory').style.display = 'block';
document.getElementById('typingArea').style.display = 'block';
// Setup race
this.setupRace();
// Focus on input
setTimeout(() => {
document.getElementById('typingInput').focus();
}, 500);
}
setupRace() {
// Select random racing text
const raceData = this.racingTexts[Math.floor(Math.random() * this.racingTexts.length)];
this.currentText = raceData.text;
// Update UI
document.getElementById('raceTitle').textContent = raceData.title;
document.getElementById('difficulty').textContent = raceData.difficulty;
document.getElementById('textContent').textContent = this.currentText;
// Setup player racer
const playerRacer = document.getElementById('playerRacer');
const selectedChar = this.characters[this.selectedCharacter];
playerRacer.innerHTML = `<span class="racer-icon" style="color: ${selectedChar.color}">${selectedChar.icon}</span>`;
// Reset game state
this.currentIndex = 0;
this.correctChars = 0;
this.incorrectChars = 0;
this.isRacing = false;
this.cpuProgress = 0;
// Reset powerup state
this.powerups = [];
this.powerupWords = [];
this.cpuStunned = false;
this.cpuSlowed = false;
if (this.cpuStunTimer) clearTimeout(this.cpuStunTimer);
if (this.cpuSlowTimer) clearTimeout(this.cpuSlowTimer);
// Reset positions
document.getElementById('playerRacer').style.left = '0%';
document.getElementById('cpuRacer').style.left = '0%';
// Clear input
document.getElementById('typingInput').value = '';
// Setup powerup words in text
this.setupPowerupWords();
// Reset stats
this.updateStats();
// Initialize powerup inventory
this.updatePowerupInventory();
// Start power-ups
this.startPowerUpAnimation();
}
startRace() {
if (!this.isRacing && this.currentText) {
this.isRacing = true;
this.startTime = Date.now();
this.startCPURace();
}
}
handleTyping(e) {
if (!this.isRacing) {
this.startRace();
}
const input = e.target.value;
const expectedText = this.currentText.substring(0, input.length);
// Clear previous styling
this.updateTextDisplay(input);
// Check if input matches expected text
if (input === expectedText) {
this.correctChars = input.length;
this.currentIndex = input.length;
this.showInputFeedback('Great typing! 🏎️', 'correct');
// Check for powerup collection
this.checkPowerupCollection(input);
// Update player position
const progress = (input.length / this.currentText.length) * 100;
document.getElementById('playerRacer').style.left = Math.min(progress, 85) + '%';
// Check if race is complete
if (input.length === this.currentText.length) {
this.finishRace('player');
return;
}
// Add success effects
if (input.length % 10 === 0 && input.length > 0) {
this.createSuccessBurst();
}
} else {
this.showInputFeedback('Check your typing! 🐢', 'incorrect');
this.incorrectChars++;
}
this.updateStats();
}
updateTextDisplay(input) {
const textContent = document.getElementById('textContent');
const fullText = this.currentText;
let html = '';
for (let i = 0; i < fullText.length; i++) {
const char = fullText[i];
if (i < input.length) {
if (input[i] === char) {
html += `<span class="correct">${char}</span>`;
} else {
html += `<span class="incorrect">${char}</span>`;
}
} else if (i === input.length) {
html += `<span class="current">${char}</span>`;
} else {
html += char;
}
}
textContent.innerHTML = html;
}
showInputFeedback(message, type) {
const feedback = document.getElementById('inputFeedback');
feedback.textContent = message;
feedback.className = `input-feedback ${type}`;
}
startCPURace() {
const cpuInterval = setInterval(() => {
if (!this.isRacing) {
clearInterval(cpuInterval);
return;
}
// CPU makes progress based on difficulty and some randomness
let baseSpeed = this.cpuSpeed;
const randomFactor = 0.8 + Math.random() * 0.4; // 0.8 to 1.2
// Apply powerup effects
if (this.cpuStunned) {
baseSpeed = 0; // CPU can't move when stunned
} else if (this.cpuSlowed) {
baseSpeed *= 0.3; // CPU moves at 30% speed when slowed
}
const progressIncrement = (baseSpeed * randomFactor) / 60; // Per second, converted to per interval
this.cpuProgress += progressIncrement;
const cpuPosition = Math.min((this.cpuProgress / this.currentText.length) * 100, 85);
document.getElementById('cpuRacer').style.left = cpuPosition + '%';
// Check if CPU wins
if (this.cpuProgress >= this.currentText.length) {
clearInterval(cpuInterval);
this.finishRace('cpu');
}
}, 100); // Update every 100ms
}
updateStats() {
if (!this.startTime) return;
const currentTime = Date.now();
const timeElapsed = (currentTime - this.startTime) / 1000; // seconds
const minutes = Math.floor(timeElapsed / 60);
const seconds = Math.floor(timeElapsed % 60);
// Update timer
document.getElementById('timer').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
// Calculate WPM
const wordsTyped = this.correctChars / 5; // Standard: 5 characters = 1 word
const wpm = timeElapsed > 0 ? Math.round((wordsTyped / timeElapsed) * 60) : 0;
document.getElementById('wpm').textContent = wpm;
// Calculate accuracy
const totalChars = this.correctChars + this.incorrectChars;
const accuracy = totalChars > 0 ? Math.round((this.correctChars / totalChars) * 100) : 100;
document.getElementById('accuracy').textContent = accuracy + '%';
}
finishRace(winner) {
this.isRacing = false;
this.endTime = Date.now();
// Stop power-ups
if (this.powerUpInterval) {
clearInterval(this.powerUpInterval);
}
// Calculate final stats
const timeElapsed = (this.endTime - this.startTime) / 1000;
const minutes = Math.floor(timeElapsed / 60);
const seconds = Math.floor(timeElapsed % 60);
const wordsTyped = this.correctChars / 5;
const wpm = Math.round((wordsTyped / timeElapsed) * 60);
const totalChars = this.correctChars + this.incorrectChars;
const accuracy = totalChars > 0 ? Math.round((this.correctChars / totalChars) * 100) : 100;
// Show results
this.showResults(winner, wpm, accuracy, minutes, seconds);
}
showResults(winner, wpm, accuracy, minutes, seconds) {
const resultsScreen = document.getElementById('resultsScreen');
const resultsTitle = document.getElementById('resultsTitle');
const resultsMessage = document.getElementById('resultsMessage');
// Set results data
document.getElementById('finalWPM').textContent = wpm;
document.getElementById('finalAccuracy').textContent = accuracy + '%';
document.getElementById('finalTime').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
// Set winner message
if (winner === 'player') {
resultsTitle.textContent = '🏆 Victory! You Won!';
resultsMessage.textContent = this.getVictoryMessage(wpm, accuracy);
} else {
resultsTitle.textContent = '🥈 Good Race! CPU Won';
resultsMessage.textContent = this.getDefeatMessage(wpm, accuracy);
}
// Show results screen
resultsScreen.style.display = 'flex';
// Celebration effects
if (winner === 'player') {
this.createCelebrationEffects();
}
}
getVictoryMessage(wpm, accuracy) {
if (wpm >= 80 && accuracy >= 95) {
return "Incredible! You're a typing champion! 🎉";
} else if (wpm >= 60 && accuracy >= 90) {
return "Excellent racing! Mario would be proud! 🌟";
} else if (wpm >= 40 && accuracy >= 85) {
return "Great job! You've got some serious skills! 🚀";
} else {
return "Nice work! Keep practicing to improve! 💪";
}
}
getDefeatMessage(wpm, accuracy) {
if (wpm >= 50 && accuracy >= 90) {
return "So close! You almost had it! 🏁";
} else if (wpm >= 30 && accuracy >= 80) {
return "Good effort! Practice makes perfect! 🎯";
} else {
return "Keep trying! Every racer starts somewhere! 🎮";
}
}
resetGame() {
// Hide results
document.getElementById('resultsScreen').style.display = 'none';
// Reset and start new race
this.setupRace();
// Focus input
setTimeout(() => {
document.getElementById('typingInput').focus();
}, 100);
}
showCharacterSelection() {
// Hide all game screens
document.getElementById('resultsScreen').style.display = 'none';
document.getElementById('raceTrack').style.display = 'none';
document.getElementById('powerupInventory').style.display = 'none';
document.getElementById('typingArea').style.display = 'none';
// Show character selection
document.getElementById('characterSelection').style.display = 'block';
// Reset selection
this.selectedCharacter = null;
document.querySelectorAll('.character').forEach(char => {
char.classList.remove('selected');
});
this.setupCharacterSelection();
}
// Visual Effects
createSparkles(element) {
const rect = element.getBoundingClientRect();
const sparkleCount = 8;
for (let i = 0; i < sparkleCount; i++) {
setTimeout(() => {
const sparkle = document.createElement('div');
sparkle.className = 'sparkle';
sparkle.textContent = '✨';
sparkle.style.position = 'absolute';
sparkle.style.left = (rect.left + Math.random() * rect.width) + 'px';
sparkle.style.top = (rect.top + Math.random() * rect.height) + 'px';
document.body.appendChild(sparkle);
setTimeout(() => {
sparkle.remove();
}, 1500);
}, i * 100);
}
}
createSuccessBurst() {
const input = document.getElementById('typingInput');
const rect = input.getBoundingClientRect();
const burst = document.createElement('div');
burst.className = 'success-burst';
burst.textContent = '🎯';
burst.style.position = 'absolute';
burst.style.left = (rect.right - 30) + 'px';
burst.style.top = (rect.top + rect.height / 2) + 'px';
document.body.appendChild(burst);
setTimeout(() => {
burst.remove();
}, 1000);
}
createCelebrationEffects() {
const effectCount = 20;
const powerUpsContainer = document.getElementById('powerUps');
for (let i = 0; i < effectCount; i++) {
setTimeout(() => {
const powerUp = document.createElement('div');
powerUp.className = 'power-up';
powerUp.textContent = this.powerUpEmojis[Math.floor(Math.random() * this.powerUpEmojis.length)];
powerUp.style.left = Math.random() * 100 + '%';
powerUpsContainer.appendChild(powerUp);
setTimeout(() => {
powerUp.remove();
}, 3000);
}, i * 200);
}
}
startPowerUpAnimation() {
this.powerUpInterval = setInterval(() => {
if (!this.isRacing) return;
const powerUpsContainer = document.getElementById('powerUps');
const powerUp = document.createElement('div');
powerUp.className = 'power-up';
powerUp.textContent = this.powerUpEmojis[Math.floor(Math.random() * this.powerUpEmojis.length)];
powerUp.style.left = Math.random() * 100 + '%';
powerUpsContainer.appendChild(powerUp);
setTimeout(() => {
powerUp.remove();
}, 3000);
}, 2000);
}
// Powerup System Methods
setupPowerupWords() {
const words = this.currentText.split(' ');
const powerupIndices = [];
// Select 3-5 random words to be powerup words
const numPowerupWords = Math.floor(Math.random() * 3) + 3;
for (let i = 0; i < numPowerupWords; i++) {
let randomIndex;
do {
randomIndex = Math.floor(Math.random() * words.length);
} while (powerupIndices.includes(randomIndex));
powerupIndices.push(randomIndex);
}
// Store powerup words info
this.powerupWords = powerupIndices.map(index => ({
index,
word: words[index],
collected: false
}));
// Update text display with highlighted powerup words
this.updateTextWithPowerups();
}
updateTextWithPowerups() {
const words = this.currentText.split(' ');
let html = '';
let wordIndex = 0;
for (let i = 0; i < words.length; i++) {
const word = words[i];
const isPowerupWord = this.powerupWords.some(pw => pw.index === i && !pw.collected);
if (isPowerupWord) {
html += `<span class="powerup-word">${word}</span>`;
} else {
html += word;
}
if (i < words.length - 1) html += ' ';
}
document.getElementById('textContent').innerHTML = html;
}
checkPowerupCollection(input) {
const words = this.currentText.split(' ');
let currentWordIndex = 0;
let charCount = 0;
// Find which word we're currently on
for (let i = 0; i < words.length; i++) {
const wordEnd = charCount + words[i].length;
if (input.length <= wordEnd) {
currentWordIndex = i;
break;
}
charCount += words[i].length + 1; // +1 for space
}
// Check if we just completed a powerup word
const powerupWord = this.powerupWords.find(pw => pw.index === currentWordIndex && !pw.collected);
if (powerupWord) {
const wordStart = charCount;
const wordEnd = charCount + words[currentWordIndex].length;
if (input.length >= wordEnd && input.substring(wordStart, wordEnd) === words[currentWordIndex]) {
this.collectPowerup(powerupWord);
}
}
}
collectPowerup(powerupWord) {
powerupWord.collected = true;
// Add powerup to inventory
if (this.powerups.length < 3) {
const powerupTypeKeys = Object.keys(this.powerupTypes);
const randomType = powerupTypeKeys[Math.floor(Math.random() * powerupTypeKeys.length)];
this.powerups.push(this.powerupTypes[randomType]);
this.updatePowerupInventory();
this.updateTextWithPowerups();
// Show collection effect
this.showPowerupCollectionEffect();
// Play collection sound
if (window.soundManager) {
window.soundManager.playSuccess();
}
}
}
updatePowerupInventory() {
for (let i = 0; i < 3; i++) {
const slot = document.getElementById(`powerupSlot${i + 1}`);
const icon = slot.querySelector('.powerup-icon');
if (this.powerups[i]) {
icon.textContent = this.powerups[i].icon;
slot.classList.add('has-powerup');
slot.classList.remove('used');
slot.title = `${this.powerups[i].name}: ${this.powerups[i].description}`;
} else {
icon.textContent = '';
slot.classList.remove('has-powerup', 'used');
slot.title = 'Empty slot';
}
}
}
usePowerup(slotIndex) {
if (!this.isRacing || !this.powerups[slotIndex]) return;
const powerup = this.powerups[slotIndex];
this.applyPowerupEffect(powerup);
// Remove powerup from inventory
this.powerups[slotIndex] = null;
this.powerups = this.powerups.filter(p => p !== null);
// Update UI
this.updatePowerupInventory();
// Mark slot as used temporarily
const slot = document.getElementById(`powerupSlot${slotIndex + 1}`);
slot.classList.add('used');
slot.classList.remove('has-powerup');
}
applyPowerupEffect(powerup) {
const cpuRacer = document.getElementById('cpuRacer');
const playerRacer = document.getElementById('playerRacer');
switch (powerup.effect) {
case 'stun':
this.cpuStunned = true;
cpuRacer.classList.add('cpu-stunned');
this.createPowerupEffect('💥', cpuRacer);
if (this.cpuStunTimer) clearTimeout(this.cpuStunTimer);
this.cpuStunTimer = setTimeout(() => {
this.cpuStunned = false;
cpuRacer.classList.remove('cpu-stunned');
}, 3000);
break;
case 'slow':
this.cpuSlowed = true;
cpuRacer.classList.add('cpu-slowed');
this.createPowerupEffect('🐌', cpuRacer);
if (this.cpuSlowTimer) clearTimeout(this.cpuSlowTimer);
this.cpuSlowTimer = setTimeout(() => {
this.cpuSlowed = false;
cpuRacer.classList.remove('cpu-slowed');
}, 5000);
break;
case 'boost':
playerRacer.classList.add('player-boosted');
this.createPowerupEffect('🚀', playerRacer);
// Give player a boost by advancing them slightly
const currentProgress = (this.correctChars / this.currentText.length) * 100;
const boostedProgress = Math.min(currentProgress + 5, 85);
playerRacer.style.left = boostedProgress + '%';
setTimeout(() => {
playerRacer.classList.remove('player-boosted');
}, 1000);
break;
case 'lightning':
this.cpuSlowed = true;
cpuRacer.classList.add('cpu-slowed');
this.createPowerupEffect('⚡', cpuRacer);
if (this.cpuSlowTimer) clearTimeout(this.cpuSlowTimer);
this.cpuSlowTimer = setTimeout(() => {
this.cpuSlowed = false;
cpuRacer.classList.remove('cpu-slowed');
}, 4000);
break;
case 'banana':
this.cpuSlowed = true;
cpuRacer.classList.add('cpu-slowed');
this.createPowerupEffect('🍌', cpuRacer);
if (this.cpuSlowTimer) clearTimeout(this.cpuSlowTimer);
this.cpuSlowTimer = setTimeout(() => {
this.cpuSlowed = false;
cpuRacer.classList.remove('cpu-slowed');
}, 2000);
break;
}
// Play powerup sound
if (window.soundManager) {
window.soundManager.playTone(800, 0.3, 'square');
}
}
createPowerupEffect(emoji, targetElement) {
const rect = targetElement.getBoundingClientRect();
const effect = document.createElement('div');
effect.className = 'powerup-effect';
effect.textContent = emoji;
effect.style.position = 'absolute';
effect.style.left = (rect.left + rect.width / 2) + 'px';
effect.style.top = (rect.top + rect.height / 2) + 'px';
effect.style.zIndex = '1000';
document.body.appendChild(effect);
setTimeout(() => {
effect.remove();
}, 2000);
}
showPowerupCollectionEffect() {
const effects = ['✨', '💫', '🌟'];
const randomEffect = effects[Math.floor(Math.random() * effects.length)];
const effect = document.createElement('div');
effect.className = 'powerup-effect';
effect.textContent = randomEffect;
effect.style.position = 'absolute';
effect.style.left = '50%';
effect.style.top = '30%';
effect.style.transform = 'translateX(-50%)';
document.body.appendChild(effect);
setTimeout(() => {
effect.remove();
}, 2000);
}
}
// Sound Effects (Web Audio API)
class SoundManager {
constructor() {
this.audioContext = null;
this.sounds = {};
this.init();
}
init() {
try {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
} catch (error) {
console.log('Web Audio API not supported');
}
}
playTone(frequency, duration, type = 'sine') {
if (!this.audioContext) return;
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
oscillator.frequency.value = frequency;
oscillator.type = type;
gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + duration);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + duration);
}
playSuccess() {
this.playTone(523.25, 0.2); // C5
setTimeout(() => this.playTone(659.25, 0.2), 100); // E5
setTimeout(() => this.playTone(783.99, 0.3), 200); // G5
}
playError() {
this.playTone(220, 0.5, 'sawtooth'); // A3
}
playVictory() {
const notes = [523.25, 659.25, 783.99, 1046.50]; // C5, E5, G5, C6
notes.forEach((note, index) => {
setTimeout(() => this.playTone(note, 0.3), index * 150);
});
}
}
// Initialize Game
document.addEventListener('DOMContentLoaded', () => {
window.typeKartGame = new TypeKartGame();
window.soundManager = new SoundManager();
// Add sound effects to typing
const originalHandleTyping = window.typeKartGame.handleTyping.bind(window.typeKartGame);
window.typeKartGame.handleTyping = function(e) {
const input = e.target.value;
const expectedText = this.currentText.substring(0, input.length);
if (input === expectedText && input.length > 0) {
// Play success sound for correct typing
if (input.length % 5 === 0) {
window.soundManager.playSuccess();
}
} else if (input.length > 0 && input !== expectedText) {
// Play error sound for incorrect typing
window.soundManager.playError();
}
originalHandleTyping(e);
};
// Add victory sound to finish race
const originalFinishRace = window.typeKartGame.finishRace.bind(window.typeKartGame);
window.typeKartGame.finishRace = function(winner) {
if (winner === 'player') {
window.soundManager.playVictory();
}
originalFinishRace(winner);
};
console.log('🏁 Type Kart game initialized! Choose your racer and start typing! 🏎️');
});