-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreaction_game.html
More file actions
904 lines (793 loc) · 24.7 KB
/
reaction_game.html
File metadata and controls
904 lines (793 loc) · 24.7 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Latin Reaction Game</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1100px;
margin: 2rem auto;
padding: 0 1rem;
}
h1 {
margin-bottom: 0.5rem;
}
.muted {
color: #666;
}
.selectors {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin: 1rem 0;
}
@media (max-width: 900px) {
.selectors {
grid-template-columns: 1fr;
}
}
label {
display: block;
font-weight: 600;
margin-bottom: 0.35rem;
}
select,
button {
font: inherit;
width: 100%;
padding: 0.55rem;
}
.actions {
display: flex;
gap: 0.75rem;
margin-bottom: 1rem;
}
.actions button {
width: auto;
cursor: pointer;
}
.status {
margin-bottom: 0.75rem;
}
.error {
color: #b00020;
}
.stats {
margin-bottom: 0.75rem;
font-weight: 600;
}
.highscores {
margin-bottom: 0.9rem;
border: 1px solid #d8d8d8;
border-radius: 8px;
background: #fafafa;
padding: 0.75rem;
}
.highscores h2 {
margin: 0 0 0.4rem 0;
font-size: 1rem;
}
.highscores ol {
margin: 0;
padding-left: 1.2rem;
}
.highscores li {
margin: 0.2rem 0;
}
.game-wrap {
position: relative;
border: 1px solid #d8d8d8;
border-radius: 10px;
background: #f8f8f8;
min-height: 520px;
overflow: hidden;
}
.playfield {
position: relative;
height: 420px;
overflow: hidden;
}
.falling-word {
position: absolute;
transform: translateX(-50%);
border: 1px solid #cfcfcf;
border-radius: 999px;
background: #ffffff;
padding: 0.35rem 0.75rem;
width: auto;
max-width: 80%;
cursor: pointer;
white-space: nowrap;
user-select: none;
}
.falling-word:hover {
background: #f0f0f0;
}
.prompt {
border-top: 1px solid #dedede;
background: #efefef;
padding: 0.9rem 1rem;
}
.prompt .label {
font-size: 0.92rem;
color: #555;
}
.prompt .word {
font-size: 1.45rem;
font-weight: 700;
margin-top: 0.25rem;
}
.hint {
margin-top: 0.25rem;
color: #666;
}
</style>
</head>
<body>
<h1>Latin Reaction Game</h1>
<p><a id="backLink" href="index.html">← Back to index</a></p>
<p class="muted">
A prompt appears at the bottom. Click the matching dropping word before it
vanishes.
</p>
<div class="selectors">
<div>
<label for="schoolSelect">School</label>
<select id="schoolSelect" disabled>
<option>Loading...</option>
</select>
</div>
<div>
<label for="yearSelect">Year</label>
<select id="yearSelect" disabled>
<option>Select school first</option>
</select>
</div>
<div>
<label for="chapterSelect">Chapter</label>
<select id="chapterSelect" disabled>
<option>Select year first</option>
</select>
</div>
<div>
<label for="sectionSelect">Section</label>
<select id="sectionSelect" disabled>
<option>Select chapter first</option>
</select>
</div>
<div>
<label for="scopeSelect">Play scope</label>
<select id="scopeSelect">
<option value="section" selected>Selected section</option>
<option value="chapter">Whole chapter</option>
</select>
</div>
</div>
<div class="actions">
<button type="button" id="startBtn" disabled>Start game</button>
<button type="button" id="stopBtn" disabled>Stop</button>
</div>
<div id="status" class="status muted"></div>
<div id="stats" class="stats"></div>
<section class="highscores" aria-live="polite">
<h2>Top 3 Highscores</h2>
<ol id="highscoresList">
<li>-</li>
</ol>
</section>
<section class="game-wrap" aria-live="polite">
<div id="playfield" class="playfield"></div>
<div class="prompt">
<div class="label" id="promptLabel">Prompt</div>
<div class="word" id="promptWord">-</div>
<div class="hint">Click the matching Dutch translation above.</div>
</div>
</section>
<script>
const API_URL = "api/section_words.php";
const schoolSelect = document.getElementById("schoolSelect");
const yearSelect = document.getElementById("yearSelect");
const chapterSelect = document.getElementById("chapterSelect");
const sectionSelect = document.getElementById("sectionSelect");
const scopeSelect = document.getElementById("scopeSelect");
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const backLink = document.getElementById("backLink");
const status = document.getElementById("status");
const stats = document.getElementById("stats");
const highscoresList = document.getElementById("highscoresList");
const playfield = document.getElementById("playfield");
const promptLabel = document.getElementById("promptLabel");
const promptWord = document.getElementById("promptWord");
const GAME_KEY = "reaction";
let structure = null;
let wordPairs = [];
let currentPair = null;
let particles = [];
let score = 0;
let misses = 0;
let running = false;
let lastFrameTime = 0;
let spawnAccumulator = 0;
let animationFrameId = 0;
let activePromptVersion = 0;
let highscores = [];
function setStatus(text, isError = false) {
status.textContent = text;
status.className = isError ? "status error" : "status muted";
}
function fillSelect(selectEl, items, placeholder) {
selectEl.innerHTML = "";
if (!items.length) {
const option = document.createElement("option");
option.value = "";
option.textContent = placeholder;
selectEl.appendChild(option);
selectEl.disabled = true;
return;
}
const chooseOption = document.createElement("option");
chooseOption.value = "";
chooseOption.textContent = "Choose...";
selectEl.appendChild(chooseOption);
items.forEach((item) => {
const option = document.createElement("option");
option.value = item;
option.textContent = item;
selectEl.appendChild(option);
});
selectEl.disabled = false;
}
function sortedKeys(obj) {
return Object.keys(obj || {}).sort((a, b) =>
a.localeCompare(b, undefined, { sensitivity: "base", numeric: true }),
);
}
function updateStats() {
const speedMultiplier = getSpeedMultiplier().toFixed(2);
stats.textContent = `Score: ${score} | Misses: ${misses} | Speed x${speedMultiplier}`;
}
function currentSelection() {
return {
school: schoolSelect.value,
year: yearSelect.value,
chapter: chapterSelect.value,
section: sectionSelect.value,
};
}
function updateStartButtonAvailability() {
const scope = scopeSelect.value;
const hasChapter = !!(
schoolSelect.value &&
yearSelect.value &&
chapterSelect.value
);
if (scope === "chapter") {
startBtn.disabled = !hasChapter;
return;
}
startBtn.disabled = !(hasChapter && sectionSelect.value);
}
function updateBackLink() {
const selection = currentSelection();
const params = new URLSearchParams();
if (selection.school) {
params.set("school", selection.school);
}
if (selection.year) {
params.set("year", selection.year);
}
if (selection.chapter) {
params.set("chapter", selection.chapter);
}
if (selection.section) {
params.set("section", selection.section);
}
backLink.href = params.toString()
? `index.html?${params.toString()}`
: "index.html";
}
function renderHighscores() {
highscoresList.innerHTML = "";
if (!highscores.length) {
highscoresList.innerHTML = "<li>No highscores yet.</li>";
return;
}
highscores.forEach((entry) => {
const li = document.createElement("li");
const name = entry.name || "Unknown";
const entryScore = Number(entry.score || 0);
li.textContent = `${name} — ${entryScore}`;
highscoresList.appendChild(li);
});
}
function isTopThreeScore(candidateScore) {
if (highscores.length < 3) {
return true;
}
const lastScore = Number(highscores[highscores.length - 1].score || 0);
return candidateScore > lastScore;
}
async function loadHighscores() {
const selection = currentSelection();
if (
!selection.school ||
!selection.year ||
!selection.chapter ||
!selection.section
) {
highscores = [];
renderHighscores();
return;
}
const params = new URLSearchParams({
action: "highscores_get",
game: GAME_KEY,
school: selection.school,
year: selection.year,
chapter: selection.chapter,
section: selection.section,
});
try {
const response = await fetch(`${API_URL}?${params.toString()}`, {
cache: "no-store",
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || `HTTP ${response.status}`);
}
highscores = Array.isArray(data.scores) ? data.scores : [];
renderHighscores();
} catch {
highscores = [];
renderHighscores();
}
}
async function submitHighscoreIfEligible(finalScore) {
const selection = currentSelection();
if (
!selection.school ||
!selection.year ||
!selection.chapter ||
!selection.section
) {
return;
}
if (!isTopThreeScore(finalScore)) {
return;
}
const name = window.prompt("New top 3 score! Enter your name:", "");
if (!name || !name.trim()) {
return;
}
const params = new URLSearchParams({
action: "highscores_add",
game: GAME_KEY,
school: selection.school,
year: selection.year,
chapter: selection.chapter,
section: selection.section,
name: name.trim(),
score: String(finalScore),
});
try {
const response = await fetch(`${API_URL}?${params.toString()}`, {
cache: "no-store",
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || `HTTP ${response.status}`);
}
highscores = Array.isArray(data.scores) ? data.scores : [];
renderHighscores();
} catch {
// ignore highscore submit errors in gameplay flow
}
}
function clearParticles() {
particles.forEach((particle) => particle.el.remove());
particles = [];
}
function resetGameState() {
clearParticles();
score = 0;
misses = 0;
activePromptVersion = 0;
currentPair = null;
promptWord.textContent = "-";
updateStats();
}
function getSpeedMultiplier() {
return 1 + score * 0.08;
}
function getSpawnIntervalMs() {
const base = 1200;
const interval = base - score * 45;
return Math.max(350, interval);
}
function getDropPixelsPerSecond() {
const base = 45;
return base * getSpeedMultiplier();
}
function chooseNewPrompt() {
if (!wordPairs.length) {
currentPair = null;
promptWord.textContent = "-";
return;
}
const randomIndex = Math.floor(Math.random() * wordPairs.length);
currentPair = wordPairs[randomIndex];
activePromptVersion += 1;
promptWord.textContent = currentPair.latin;
}
function createParticle(text, isCorrectWord, promptVersion) {
const element = document.createElement("button");
element.type = "button";
element.className = "falling-word";
element.textContent = text;
const fieldWidth = playfield.clientWidth;
const x = 24 + Math.random() * Math.max(30, fieldWidth - 48);
element.style.left = `${x}px`;
element.style.top = `-26px`;
const particle = {
el: element,
text,
y: -26,
isCorrectWord,
promptVersion,
removed: false,
};
element.addEventListener("click", () => {
if (!running || particle.removed) {
return;
}
if (!currentPair) {
return;
}
if (
particle.isCorrectWord &&
particle.promptVersion === activePromptVersion
) {
score += 1;
setStatus("Correct!", false);
removeParticle(particle);
chooseNewPrompt();
} else {
misses += 1;
setStatus("Wrong word.", true);
removeParticle(particle);
}
updateStats();
if (misses >= 3) {
endRound("Game over. You reached 3 misses.");
}
});
playfield.appendChild(element);
particles.push(particle);
}
function removeParticle(particle) {
if (particle.removed) {
return;
}
particle.removed = true;
particle.el.remove();
}
function getDistractorTranslation(correctTranslation) {
const pool = wordPairs
.map((pair) => pair.nl)
.filter((translation) => translation !== correctTranslation);
if (!pool.length) {
return correctTranslation;
}
const index = Math.floor(Math.random() * pool.length);
return pool[index];
}
function spawnWords() {
if (!currentPair) {
return;
}
const targetFirst = Math.random() < 0.55;
const distractorCount = 2 + Math.floor(Math.random() * 2);
if (targetFirst) {
createParticle(currentPair.nl, true, activePromptVersion);
}
for (let index = 0; index < distractorCount; index += 1) {
const translation = getDistractorTranslation(currentPair.nl);
createParticle(translation, false, activePromptVersion);
}
if (!targetFirst) {
createParticle(currentPair.nl, true, activePromptVersion);
}
}
function gameLoop(timestamp) {
if (!running) {
return;
}
if (!lastFrameTime) {
lastFrameTime = timestamp;
}
const deltaMs = timestamp - lastFrameTime;
lastFrameTime = timestamp;
spawnAccumulator += deltaMs;
const dropSpeed = getDropPixelsPerSecond();
const maxY = playfield.clientHeight + 40;
particles.forEach((particle) => {
if (particle.removed) {
return;
}
particle.y += (dropSpeed * deltaMs) / 1000;
particle.el.style.top = `${particle.y}px`;
if (particle.y > maxY) {
if (
particle.isCorrectWord &&
particle.promptVersion === activePromptVersion
) {
misses += 1;
setStatus("Too slow, target vanished.", true);
chooseNewPrompt();
updateStats();
if (misses >= 3) {
endRound("Game over. You reached 3 misses.");
}
}
removeParticle(particle);
}
});
particles = particles.filter((particle) => !particle.removed);
const spawnInterval = getSpawnIntervalMs();
while (spawnAccumulator >= spawnInterval) {
spawnAccumulator -= spawnInterval;
spawnWords();
}
animationFrameId = requestAnimationFrame(gameLoop);
}
function stopGame(showMessage = true) {
running = false;
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = 0;
}
clearParticles();
stopBtn.disabled = true;
if (showMessage) {
setStatus("Game stopped.");
}
}
function endRound(message) {
if (!running) {
return;
}
const finalScore = score;
stopGame(false);
setStatus(message);
submitHighscoreIfEligible(finalScore);
}
function startGame() {
if (wordPairs.length < 3) {
setStatus(
"Need at least 3 words with Dutch translations in this section.",
true,
);
return;
}
stopGame(false);
resetGameState();
running = true;
stopBtn.disabled = false;
chooseNewPrompt();
setStatus("Game started. Click the matching Dutch translation.");
lastFrameTime = 0;
spawnAccumulator = 0;
animationFrameId = requestAnimationFrame(gameLoop);
}
async function loadStructure() {
try {
const response = await fetch(`${API_URL}?action=structure`, {
cache: "no-store",
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || `HTTP ${response.status}`);
}
structure = data;
fillSelect(
schoolSelect,
sortedKeys(structure.schools),
"No schools found",
);
fillSelect(yearSelect, [], "Select school first");
fillSelect(chapterSelect, [], "Select year first");
fillSelect(sectionSelect, [], "Select chapter first");
renderHighscores();
setStatus("Choose a section and click Start game.");
} catch (error) {
setStatus(`Could not load structure: ${error.message}`, true);
}
}
function clearSelectionGameData() {
stopGame(false);
resetGameState();
wordPairs = [];
highscores = [];
renderHighscores();
startBtn.disabled = true;
}
function updateYears() {
fillSelect(
yearSelect,
sortedKeys(structure?.schools?.[schoolSelect.value]),
"No years found",
);
fillSelect(chapterSelect, [], "Select year first");
fillSelect(sectionSelect, [], "Select chapter first");
clearSelectionGameData();
updateBackLink();
updateStartButtonAvailability();
}
function updateChapters() {
fillSelect(
chapterSelect,
sortedKeys(
structure?.schools?.[schoolSelect.value]?.[yearSelect.value],
),
"No chapters found",
);
fillSelect(sectionSelect, [], "Select chapter first");
clearSelectionGameData();
updateBackLink();
updateStartButtonAvailability();
}
function updateSections() {
fillSelect(
sectionSelect,
sortedKeys(
structure?.schools?.[schoolSelect.value]?.[yearSelect.value]?.[
chapterSelect.value
],
),
"No sections found",
);
clearSelectionGameData();
updateBackLink();
updateStartButtonAvailability();
}
async function loadSectionData() {
const school = schoolSelect.value;
const year = yearSelect.value;
const chapter = chapterSelect.value;
const section = sectionSelect.value;
const scope = scopeSelect.value;
if (!school || !year || !chapter || (scope === "section" && !section)) {
setStatus(
scope === "chapter"
? "Please choose school, year and chapter."
: "Please choose school, year, chapter and section.",
true,
);
return;
}
stopGame(false);
resetGameState();
setStatus("Loading section words...");
try {
const sectionsToLoad =
scope === "chapter"
? sortedKeys(structure?.schools?.[school]?.[year]?.[chapter])
: [section];
const sectionResponses = await Promise.all(
sectionsToLoad.map(async (sectionName) => {
const params = new URLSearchParams({
action: "section",
school,
year,
chapter,
section: sectionName,
});
const response = await fetch(`${API_URL}?${params.toString()}`, {
cache: "no-store",
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || `HTTP ${response.status}`);
}
return data;
}),
);
const combinedMap = new Map();
sectionResponses.forEach((data) => {
data.words.forEach((entry) => {
if (!entry.found || !entry.attributes || !entry.attributes.nl) {
return;
}
if (!combinedMap.has(entry.latin)) {
combinedMap.set(entry.latin, {
latin: entry.latin,
nl: entry.attributes.nl,
});
}
});
});
wordPairs = Array.from(combinedMap.values());
if (wordPairs.length < 3) {
startBtn.disabled = true;
setStatus(
"Need at least 3 words with translations for this game.",
true,
);
return;
}
startBtn.disabled = false;
setStatus(
scope === "chapter"
? `Loaded ${wordPairs.length} words from whole chapter. Click Start game.`
: `Loaded ${wordPairs.length} words. Click Start game.`,
);
await loadHighscores();
startGame();
} catch (error) {
startBtn.disabled = true;
setStatus(`Could not load section: ${error.message}`, true);
}
}
schoolSelect.addEventListener("change", updateYears);
yearSelect.addEventListener("change", updateChapters);
chapterSelect.addEventListener("change", updateSections);
sectionSelect.addEventListener("change", () => {
clearSelectionGameData();
updateStartButtonAvailability();
updateBackLink();
});
scopeSelect.addEventListener("change", () => {
clearSelectionGameData();
updateStartButtonAvailability();
});
startBtn.addEventListener("click", loadSectionData);
stopBtn.addEventListener("click", () => {
if (!running) {
stopGame(true);
return;
}
endRound("Game stopped.");
});
function applySelectionFromQuery() {
const params = new URLSearchParams(window.location.search);
const school = params.get("school") || "";
const year = params.get("year") || "";
const chapter = params.get("chapter") || "";
const section = params.get("section") || "";
if (
school &&
Array.from(schoolSelect.options).some((o) => o.value === school)
) {
schoolSelect.value = school;
updateYears();
}
if (
year &&
Array.from(yearSelect.options).some((o) => o.value === year)
) {
yearSelect.value = year;
updateChapters();
}
if (
chapter &&
Array.from(chapterSelect.options).some((o) => o.value === chapter)
) {
chapterSelect.value = chapter;
updateSections();
}
if (
section &&
Array.from(sectionSelect.options).some((o) => o.value === section)
) {
sectionSelect.value = section;
}
updateStartButtonAvailability();
updateBackLink();
}
loadStructure().then(applySelectionFromQuery);
</script>
</body>
</html>