Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
912 lines (810 loc) · 31 KB
/
Copy pathgame.js
File metadata and controls
912 lines (810 loc) · 31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
document.addEventListener("DOMContentLoaded", () => {
let data = [];
let activeData = [];
let currentAircraft;
let difficulty;
let mode;
let score = 0;
let total = 0;
let highScore = 0;
let usedAircraft = [];
let aircraftQueue = [];
let timerInterval;
let timeLeft = 60;
let gameOver = false;
// Streak & multiplier
let streak = 0;
let sessionBestStreak = 0;
let multiplier = 1;
let correctCount = 0;
// Daily challenge
let isDaily = false;
let dailyAnswers = [];
// Recap of planes missed in the current session (used for end-of-game review)
let sessionMissed = [];
// Lifetime stats
let lifeStats = JSON.parse(localStorage.getItem("planeguessrLifeStats")) || {
gamesPlayed: 0,
totalCorrect: 0,
totalAnswered: 0,
bestStreak: 0
};
// Widebody/narrowbody classification by family
const widebodyFamilies = new Set([
"A300", "A310", "A330", "A330neo", "A340", "A350", "A380",
"747", "767", "777", "777X", "787",
"C-17", "L-1011", "MD-11"
]);
// Cargo/freighter aircraft by model
const cargoModels = new Set([
"A300-600F", "A321P2F", "747-8F", "MD-11F", "C-17"
]);
const modeSelect = document.getElementById("mode-select");
const timeWrapper = document.getElementById("time-wrapper");
const difficultySelect = document.getElementById("difficulty-select");
const filterWrapper = document.getElementById("filter-wrapper");
const filterSelect = document.getElementById("filter-select");
function updateSettingsGrid() {
const grid = document.getElementById("settings-grid");
if (!grid) return;
const items = grid.children;
for (const item of items) {
item.style.gridColumn = "";
}
const visible = [...items].filter(i => i.style.display !== "none");
if (visible.length % 2 === 1) {
visible[visible.length - 1].style.gridColumn = "1 / -1";
}
}
modeSelect.addEventListener("change", () => {
timeWrapper.style.display = modeSelect.value === "timed" ? "" : "none";
updateSettingsGrid();
});
difficultySelect.addEventListener("change", () => {
if (difficultySelect.value === "easy") {
filterWrapper.style.display = "none";
if (filterSelect.value !== "all") {
filterSelect.value = "all";
filterSelect.dispatchEvent(new Event("change", { bubbles: true }));
}
} else {
filterWrapper.style.display = "";
}
updateSettingsGrid();
});
if (modeSelect.value !== "timed") {
timeWrapper.style.display = "none";
}
if (difficultySelect.value === "easy") {
filterWrapper.style.display = "none";
}
updateSettingsGrid();
// Initialize sound - corner toggle button
if (window.SoundManager) {
SoundManager.init();
const soundBtn = document.getElementById("sound-toggle-btn");
soundBtn.dataset.sound = SoundManager.isEnabled() ? "on" : "off";
soundBtn.addEventListener("click", () => {
const next = !SoundManager.isEnabled();
SoundManager.setEnabled(next);
soundBtn.dataset.sound = next ? "on" : "off";
});
}
renderLifeStats();
fetch("aircraft-data.json")
.then(res => res.json())
.then(json => {
const required = ["manufacturer", "family", "model", "image"];
data = json.filter(entry => {
const ok = entry && required.every(k => typeof entry[k] === "string" && entry[k].length > 0);
if (!ok) console.warn("Skipping invalid aircraft entry:", entry);
return ok;
});
document.querySelector('button[onclick="startGame()"]')?.removeAttribute("disabled");
document.getElementById("daily-card")?.removeAttribute("disabled");
document.querySelectorAll(".preset-btn").forEach(b => b.removeAttribute("disabled"));
updateDailyCard();
})
.catch(error => {
console.error("Error loading JSON:", error);
const statusEl = document.getElementById("daily-card-status");
if (statusEl) statusEl.innerText = "Couldn't load aircraft data. Refresh to retry.";
});
// Preset configurations
const presets = {
quick: { difficulty: "normal", mode: "timed", time: "30", filter: "passenger" },
hardcore: { difficulty: "hard", mode: "normal", time: "30", filter: "all" },
manufacturers: { difficulty: "easy", mode: "normal", time: "30", filter: "all" }
};
function applyPreset(name) {
const p = presets[name];
if (!p) return;
const set = (id, val) => {
const el = document.getElementById(id);
if (!el) return;
el.value = val;
el.dispatchEvent(new Event("change", { bubbles: true }));
};
set("difficulty-select", p.difficulty);
set("mode-select", p.mode);
set("time-select", p.time);
set("filter-select", p.filter);
}
document.querySelectorAll(".preset-btn").forEach(btn => {
btn.addEventListener("click", () => {
if (btn.disabled) return;
applyPreset(btn.dataset.preset);
startGame();
});
});
// --- Multiplier tiers ---
function getMultiplier(s) {
if (s >= 10) return 4;
if (s >= 6) return 3;
if (s >= 3) return 2;
return 1;
}
// --- Streak & multiplier UI ---
function updateStreak() {
const streakContainer = document.getElementById("streak-container");
const streakEl = document.getElementById("streak");
if (streak >= 2) {
streakContainer.style.display = "";
streakEl.innerText = "\u{1F525} " + streak;
} else {
streakContainer.style.display = "none";
}
multiplier = getMultiplier(streak);
const multContainer = document.getElementById("multiplier-container");
const multEl = document.getElementById("multiplier");
if (multiplier > 1 && mode === "timed") {
multContainer.style.display = "";
multEl.innerText = "\u00D7" + multiplier;
} else {
multContainer.style.display = "none";
}
}
// --- Lifetime stats ---
function renderLifeStats() {
document.getElementById("stat-games").innerText = lifeStats.gamesPlayed;
document.getElementById("stat-streak").innerText = lifeStats.bestStreak;
if (lifeStats.totalAnswered > 0) {
const pct = Math.round((lifeStats.totalCorrect / lifeStats.totalAnswered) * 100);
document.getElementById("stat-accuracy").innerText = pct + "%";
} else {
document.getElementById("stat-accuracy").innerText = "\u00b7";
}
const streakData = JSON.parse(localStorage.getItem("planeguessrDailyStreak") || '{"current":0}');
document.getElementById("stat-daily-streak").innerText = streakData.current;
}
function saveLifeStats() {
lifeStats.gamesPlayed++;
lifeStats.totalCorrect += correctCount;
lifeStats.totalAnswered += total;
if (sessionBestStreak > lifeStats.bestStreak) {
lifeStats.bestStreak = sessionBestStreak;
}
localStorage.setItem("planeguessrLifeStats", JSON.stringify(lifeStats));
renderLifeStats();
}
// --- Game start ---
window.startGame = function () {
document.getElementById("start-screen").style.display = "none";
const gameScreen = document.getElementById("game-screen");
gameScreen.style.display = "block";
gameScreen.classList.remove("screen-fade");
void gameScreen.offsetWidth;
gameScreen.classList.add("screen-fade");
document.getElementById("score-row").style.display = "";
difficulty = document.getElementById("difficulty-select").value;
mode = document.getElementById("mode-select").value;
// Apply filter
const filter = document.getElementById("filter-select").value;
if (filter === "all" || difficulty === "easy") {
activeData = data;
} else if (filter === "widebody") {
activeData = data.filter(ac => widebodyFamilies.has(ac.family));
} else if (filter === "narrowbody") {
activeData = data.filter(ac => !widebodyFamilies.has(ac.family));
} else if (filter === "cargo") {
activeData = data.filter(ac => cargoModels.has(ac.model));
} else if (filter === "passenger") {
activeData = data.filter(ac => !cargoModels.has(ac.model));
} else {
activeData = data.filter(ac => ac.manufacturer === filter);
}
// Load mode-specific high score
const hsKey = mode === "timed" ? "planeguessrHighScoreTimed" : "planeguessrHighScore";
highScore = parseInt(localStorage.getItem(hsKey)) || 0;
document.getElementById("high-score").innerText = highScore;
score = 0;
total = 0;
correctCount = 0;
streak = 0;
sessionBestStreak = 0;
multiplier = 1;
usedAircraft = [];
sessionMissed = [];
aircraftQueue = buildShuffledDeck(activeData);
gameOver = false;
hideRecap();
updateScore();
updateStreak();
if (mode === "timed") {
const selectedTime = parseInt(document.getElementById("time-select")?.value || "60", 10);
timeLeft = selectedTime;
const totalTime = selectedTime;
document.getElementById("timer").innerText = `${timeLeft}s`;
document.getElementById("timer").style.color = "";
document.getElementById("timer-container").style.display = "";
document.getElementById("timer-bar-wrapper").style.display = "block";
document.getElementById("timer-bar").style.width = "100%";
document.getElementById("timer-bar").style.backgroundColor = "";
timerInterval = setInterval(() => {
timeLeft--;
document.getElementById("timer").innerText = `${timeLeft}s`;
const pct = (timeLeft / totalTime) * 100;
document.getElementById("timer-bar").style.width = `${pct}%`;
if (timeLeft <= 10) {
document.getElementById("timer").style.color = "#e94560";
document.getElementById("timer-bar").style.backgroundColor = "#e94560";
}
if (timeLeft <= 0) {
clearInterval(timerInterval);
endTimedGame();
}
}, 1000);
} else {
document.getElementById("timer-container").style.display = "none";
document.getElementById("timer-bar-wrapper").style.display = "none";
}
nextRound();
};
function endTimedGame() {
gameOver = true;
hideNextControl();
saveLifeStats();
if (window.SoundManager) {
SoundManager.play(total > 0 && correctCount / total >= 0.7 ? "gameEndGood" : "gameEndBad");
}
document.getElementById("timer-container").style.display = "none";
document.getElementById("timer-bar-wrapper").style.display = "none";
const accuracy = total > 0 ? Math.round((correctCount / total) * 100) : 0;
const html = `
<div class="recap-block">
<div class="recap-title">Time's up!</div>
<div class="recap-subtitle">${correctCount}/${total} correct · ${score} pts · ${accuracy}% accuracy</div>
${renderMissedHtml(sessionMissed)}
</div>
`;
showRecap(html);
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, ch => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'"
}[ch]));
}
function renderMissedHtml(missed) {
if (!missed || missed.length === 0) return "";
const rows = missed.map(m => `
<div class="missed-row">
<img src="${escapeHtml(m.image)}" alt="" class="missed-thumb" loading="lazy">
<div class="missed-info">
<div class="missed-correct">${escapeHtml(m.correctAnswer)}</div>
<div class="missed-user">You said: <strong>${escapeHtml(m.userAnswer)}</strong></div>
</div>
</div>
`).join("");
return `<div class="missed-planes">
<div class="missed-title">Planes you missed (${missed.length})</div>
<div class="missed-list">${rows}</div>
</div>`;
}
function showRecap(html) {
const recap = document.getElementById("results-recap");
const imgWrapper = document.getElementById("aircraft-img").parentElement;
const choices = document.getElementById("choices");
const feedback = document.getElementById("feedback");
if (!recap) return;
feedback.innerHTML = "";
feedback.classList.remove("text-3xl");
if (imgWrapper) imgWrapper.style.display = "none";
if (choices) choices.innerHTML = "";
hideNextControl();
hideImageLoadingHint();
recap.innerHTML = html;
recap.style.display = "";
}
function hideRecap() {
const recap = document.getElementById("results-recap");
if (recap) { recap.style.display = "none"; recap.innerHTML = ""; }
const imgWrapper = document.getElementById("aircraft-img")?.parentElement;
if (imgWrapper) imgWrapper.style.display = "";
}
let imgLoadingTimer = null;
function showImageLoadingHint() {
const hint = document.getElementById("img-loading-text");
if (hint) hint.style.display = "";
}
function hideImageLoadingHint() {
if (imgLoadingTimer !== null) { clearTimeout(imgLoadingTimer); imgLoadingTimer = null; }
const hint = document.getElementById("img-loading-text");
if (hint) hint.style.display = "none";
}
let nextControlTimer = null;
function showNextControl(autoDelay) {
const controls = document.getElementById("next-controls");
const btn = document.getElementById("next-btn");
if (!controls || !btn) { setTimeout(nextRound, autoDelay); return; }
controls.style.display = "";
const advance = () => {
if (nextControlTimer !== null) { clearTimeout(nextControlTimer); nextControlTimer = null; }
btn.onclick = null;
controls.style.display = "none";
nextRound();
};
btn.onclick = advance;
nextControlTimer = setTimeout(advance, autoDelay);
}
function hideNextControl() {
if (nextControlTimer !== null) { clearTimeout(nextControlTimer); nextControlTimer = null; }
const controls = document.getElementById("next-controls");
if (controls) controls.style.display = "none";
const btn = document.getElementById("next-btn");
if (btn) btn.onclick = null;
}
function nextRound() {
if (gameOver) return;
hideNextControl();
const feedback = document.getElementById("feedback");
feedback.innerText = "";
feedback.classList.remove("text-3xl");
if (aircraftQueue.length === 0) {
if (isDaily) {
endDailyGame();
} else {
document.getElementById("feedback").innerText = "You've seen all aircraft! More will be added soon. GG";
if (window.SoundManager) {
SoundManager.play(total > 0 && correctCount / total >= 0.7 ? "gameEndGood" : "gameEndBad");
}
}
return;
}
currentAircraft = aircraftQueue.shift();
usedAircraft.push(currentAircraft.model);
const img = document.getElementById("aircraft-img");
img.classList.remove("loaded");
hideImageLoadingHint();
imgLoadingTimer = setTimeout(showImageLoadingHint, 1500);
img.onload = () => {
img.classList.add("loaded");
hideImageLoadingHint();
};
img.onerror = () => {
console.warn("Failed to load aircraft image:", currentAircraft.image);
img.classList.add("loaded");
hideImageLoadingHint();
};
img.alt = "Aircraft";
img.src = currentAircraft.image;
const correctAnswer = getCorrectAnswer();
const answers = generateAnswers(correctAnswer);
displayChoices(answers, correctAnswer);
}
function getCorrectAnswer() {
if (difficulty === "easy") return currentAircraft.manufacturer;
if (difficulty === "normal") return currentAircraft.family;
return currentAircraft.model;
}
function generateAnswers(correctAnswer) {
let answers = activeData.map(ac => {
if (difficulty === "easy") return ac.manufacturer;
if (difficulty === "normal") return ac.family;
return ac.model;
});
answers = [...new Set(answers.filter(a => a !== correctAnswer))];
if (difficulty === "easy") {
const manufacturers = [...new Set(activeData.map(ac => ac.manufacturer))];
if (manufacturers.length <= 4) {
answers = [...manufacturers];
} else {
answers = manufacturers.filter(m => m !== correctAnswer);
shuffleArray(answers);
answers = answers.slice(0, 3);
answers.push(correctAnswer);
}
shuffleArray(answers);
} else {
shuffleArray(answers);
answers = answers.slice(0, 3);
answers.push(correctAnswer);
shuffleArray(answers);
}
return answers;
}
function displayChoices(answers, correctAnswer) {
const choicesDiv = document.getElementById("choices");
choicesDiv.innerHTML = "";
answers.forEach((choice, i) => {
const btn = document.createElement("button");
btn.innerHTML = `<span style="opacity:0.4;margin-right:6px;font-size:0.8em;">${i + 1}</span>${choice}`;
btn.className = "choice-btn";
btn.dataset.answer = choice;
btn.disabled = false;
btn.onclick = () => {
document.querySelectorAll(".choice-btn").forEach(b => b.disabled = true);
checkAnswer(choice, correctAnswer, btn);
};
choicesDiv.appendChild(btn);
});
}
function checkAnswer(choice, correctAnswer, clickedBtn) {
total++;
const feedback = document.getElementById("feedback");
const buttons = document.querySelectorAll(".choice-btn");
buttons.forEach(btn => {
if (btn.dataset.answer === correctAnswer) {
btn.classList.add("correct");
}
if (btn === clickedBtn && choice !== correctAnswer) {
btn.classList.add("wrong");
}
});
if (choice === correctAnswer) {
correctCount++;
streak++;
if (streak > sessionBestStreak) sessionBestStreak = streak;
updateStreak();
if (isDaily) dailyAnswers.push(true);
if (window.SoundManager) {
if ([3, 6, 10].includes(streak)) SoundManager.play("milestone");
else SoundManager.play("correct");
}
const points = (mode === "timed") ? multiplier : 1;
score += points;
if (points > 1) {
feedback.innerHTML = `<span style="color:#4ade80;">✓ Correct!</span> <span style="color:#eab308;">+${points}</span>`;
} else {
feedback.innerHTML = '<span style="color:#4ade80;">✓ Correct!</span>';
}
const countEl = document.getElementById("correct-count");
countEl.classList.remove("score-pop");
void countEl.offsetWidth;
countEl.classList.add("score-pop");
if (mode === "timed") {
const scoreEl = document.getElementById("score");
scoreEl.classList.remove("score-pop");
void scoreEl.offsetWidth;
scoreEl.classList.add("score-pop");
}
updateScore();
setTimeout(() => nextRound(), mode === "timed" ? 400 : 1000);
} else {
streak = 0;
updateStreak();
if (isDaily) dailyAnswers.push(false);
sessionMissed.push({
image: currentAircraft.image,
correctAnswer: correctAnswer,
userAnswer: choice,
model: currentAircraft.model
});
if (window.SoundManager) SoundManager.play("wrong");
feedback.innerHTML = `<span style="color:#f87171;">✗ Wrong!</span> <span style="color:#888;margin-left:4px;">The answer was</span> <span style="color:#eaeaea;font-weight:700;">${correctAnswer}</span>`;
updateScore();
if (mode === "timed") {
setTimeout(() => nextRound(), 600);
} else {
showNextControl(4000);
}
}
}
function updateScore() {
document.getElementById("correct-count").innerText = correctCount;
document.getElementById("total").innerText = total;
document.getElementById("score").innerText = score;
// Show points separately in timed mode
document.getElementById("points-container").style.display = (mode === "timed") ? "" : "none";
if (score > highScore) {
highScore = score;
const hsKey = mode === "timed" ? "planeguessrHighScoreTimed" : "planeguessrHighScore";
localStorage.setItem(hsKey, highScore);
document.getElementById("high-score").innerText = highScore;
}
}
function doReset() {
if (isDaily && total > 0 && !gameOver) {
while (dailyAnswers.length < 10) dailyAnswers.push(false);
const today = getTodayString();
localStorage.setItem("planeguessrDaily", JSON.stringify({
date: today, answers: dailyAnswers, correctCount: correctCount, missed: sessionMissed, completed: true
}));
updateDailyStreak(today);
}
if (total > 0 && !gameOver) {
saveLifeStats();
}
hideNextControl();
hideImageLoadingHint();
document.getElementById("game-screen").style.display = "none";
const startScreen = document.getElementById("start-screen");
startScreen.style.display = "block";
startScreen.classList.remove("screen-fade");
void startScreen.offsetWidth;
startScreen.classList.add("screen-fade");
clearInterval(timerInterval);
gameOver = false;
isDaily = false;
dailyAnswers = [];
updateSettingsGrid();
updateDailyCard();
}
window.resetGame = function () {
if (isDaily && total > 0 && !gameOver) {
const remaining = 10 - total;
showQuitConfirm(remaining, doReset);
return;
}
doReset();
};
function showQuitConfirm(remaining, onConfirm) {
const modal = document.getElementById("confirm-modal");
const msg = document.getElementById("confirm-msg");
const cancel = document.getElementById("confirm-cancel");
const quit = document.getElementById("confirm-quit");
if (!modal || !msg || !cancel || !quit) { onConfirm(); return; }
msg.innerText = `${remaining} remaining plane${remaining === 1 ? " will" : "s will"} count as wrong, and this will be locked in as today's attempt.`;
modal.style.display = "flex";
const close = () => {
modal.style.display = "none";
cancel.onclick = null;
quit.onclick = null;
modal.onclick = null;
document.removeEventListener("keydown", onKey);
};
const onKey = (e) => {
if (e.key === "Escape") { e.preventDefault(); close(); }
};
cancel.onclick = close;
quit.onclick = () => { close(); onConfirm(); };
modal.onclick = (e) => { if (e.target === modal) close(); };
document.addEventListener("keydown", onKey);
}
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Build a shuffled deck where the same manufacturer never appears back-to-back.
// Groups aircraft by manufacturer, shuffles each group, then uses weighted
// random selection - always picking from a different manufacturer than the last,
// proportional to how many of that manufacturer remain (so share is preserved).
function buildShuffledDeck(aircraft) {
const groups = {};
for (const ac of aircraft) {
if (!groups[ac.manufacturer]) groups[ac.manufacturer] = [];
groups[ac.manufacturer].push(ac);
}
for (const mfr in groups) shuffleArray(groups[mfr]);
const result = [];
let lastMfr = null;
while (true) {
const piles = Object.values(groups).filter(p => p.length > 0);
if (piles.length === 0) break;
// Prefer different manufacturer than last; fall back to same if no choice
const available = piles.filter(p => p[0].manufacturer !== lastMfr);
const pool = available.length > 0 ? available : piles;
// Weighted random: larger piles are proportionally more likely
const total = pool.reduce((s, p) => s + p.length, 0);
let r = Math.random() * total;
let chosen = pool[pool.length - 1];
for (const pile of pool) {
r -= pile.length;
if (r <= 0) { chosen = pile; break; }
}
const ac = chosen.shift();
result.push(ac);
lastMfr = ac.manufacturer;
}
return result;
}
// --- Seeded PRNG (for daily challenge) ---
function mulberry32(a) {
return function () {
a |= 0; a = a + 0x6D2B79F5 | 0;
var t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
function getTodayString() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
function getDailyNumber() {
const epoch = new Date(2025, 0, 1);
const today = new Date();
today.setHours(0, 0, 0, 0);
return Math.floor((today - epoch) / 86400000);
}
function getDailyAircraft(allData) {
const seed = hashString(getTodayString());
const rng = mulberry32(seed);
const shuffled = allData.slice();
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled.slice(0, 10);
}
// --- Daily challenge functions ---
function updateDailyCard() {
const dayEl = document.getElementById("daily-card-day");
const statusEl = document.getElementById("daily-card-status");
const streakEl = document.getElementById("daily-card-streak");
if (!dayEl) return;
dayEl.innerText = "#" + getDailyNumber();
const saved = JSON.parse(localStorage.getItem("planeguessrDaily") || "null");
if (saved && saved.date === getTodayString() && saved.completed) {
statusEl.innerText = `Completed \u2713 ${saved.correctCount}/10 \u00b7 tap to view`;
} else {
statusEl.innerText = "10 planes, same for everyone today";
}
const sd = JSON.parse(localStorage.getItem("planeguessrDailyStreak") || '{"current":0}');
streakEl.innerText = sd.current > 0 ? `\u{1F525} ${sd.current}-day streak` : "";
}
function updateDailyStreak(today) {
const stored = JSON.parse(localStorage.getItem("planeguessrDailyStreak") || '{"current":0,"lastDate":""}');
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, "0")}-${String(yesterday.getDate()).padStart(2, "0")}`;
if (stored.lastDate === yesterdayStr) {
stored.current++;
} else if (stored.lastDate !== today) {
stored.current = 1;
}
stored.lastDate = today;
localStorage.setItem("planeguessrDailyStreak", JSON.stringify(stored));
renderLifeStats();
}
function showDailyResults(state) {
document.getElementById("start-screen").style.display = "none";
const gameScreen = document.getElementById("game-screen");
gameScreen.style.display = "block";
gameScreen.classList.remove("screen-fade");
void gameScreen.offsetWidth;
gameScreen.classList.add("screen-fade");
const dayNum = getDailyNumber();
const grid = state.answers.map(a => a ? "\u{1F7E9}" : "\u{1F7E5}").join("");
const streakData = JSON.parse(localStorage.getItem("planeguessrDailyStreak") || '{"current":0}');
document.getElementById("timer-container").style.display = "none";
document.getElementById("timer-bar-wrapper").style.display = "none";
document.getElementById("points-container").style.display = "none";
document.getElementById("score-row").style.display = "none";
document.getElementById("correct-count").innerText = state.correctCount;
document.getElementById("total").innerText = "10";
const html = `
<div class="recap-block">
<div class="recap-title">Daily #${dayNum}: ${state.correctCount}/10</div>
<div class="recap-grid">${grid}</div>
${streakData.current > 0 ? `<div class="recap-streak">\u{1F525} ${streakData.current}-day streak</div>` : ""}
<button onclick="shareDaily()" id="share-btn" class="recap-share">Share Result</button>
${renderMissedHtml(state.missed)}
</div>
`;
showRecap(html);
}
function endDailyGame() {
gameOver = true;
hideNextControl();
saveLifeStats();
const today = getTodayString();
const dailyState = {
date: today,
answers: dailyAnswers,
correctCount: correctCount,
missed: sessionMissed,
completed: true
};
localStorage.setItem("planeguessrDaily", JSON.stringify(dailyState));
updateDailyStreak(today);
if (window.SoundManager) {
SoundManager.play(correctCount / 10 >= 0.7 ? "gameEndGood" : "gameEndBad");
}
showDailyResults(dailyState);
}
window.startDaily = function () {
// Check if already completed today
const saved = JSON.parse(localStorage.getItem("planeguessrDaily") || "null");
if (saved && saved.date === getTodayString() && saved.completed) {
showDailyResults(saved);
return;
}
isDaily = true;
dailyAnswers = [];
// Switch screens
document.getElementById("start-screen").style.display = "none";
const gameScreen = document.getElementById("game-screen");
gameScreen.style.display = "block";
gameScreen.classList.remove("screen-fade");
void gameScreen.offsetWidth;
gameScreen.classList.add("screen-fade");
document.getElementById("score-row").style.display = "";
// Force normal difficulty, normal mode
difficulty = "normal";
mode = "normal";
// Generate seeded aircraft for today
activeData = getDailyAircraft(data);
// Standard game init
highScore = 0;
document.getElementById("high-score").innerText = "\u00b7";
score = 0;
total = 0;
correctCount = 0;
streak = 0;
sessionBestStreak = 0;
multiplier = 1;
usedAircraft = [];
sessionMissed = [];
aircraftQueue = activeData.slice(); // daily uses seeded order as-is
gameOver = false;
hideRecap();
updateScore();
updateStreak();
document.getElementById("timer-container").style.display = "none";
document.getElementById("timer-bar-wrapper").style.display = "none";
nextRound();
};
function getDailyQuip(correct) {
if (correct === 10) return "Perfect score! Born to fly. \u{1F3C6}";
if (correct >= 8) return "Strong work! You know your planes. \u2708\uFE0F";
if (correct >= 6) return "Not bad for a passenger! \u{1F6E9}\uFE0F";
if (correct >= 4) return "Tricky skies today. \u{1F605}";
return "Every pilot starts somewhere. \u{1F6EB}";
}
window.shareDaily = function () {
const state = JSON.parse(localStorage.getItem("planeguessrDaily"));
if (!state) return;
const dayNum = getDailyNumber();
const grid = state.answers.map(a => a ? "\u{1F7E9}" : "\u{1F7E5}").join("");
const quip = getDailyQuip(state.correctCount);
const text = `\u2708\uFE0F PlaneGuessr Daily #${dayNum}\n${grid} ${state.correctCount}/10\n${quip}\nplaneguessr.com`;
const btn = document.getElementById("share-btn");
const onSuccess = () => {
if (btn) {
btn.innerText = "Copied! \u2713";
setTimeout(() => { btn.innerText = "Share Result"; }, 2000);
}
};
const onFailure = () => {
if (btn) btn.innerText = "Copy failed, long-press to copy";
window.prompt("Copy your result:", text);
};
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(onSuccess).catch(onFailure);
} else {
onFailure();
}
};
document.addEventListener("keydown", (e) => {
const key = e.key;
const buttons = Array.from(document.querySelectorAll(".choice-btn"));
if (["1", "2", "3", "4"].includes(key)) {
const index = parseInt(key) - 1;
if (index < buttons.length && !buttons[index].disabled) {
const btn = buttons[index];
btn.classList.add("pressed");
btn.click();
}
}
});
});