Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
817 lines (698 loc) · 33.6 KB
/
Copy pathapp.js
File metadata and controls
817 lines (698 loc) · 33.6 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
// If you host the frontend on GitHub Pages, paste your Vercel backend URL here (e.g. "https://your-project.vercel.app")
// If you host both frontend and backend on Vercel, leave it empty "" to use a relative path.
const BACKEND_API_URL = "https://trivia-betting.vercel.app/";
// Global array for questions currently being played
let activeQuestions = [];
// Questions Database (Local Fallback - Sorted Easy to Hard)
const localFallbackQuestions = [
{
question: "เมืองหลวงของประเทศฝรั่งเศสคือเมืองอะไร?",
options: ["ปารีส", "ลอนดอน", "โรม", "มาดริด"],
answer: 0
},
{
question: "ดาวเคราะห์ดวงใดอยู่ใกล้ดวงอาทิตย์มากที่สุดในระบบสุริยะ?",
options: ["ดาวพุธ", "ดาวศุกร์", "โลก", "ดาวอังคาร"],
answer: 0
},
{
question: "แม่น้ำสายที่ยาวที่สุดในโลกคือแม่น้ำสายใด?",
options: ["แม่น้ำไนล์", "แม่น้ำอเมซอน", "แม่น้ำแยงซี", "แม่น้ำมิสซิสซิปปี"],
answer: 0
},
{
question: "ใครคือผู้ประดิษฐ์หลอดไฟคนแรกของโลก?",
options: ["โทมัส อัลวา เอดิสัน", "อัลเบิร์ต ไอน์สไตน์", "นิกโคลา เทสลา", "อเล็กซานเดอร์ เกรแฮม เบลล์"],
answer: 0
},
{
question: "สิ่งมีชีวิตใดเป็นสัตว์เลี้ยงลูกด้วยนมที่วางไข่ได้?",
options: ["ตุ่นปากเป็ด", "จิงโจ้", "ค้างคาว", "วอลรัส"],
answer: 0
},
{
question: "มหาสมุทรที่ลึกที่สุดในโลกคือมหาสมุทรใดและจุดที่ลึกที่สุดเรียกว่าอะไร?",
options: [
"มหาสมุทรแปซิฟิก - ร่องลึกมาเรียนา",
"มหาสมุทรแอตแลนติก - ร่องลึกเปอร์โตริโก",
"มหาสมุทรอินเดีย - ร่องลึกชวา",
"มหาสมุทรอาร์กติก - ร่องลึกยูเรเชีย"
],
answer: 0
},
{
question: "สงครามร้อยปี (Hundred Years' War) เป็นสงครามระหว่างสองประเทศใด?",
options: ["อังกฤษและฝรั่งเศส", "ฝรั่งเศสและเยอรมนี", "สเปนและโปรตุเกส", "อิตาลีและกรีซ"],
answer: 0
},
{
question: "ก๊าซที่พบมากที่สุดในชั้นบรรยากาศของโลกคือก๊าซอะไร?",
options: ["ไนโตรเจน", "ออกซิเจน", "คาร์บอนไดออกไซด์", "อาร์กอน"],
answer: 0
},
{
question: "ใครคือผู้เขียนวรรณกรรมชิ้นเอกของโลกเรื่อง \"Don Quixote\" (ดอน กิโฆเต้)?",
options: ["มิเกล เด เซร์บันเตส", "วิลเลียม เชกสเปียร์", "วิกเตอร์ อูโก", "ลีโอ ตอลสตอย"],
answer: 0
},
{
question: "ธาตุที่หายากที่สุดและมีความเสถียรน้อยที่สุดบนเปลือกโลกตามธรรมชาติคือธาตุใด?",
options: ["แอสทาทีน", "แฟรนเซียม", "เรเดียม", "โพลอนีเซียม"],
answer: 0
}
];
// Game State
let state = {
score: 100,
currentQuestionIndex: 0,
currentBet: 0,
timeLeft: 15,
timerInterval: null,
scoreInterval: null,
isMuted: false,
audioCtx: null,
correctCount: 0,
incorrectCount: 0,
maxBetPlaced: 0,
activePhase: null // 'bet' or 'answer'
};
// DOM Elements
const startScreen = document.getElementById('start-screen');
const betScreen = document.getElementById('bet-screen');
const answerScreen = document.getElementById('answer-screen');
const gameoverScreen = document.getElementById('gameover-screen');
const victoryScreen = document.getElementById('victory-screen');
const gameHeader = document.getElementById('game-header');
const questionProgress = document.getElementById('question-progress');
const progressBarFill = document.getElementById('progress-bar-fill');
const scoreDisplay = document.getElementById('score-display');
const scoreFloat = document.getElementById('score-float');
const timerWrapper = document.getElementById('timer-wrapper');
const timerBar = document.getElementById('timer-bar');
const timerText = document.getElementById('timer-text');
const muteBtn = document.getElementById('mute-btn');
const startGameBtn = document.getElementById('start-game-btn');
const retryGameBtn = document.getElementById('retry-game-btn');
const restartGameBtn = document.getElementById('restart-game-btn');
// Betting Screen Elements
const betQuestionText = document.getElementById('bet-question-text');
const betOpt1 = document.getElementById('bet-opt-1');
const betOpt2 = document.getElementById('bet-opt-2');
const betOpt3 = document.getElementById('bet-opt-3');
const betOpt4 = document.getElementById('bet-opt-4');
const betBtns = document.querySelectorAll('.bet-btn');
// Answer Screen Elements
const answerQuestionText = document.getElementById('answer-question-text');
const currentBetBadge = document.getElementById('current-bet-badge');
const answersContainer = document.getElementById('answers-container');
const feedbackBox = document.getElementById('feedback-box');
// Web Audio API Synthesizer
function playSound(type) {
if (state.isMuted) return;
try {
if (!state.audioCtx) {
state.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (state.audioCtx.state === 'suspended') {
state.audioCtx.resume();
}
const now = state.audioCtx.currentTime;
switch(type) {
case 'click': {
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(600, now);
gain.gain.setValueAtTime(0.08, now);
gain.gain.linearRampToValueAtTime(0, now + 0.1);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(now);
osc.stop(now + 0.1);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
break;
}
case 'bet': {
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(350, now);
osc.frequency.exponentialRampToValueAtTime(750, now + 0.15);
gain.gain.setValueAtTime(0.1, now);
gain.gain.linearRampToValueAtTime(0, now + 0.15);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(now);
osc.stop(now + 0.15);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
break;
}
case 'correct': {
const notes = [523.25, 659.25, 783.99]; // C5, E5, G5 arpeggio
notes.forEach((f, idx) => {
const startTime = now + idx * 0.08;
const stopTime = startTime + 0.25;
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(f, startTime);
gain.gain.setValueAtTime(0.08, startTime);
gain.gain.linearRampToValueAtTime(0, stopTime);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(startTime);
osc.stop(stopTime);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
});
break;
}
case 'incorrect': {
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(180, now);
osc.frequency.linearRampToValueAtTime(90, now + 0.4);
gain.gain.setValueAtTime(0.15, now);
gain.gain.linearRampToValueAtTime(0, now + 0.4);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(now);
osc.stop(now + 0.4);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
break;
}
case 'tick': {
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(state.timeLeft <= 3 ? 1100 : 750, now);
gain.gain.setValueAtTime(0.03, now);
gain.gain.linearRampToValueAtTime(0, now + 0.05);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(now);
osc.stop(now + 0.05);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
break;
}
case 'gameover': {
const notes = [130.81, 110.00, 82.41]; // C3, A2, E2
notes.forEach((f, idx) => {
const startTime = now + idx * 0.12;
const stopTime = startTime + 0.4;
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(f, startTime);
osc.frequency.linearRampToValueAtTime(f - 15, stopTime);
gain.gain.setValueAtTime(0.05, startTime);
gain.gain.linearRampToValueAtTime(0, stopTime);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(startTime);
osc.stop(stopTime);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
});
break;
}
case 'victory': {
const notes = [261.63, 329.63, 392.00, 523.25, 659.25, 783.99, 1046.50]; // C4 to C6 arpeggio
notes.forEach((f, idx) => {
const startTime = now + idx * 0.08;
const stopTime = startTime + 0.3;
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(f, startTime);
gain.gain.setValueAtTime(0.06, startTime);
gain.gain.linearRampToValueAtTime(0, stopTime);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start(startTime);
osc.stop(stopTime);
osc.onended = () => {
osc.disconnect();
gain.disconnect();
};
});
break;
}
}
} catch (e) {
console.error("Audio playback error:", e);
}
}
// Initialize audio context on first click/tap to bypass browser security policies
function initAudio() {
if (!state.audioCtx) {
state.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (state.audioCtx.state === 'suspended') {
state.audioCtx.resume();
}
}
// Audio Control Button Handler
muteBtn.addEventListener('click', () => {
initAudio();
state.isMuted = !state.isMuted;
if (state.isMuted) {
muteBtn.innerHTML = '<i class="fas fa-volume-mute"></i>';
muteBtn.classList.add('muted');
} else {
muteBtn.innerHTML = '<i class="fas fa-volume-up"></i>';
muteBtn.classList.remove('muted');
playSound('click');
}
});
// Dynamic Bet Calculations (Scales dynamically with score to maintain excitement)
function generateBets(score) {
if (score <= 4) {
return [1, Math.min(2, score), Math.min(3, score), score];
}
// Scale percentages for all scores
let opt1 = Math.max(5, Math.floor(score * 0.15));
let opt2 = Math.max(opt1 + 5, Math.floor(score * 0.35));
let opt3 = Math.max(opt2 + 5, Math.floor(score * 0.65));
let opt4 = score;
// Helper to round to nearest 5 or 10 for readability
const roundClean = (val) => {
if (val <= 10) return val;
if (val <= 50) return Math.round(val / 5) * 5;
return Math.round(val / 10) * 10;
};
opt1 = roundClean(opt1);
opt2 = roundClean(opt2);
opt3 = roundClean(opt3);
// Ensure strict ordering: opt1 < opt2 < opt3 < opt4
if (opt2 <= opt1) opt2 = opt1 + 5;
if (opt3 <= opt2) opt3 = opt2 + 5;
if (opt3 >= opt4) opt3 = Math.max(opt2 + 5, opt4 - 5);
if (opt2 >= opt3) opt2 = Math.max(opt1 + 5, opt3 - 5);
return [Math.max(1, opt1), Math.max(2, opt2), Math.max(3, opt3), opt4];
}
// Timer Functions
function startTimer(phase) {
clearInterval(state.timerInterval);
state.timeLeft = 15;
state.activePhase = phase;
updateTimerUI();
state.timerInterval = setInterval(() => {
state.timeLeft--;
updateTimerUI();
if (state.timeLeft > 0) {
playSound('tick');
} else {
clearInterval(state.timerInterval);
handleTimeout();
}
}, 1000);
}
function updateTimerUI() {
timerText.textContent = state.timeLeft;
// Scale the countdown bar horizontally (15 seconds total)
const scale = state.timeLeft / 15;
timerBar.style.transform = `scaleX(${scale})`;
// Alert state colors
timerBar.classList.remove('warning', 'critical');
if (state.timeLeft <= 4) {
timerBar.classList.add('critical');
} else if (state.timeLeft <= 7) {
timerBar.classList.add('warning');
}
}
function stopTimer() {
clearInterval(state.timerInterval);
}
// Handle time-out scenario
function handleTimeout() {
if (state.activePhase === 'bet') {
// Auto-select option 1 (the lowest bet)
const options = generateBets(state.score);
const autoBet = options[0];
selectBet(autoBet);
} else if (state.activePhase === 'answer') {
// Automatically incorrect due to timeout
processAnswer(null, true);
}
}
// Start Game
startGameBtn.addEventListener('click', () => {
initAudio();
playSound('click');
setupNewGame();
});
// Pool of diverse topics to randomize AI question generation and prevent repetition
const TOPIC_SETS = [
["อารยธรรมโบราณ", "ดาราศาสตร์และอวกาศ", "สิ่งประดิษฐ์พลิกโลก"],
["สำรวจทะเลลึก", "วรรณกรรมคลาสสิก", "ประวัติศาสตร์เอเชีย"],
["วิทยาศาสตร์การแพทย์", "ศิลปะและสถาปัตยกรรม", "บุคคลสำคัญของโลก"],
["สัตว์โลกแปลกประหลาด", "ภูมิศาสตร์เกาะและมหาสมุทร", "ภาษาและนิรุกติศาสตร์"],
["ตำนานและเรื่องเล่าปรัมปรา", "เคมีในห้องอาหาร", "ฟิสิกส์ในชีวิตประจำวัน"],
["ประวัติศาสตร์คอมพิวเตอร์", "เครื่องดนตรีคลาสสิก", "อาหารและวัฒนธรรมการกิน"],
["โบราณคดีอียิปต์และเมโสโปเตเมีย", "ปรากฏการณ์ธรรมชาติสุดแปลก", "วิวัฒนาการสิ่งมีชีวิต"],
["กีฬาโอลิมปิกและประวัติศาสตร์กีฬา", "คดีปริศนาที่ยังไขไม่ได้", "การสำรวจอวกาศยุคใหม่"],
["พฤกษศาสตร์น่ารู้", "ระบบนิเวศน์ที่แปลกที่สุด", "ปรัชญาและแนวคิดของโลก"],
["ประวัติศาสตร์ยานพาหนะและการเดินทาง", "การสำรวจขั้วโลก", "วิทยาศาสตร์ทางทะเล"],
["ประวัติศาสตร์ยุคกลาง", "วิทยาการหุ่นยนต์และ AI", "สถาปัตยกรรมสิ่งก่อสร้างสุดมหัศจรรย์"],
["ตำนานนอร์สและกรีกโบราณ", "ฟอสซิลและไดโนเสาร์", "ภัยพิบัติทางธรรมชาติครั้งใหญ่ในประวัติศาสตร์"],
["เศรษฐศาสตร์ในชีวิตประจำวัน", "ภาพยนตร์และวงการฮอลลีวูด", "สัตว์ปีกและโลกของการบิน"],
["ปริศนาคณิตศาสตร์", "วัฒนธรรมญี่ปุ่นโบราณ", "การเดินทางรอบโลกของนักสำรวจยุคแรก"],
["จุลชีววิทยาและโลกของไวรัส", "ประวัติศาสตร์การพิมพ์และหนังสือ", "ภูเขาไฟและแผ่นดินไหว"]
];
// Fetch questions dynamically from Google Gemini 2.5 Flash API via Backend Proxy
async function fetchAIQuestions() {
const cleanUrl = BACKEND_API_URL.trim().replace(/\/+$/, "");
// Pick a random set of topics to inject into query parameters to prevent duplicate questions
const randomSet = TOPIC_SETS[Math.floor(Math.random() * TOPIC_SETS.length)];
const topicsStr = encodeURIComponent(randomSet.join(","));
const seed = Math.floor(Math.random() * 1000000);
const endpoint = cleanUrl
? `${cleanUrl}/api/questions?topics=${topicsStr}&seed=${seed}`
: `/api/questions?topics=${topicsStr}&seed=${seed}`;
let response;
try {
response = await fetch(endpoint, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
} catch (netErr) {
throw new Error(`ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ (Failed to fetch: ${netErr.message})`);
}
if (!response.ok) {
let errDetails = `HTTP error! status: ${response.status}`;
try {
const errJson = await response.json();
if (errJson && errJson.error) {
errDetails = errJson.error;
}
} catch(e) {}
throw new Error(errDetails);
}
const parsedQuestions = await response.json();
if (!Array.isArray(parsedQuestions) || parsedQuestions.length !== 10) {
throw new Error("โครงสร้างคำถามที่ AI ส่งกลับมาไม่ถูกต้อง");
}
// Basic verification
parsedQuestions.forEach((q, idx) => {
if (!q.question || !Array.isArray(q.options) || q.options.length !== 4 || typeof q.answer !== 'number') {
throw new Error(`คำถามข้อที่ ${idx + 1} รูปแบบฟิลด์ไม่ตรงตามข้อกำหนด`);
}
});
return parsedQuestions;
}
// Setup New Game
const startStatus = document.getElementById('start-status');
async function setupNewGame() {
state.score = 100;
state.currentQuestionIndex = 0;
state.correctCount = 0;
state.incorrectCount = 0;
state.maxBetPlaced = 0;
// Switch immediately to Start Screen to show loading progress
showScreen(startScreen);
gameHeader.classList.add('hidden');
timerWrapper.classList.add('hidden');
// Show Loading feedback with animated spinner and disable all play buttons to prevent double click
startStatus.innerHTML = `<i class="fas fa-spinner fa-spin" style="color: var(--color-primary);"></i> กำลังเชื่อมต่อ Gemini AI เพื่อสร้างคำถามใหม่...`;
startStatus.className = "start-status";
startStatus.classList.remove('hidden');
startGameBtn.disabled = true;
retryGameBtn.disabled = true;
restartGameBtn.disabled = true;
try {
activeQuestions = await fetchAIQuestions();
startStatus.innerHTML = `<i class="fas fa-check-circle" style="color: var(--color-success);"></i> สร้างคำถามสำเร็จ!`;
startStatus.className = "start-status success";
setTimeout(() => {
startGameBtn.disabled = false;
retryGameBtn.disabled = false;
restartGameBtn.disabled = false;
startStatus.classList.add('hidden');
proceedToGame();
}, 800);
} catch (err) {
console.warn("Gemini API failed or key missing. Swapping to local fallback pool.", err);
startStatus.innerHTML = `<i class="fas fa-exclamation-triangle" style="color: var(--color-error);"></i> ไม่สามารถเชื่อมต่อ AI ได้ (${err.message})<br><small style="font-size: 0.8em; opacity: 0.8; margin-top: 5px; display: block;">กำลังสลับไปใช้คำถามสำรอง...</small>`;
startStatus.className = "start-status error";
// Copy the local fallback questions directly to keep the easy-to-hard sorting order
activeQuestions = [...localFallbackQuestions];
setTimeout(() => {
startGameBtn.disabled = false;
retryGameBtn.disabled = false;
restartGameBtn.disabled = false;
startStatus.classList.add('hidden');
proceedToGame();
}, 3500);
}
}
function proceedToGame() {
// Clear any active score animation
if (state.scoreInterval) {
clearInterval(state.scoreInterval);
state.scoreInterval = null;
}
scoreDisplay.textContent = state.score;
gameHeader.classList.remove('hidden');
timerWrapper.classList.remove('hidden');
goToBetScreen();
}
// Switch Screens helper
function showScreen(screen) {
startScreen.classList.add('hidden');
betScreen.classList.add('hidden');
answerScreen.classList.add('hidden');
gameoverScreen.classList.add('hidden');
victoryScreen.classList.add('hidden');
screen.classList.remove('hidden');
}
// Phase 1: Go to Betting Screen
function goToBetScreen() {
const question = activeQuestions[state.currentQuestionIndex];
// Set Header
questionProgress.textContent = `${state.currentQuestionIndex + 1} / 10`;
progressBarFill.style.width = `${((state.currentQuestionIndex) / 10) * 100}%`;
// Setup Betting Screen
betQuestionText.textContent = question.question;
const betOptions = generateBets(state.score);
betOpt1.textContent = betOptions[0];
betOpt2.textContent = betOptions[1];
betOpt3.textContent = betOptions[2];
betOpt4.textContent = betOptions[3];
// Store original options on the buttons for handling click
betBtns.forEach((btn, index) => {
btn.dataset.betAmount = betOptions[index];
});
showScreen(betScreen);
startTimer('bet');
}
// Bind Bet Clicks
betBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
initAudio();
const betAmount = parseInt(e.currentTarget.dataset.betAmount);
playSound('bet');
selectBet(betAmount);
});
});
function selectBet(amount) {
if (state.activePhase !== 'bet') return;
state.activePhase = 'answer';
stopTimer();
state.currentBet = amount;
if (amount > state.maxBetPlaced) {
state.maxBetPlaced = amount;
}
goToAnswerScreen();
}
// Phase 2: Go to Answering Screen
function goToAnswerScreen() {
const question = activeQuestions[state.currentQuestionIndex];
answerQuestionText.textContent = question.question;
currentBetBadge.textContent = state.currentBet;
// Clear & populate answers
answersContainer.innerHTML = '';
feedbackBox.classList.add('hidden');
question.options.forEach((opt, index) => {
const btn = document.createElement('button');
btn.className = 'answer-btn';
// ABCDE Badge
const letter = String.fromCharCode(65 + index); // A, B, C, D
btn.innerHTML = `<span class="ans-badge">${letter}</span> <span class="ans-text">${opt}</span>`;
btn.addEventListener('click', () => {
initAudio();
processAnswer(index, false);
});
answersContainer.appendChild(btn);
});
showScreen(answerScreen);
startTimer('answer');
}
// Process selected answer or timeout
function processAnswer(selectedIndex, isTimeout) {
if (state.activePhase !== 'answer') return;
state.activePhase = null;
stopTimer();
const question = activeQuestions[state.currentQuestionIndex];
const isCorrect = !isTimeout && selectedIndex === question.answer;
const answerButtons = answersContainer.querySelectorAll('.answer-btn');
// Disable all options immediately
answerButtons.forEach(btn => btn.disabled = true);
if (isCorrect) {
playSound('correct');
state.correctCount++;
// Highlight answer green
answerButtons[selectedIndex].classList.add('correct');
// Dynamic Score Ticking animation
const oldScore = state.score;
state.score += state.currentBet;
animateScoreChange(oldScore, state.score, true);
// Show Success Feedback
feedbackBox.className = 'feedback-box correct';
feedbackBox.querySelector('.feedback-icon').innerHTML = '<i class="fas fa-check-circle"></i>';
feedbackBox.querySelector('.feedback-message').textContent = `ถูกต้อง! ได้รับ +${state.currentBet} คะแนน`;
feedbackBox.classList.remove('hidden');
} else {
playSound('incorrect');
state.incorrectCount++;
// Highlight correct answer green, and selected wrong answer red
if (selectedIndex !== null) {
answerButtons[selectedIndex].classList.add('incorrect');
}
answerButtons[question.answer].classList.add('correct');
// Dynamic Score Ticking animation
const oldScore = state.score;
state.score = Math.max(0, state.score - state.currentBet);
animateScoreChange(oldScore, state.score, false);
// Show Error Feedback
feedbackBox.className = 'feedback-box incorrect';
feedbackBox.querySelector('.feedback-icon').innerHTML = '<i class="fas fa-times-circle"></i>';
if (isTimeout) {
feedbackBox.querySelector('.feedback-message').textContent = `หมดเวลา! ถูกหัก -${state.currentBet} คะแนน`;
} else {
feedbackBox.querySelector('.feedback-message').textContent = `ตอบผิด! ถูกหัก -${state.currentBet} คะแนน`;
}
feedbackBox.classList.remove('hidden');
}
// Wait 2.5 seconds to show feedback, then check game flow transitions
setTimeout(() => {
if (state.score <= 0) {
// Player lost all points
endGame(false);
} else {
state.currentQuestionIndex++;
if (state.currentQuestionIndex >= 10) {
// Completed all 10 questions successfully
endGame(true);
} else {
goToBetScreen();
}
}
}, 2500);
}
// Premium Score Ticking and Floating FX Animation
function animateScoreChange(startValue, endValue, isGain) {
// 1. Clear any existing score animation interval to prevent overlap
if (state.scoreInterval) {
clearInterval(state.scoreInterval);
state.scoreInterval = null;
}
// 2. Trigger Floating indicator
scoreFloat.textContent = isGain ? `+${endValue - startValue}` : `-${startValue - endValue}`;
scoreFloat.className = 'score-float'; // reset classes
scoreFloat.classList.add(isGain ? 'add' : 'subtract');
// 3. Ticking number effect
let currentVal = startValue;
const diff = Math.abs(endValue - startValue);
if (diff === 0) {
scoreDisplay.textContent = endValue;
return;
}
const duration = 400; // total animation duration in ms (very fast!)
const totalSteps = Math.min(diff, 15); // cap steps at 15 to ensure reliable browser timing
const stepDuration = duration / totalSteps;
const stepAmount = Math.ceil(diff / totalSteps);
let stepCount = 0;
state.scoreInterval = setInterval(() => {
stepCount++;
if (isGain) {
currentVal += stepAmount;
if (currentVal >= endValue || stepCount >= totalSteps) {
currentVal = endValue;
clearInterval(state.scoreInterval);
state.scoreInterval = null;
}
} else {
currentVal -= stepAmount;
if (currentVal <= endValue || stepCount >= totalSteps) {
currentVal = endValue;
clearInterval(state.scoreInterval);
state.scoreInterval = null;
}
}
scoreDisplay.textContent = currentVal;
}, stepDuration);
}
// End Game (Victory or Game Over)
function endGame(isVictory) {
stopTimer();
gameHeader.classList.add('hidden');
timerWrapper.classList.add('hidden');
// Clear any active score animation and set display to final value
if (state.scoreInterval) {
clearInterval(state.scoreInterval);
state.scoreInterval = null;
}
scoreDisplay.textContent = state.score;
if (isVictory) {
playSound('victory');
// Set stats
document.getElementById('final-score-display').textContent = state.score;
document.getElementById('stat-correct').textContent = `${state.correctCount} / 10`;
document.getElementById('stat-incorrect').textContent = `${state.incorrectCount} / 10`;
document.getElementById('stat-max-bet').textContent = `${state.maxBetPlaced} คะแนน`;
showScreen(victoryScreen);
} else {
playSound('gameover');
// Set stats
document.getElementById('gameover-progress').textContent = `${state.currentQuestionIndex + 1} / 10 ข้อ`;
// Tailor the reason
const reasonText = document.getElementById('gameover-reason');
if (state.score <= 0) {
reasonText.textContent = "คะแนนสะสมของคุณหมดเกลี้ยงแล้ว!";
} else {
reasonText.textContent = "คุณไม่สามารถทนทานเวลาได้หมด";
}
showScreen(gameoverScreen);
}
}
// Restart buttons handlers
retryGameBtn.addEventListener('click', () => {
initAudio();
playSound('click');
setupNewGame();
});
restartGameBtn.addEventListener('click', () => {
initAudio();
playSound('click');
setupNewGame();
});