-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
861 lines (701 loc) · 27.6 KB
/
main.py
File metadata and controls
861 lines (701 loc) · 27.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
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
#!/usr/bin/env python3
"""Millionaire Game
Game console đơn giản mô phỏng "Ai là triệu phú" với nhiều mức độ khó.
Yêu cầu chính (theo đề bài):
- Có 4 chế độ độ khó: easy, medium, hard, genius.
- Mỗi chế độ có 60 câu hỏi (đã nằm trong các file:
easy-mode.py, medium-mode.py, hard-mode.py, genius-mode.py).
- Mỗi lượt chơi lấy ngẫu nhiên 10 câu hỏi KHÔNG trùng nhau từ chế độ đã chọn.
- Trả lời sai 1 câu => thua cuộc (kết thúc game).
- Trả lời đúng => được nâng "stack" (mức thưởng).
- Mỗi câu có giới hạn thời gian:
+ Easy : 60s / câu
+ Medium : 30s / câu
+ Hard : 20s / câu
+ Genius : 10s / câu
Lưu ý: Không sửa nội dung câu hỏi sẵn có, mà chỉ "bọc" các hàm có sẵn
trong những file đó để tạo thành game hoàn chỉnh.
"""
from __future__ import annotations
import builtins
import importlib.util
import os
import random
import select
import shutil
import sys
import time
import math
import wave
import struct
from dataclasses import dataclass
from types import ModuleType
from typing import Callable, Dict, List
# Pygame để phát âm thanh (nếu có)
try:
import pygame
PYGAME_AVAILABLE = True
except ImportError: # pygame chưa được cài đặt
pygame = None # type: ignore[assignment]
PYGAME_AVAILABLE = False
_pygame_mixer_initialized = False
# ========================= Tiện ích console ==========================
def clear_screen() -> None:
"""Xóa toàn bộ màn hình console (Unix/Windows)."""
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
# ANSI màu và hiệu ứng text đơn giản (typing, lighting)
RESET = "\033[0m"
BRIGHT = "\033[1m"
DIM = "\033[2m"
ITALIC = "\033[3m"
UNDERLINE = "\033[4m"
# Bảng màu mở rộng
COLORS = {
# cơ bản
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"blue": "\033[94m",
"magenta": "\033[95m",
"cyan": "\033[96m",
"white": "\033[97m",
"grey": "\033[90m",
# biến thể nhạt (dim)
"red_dim": "\033[91m" + DIM,
"green_dim": "\033[92m" + DIM,
"yellow_dim": "\033[93m" + DIM,
"blue_dim": "\033[94m" + DIM,
"magenta_dim": "\033[95m" + DIM,
"cyan_dim": "\033[96m" + DIM,
# một vài màu 256-color (nếu terminal hỗ trợ)
"orange": "\033[38;5;208m",
"gold": "\033[38;5;220m",
}
# Logo ASCII cho Millionaire Game
ASCII_LOGO = [
" __ __ _ _ _ _ _ _ ",
"| \\/ (_) | (_) | (_) ",
"| \\ / |_| |_ _| | ___ _ _ __ ___ _ __ ",
"| |\\/| | | __| | |/ _ \\| | '_ \\ / _ \\ '__| ",
"| | | | | |_| | | (_) | | | | | __/ | ",
"|_| |_|_|\\__|_|_|\\___/|_|_| |_|\\___|_| ",
" M I L L I O N A I R E G A M E ",
]
def style(text: str, *, color: str | None = None, italic: bool = False, underline: bool = False, bright: bool = True) -> str:
"""Áp dụng màu và kiểu chữ cơ bản cho text.
Tự động tắt nếu SETTINGS.colors = False.
"""
if not SETTINGS.colors:
return text
codes: list[str] = []
if bright:
codes.append(BRIGHT)
if italic:
codes.append(ITALIC)
if underline:
codes.append(UNDERLINE)
if color:
codes.append(COLORS.get(color, ""))
prefix = "".join(codes)
if not prefix:
return text
return f"{prefix}{text}{RESET}"
def type_print(text: str, delay: float = 0.02, end: str = "\n", *, color: str | None = None) -> None:
"""Hiệu ứng gõ chữ từng ký tự (typing).
- Nếu SETTINGS.effects = False thì in nhanh không delay.
- Có thể truyền màu (color) để in kèm màu.
"""
text_to_print = style(text, color=color) if color is not None else text
if not SETTINGS.effects:
sys.stdout.write(text_to_print + end)
sys.stdout.flush()
return
for ch in text_to_print:
sys.stdout.write(ch)
sys.stdout.flush()
time.sleep(delay)
sys.stdout.write(end)
sys.stdout.flush()
# ========================= Âm thanh (pygame + fallback) ==========================
BEEP_DIR = os.path.join(os.path.dirname(__file__), "sounds")
CORRECT_WAV = os.path.join(BEEP_DIR, "correct_beep.wav")
WRONG_WAV = os.path.join(BEEP_DIR, "wrong_beep.wav")
def _generate_beep_wav(path: str, freq: int = 880, duration: float = 0.15, volume: float = 0.5) -> None:
"""Sinh file WAV beep đơn giản bằng thư viện chuẩn (mono 16-bit)."""
framerate = 44100
amp = int(32767 * max(0.0, min(volume, 1.0)))
n_samples = int(duration * framerate)
os.makedirs(os.path.dirname(path), exist_ok=True)
with wave.open(path, "w") as wf:
wf.setnchannels(1)
wf.setsampwidth(2) # 16-bit
wf.setframerate(framerate)
for i in range(n_samples):
t = float(i) / framerate
sample = int(amp * math.sin(2 * math.pi * freq * t))
wf.writeframes(struct.pack("<h", sample))
def _ensure_beep_files() -> None:
"""Đảm bảo 2 file beep tồn tại, nếu chưa thì tự sinh."""
if not os.path.exists(CORRECT_WAV):
_generate_beep_wav(CORRECT_WAV, freq=880, duration=0.15, volume=0.6)
if not os.path.exists(WRONG_WAV):
_generate_beep_wav(WRONG_WAV, freq=440, duration=0.15, volume=0.7)
def _init_pygame_mixer() -> bool:
"""Khởi tạo pygame.mixer nếu có pygame, trả về True nếu OK."""
global _pygame_mixer_initialized
if not PYGAME_AVAILABLE:
return False
if _pygame_mixer_initialized and pygame.mixer.get_init(): # type: ignore[union-attr]
return True
try:
pygame.mixer.init(frequency=44100, size=-16, channels=1) # type: ignore[union-attr]
_pygame_mixer_initialized = True
return True
except Exception:
return False
def _beep(times: int = 1, interval: float = 0.1) -> None:
"""Fallback: phát tiếng beep bằng ký tự BEL (\a) nếu không dùng được pygame."""
for _ in range(times):
sys.stdout.write("\a")
sys.stdout.flush()
time.sleep(interval)
def play_correct_sound() -> None:
"""Âm thanh khi trả lời đúng: 1 beep ngắn (ưu tiên dùng pygame)."""
if not SETTINGS.sound:
return
if _init_pygame_mixer():
try:
_ensure_beep_files()
snd = pygame.mixer.Sound(CORRECT_WAV) # type: ignore[union-attr]
snd.play()
return
except Exception:
pass
# Fallback nếu pygame không dùng được
_beep(times=1, interval=0.05)
def play_wrong_sound() -> None:
"""Âm thanh khi trả lời sai: 3 beep liên tiếp (ưu tiên dùng pygame)."""
if not SETTINGS.sound:
return
if _init_pygame_mixer():
try:
_ensure_beep_files()
snd = pygame.mixer.Sound(WRONG_WAV) # type: ignore[union-attr]
# chơi 3 lần nối tiếp
snd.play()
time.sleep(0.18)
snd.play()
time.sleep(0.18)
snd.play()
return
except Exception:
pass
# Fallback nếu pygame không dùng được
_beep(times=3, interval=0.06)
def glow_print(
text: str,
repeat: int = 2,
delay: float = 0.08,
) -> None:
"""Hiệu ứng 'lighting' đơn giản: đổi màu liên tục rồi dừng ở màu sáng.
Tôn trọng SETTINGS.effects và SETTINGS.colors.
"""
if not SETTINGS.colors and not SETTINGS.effects:
print(text)
return
if not SETTINGS.effects:
# Không animation, chỉ in một dòng màu xanh sáng (nếu bật màu)
if SETTINGS.colors:
sys.stdout.write(f"{COLORS['green']}{BRIGHT}{text}{RESET}\n")
else:
sys.stdout.write(text + "\n")
sys.stdout.flush()
return
sequence = [
COLORS["yellow"],
COLORS["magenta"],
COLORS["cyan"],
COLORS["green"],
COLORS["gold"],
]
for _ in range(repeat):
for color in sequence:
if SETTINGS.colors:
sys.stdout.write(f"\r{color}{BRIGHT}{text}{RESET}")
else:
sys.stdout.write(f"\r{text}")
sys.stdout.flush()
time.sleep(delay)
# in cố định một lần cuối cùng
if SETTINGS.colors:
sys.stdout.write(f"\r{COLORS['green']}{BRIGHT}{text}{RESET}\n")
else:
sys.stdout.write("\r" + text + "\n")
sys.stdout.flush()
def rainbow_print(text: str, delay: float = 0.0, end: str = "\n") -> None:
"""In text với nhiều màu (rainbow) theo từng ký tự.
- Nếu tắt màu: in thường.
- Nếu tắt hiệu ứng: bỏ delay.
"""
if not SETTINGS.colors:
sys.stdout.write(text + end)
sys.stdout.flush()
return
rainbow_seq = [
COLORS["red"],
COLORS["orange"],
COLORS["yellow"],
COLORS["green"],
COLORS["cyan"],
COLORS["blue"],
COLORS["magenta"],
]
n = len(rainbow_seq)
eff_delay = delay if SETTINGS.effects else 0.0
for i, ch in enumerate(text):
color = rainbow_seq[i % n]
sys.stdout.write(f"{color}{BRIGHT}{ch}{RESET}")
sys.stdout.flush()
if eff_delay > 0:
time.sleep(eff_delay)
sys.stdout.write(end)
sys.stdout.flush()
def trail_print(
text: str,
main_color: str = "red",
trail_color: str = "white",
ghosts: int = 3,
delay: float = 0.03,
cycles: int = 2,
) -> None:
"""Hiệu ứng 'đường sáng' (lighting trail).
- Tôn trọng SETTINGS.effects và SETTINGS.colors.
- Nếu tắt effects: in một dòng (có màu nếu bật colors).
"""
# Nếu tắt hiệu ứng: in một dòng đơn giản
if not SETTINGS.effects:
if SETTINGS.colors:
base_raw = COLORS.get(main_color, COLORS["red"])
sys.stdout.write(f"{base_raw}{BRIGHT}{text}{RESET}\n")
else:
sys.stdout.write(text + "\n")
sys.stdout.flush()
return
width = shutil.get_terminal_size((80, 20)).columns
base = text
# cắt nếu quá dài để tránh nhảy dòng khó nhìn
if len(base) > width - 4:
base = base[: width - 4]
base_raw = COLORS.get(main_color, COLORS["red"]) # màu nền
trail_raw = COLORS.get(trail_color, COLORS["white"]) # màu sáng hơn
base_dim = base_raw + DIM
base_bright = base_raw + BRIGHT
trail_bright = trail_raw + BRIGHT
length = len(base)
total_steps = length + ghosts
for _ in range(cycles):
for step in range(total_steps):
rendered = []
for i, ch in enumerate(base):
dist = abs(i - step)
if dist == 0:
code = trail_bright # tâm highlight sáng nhất
elif dist == 1:
code = base_bright # viền xung quanh hơi sáng
else:
code = base_dim # phần còn lại tối hơn
if SETTINGS.colors:
rendered.append(f"{code}{ch}{RESET}")
else:
rendered.append(ch)
line = "".join(rendered)
sys.stdout.write(f"\r{line}")
sys.stdout.flush()
time.sleep(delay)
sys.stdout.write("\n")
sys.stdout.flush()
# ========================= Cấu hình game ==========================
EASY_TIME = 60
MEDIUM_TIME = 30
HARD_TIME = 20
GENIUS_TIME = 10
# "Stack" (bậc thưởng) cho 10 câu hỏi
PRIZE_LADDER = [
100_000,
200_000,
400_000,
800_000,
1_600_000,
3_200_000,
6_400_000,
12_800_000,
25_600_000,
51_200_000,
]
@dataclass
class ModeConfig:
key: str
label: str
file_path: str
time_per_question: int
@dataclass
class GameSettings:
effects: bool = True # hiệu ứng text (typing, trail,...)
colors: bool = True # màu chữ ANSI
sound: bool = True # âm thanh đúng/sai
timer: bool = True # giới hạn thời gian mỗi câu
SETTINGS = GameSettings()
MODES: Dict[str, ModeConfig] = {
"1": ModeConfig(
key="easy",
label="Easy (Dễ) - 60s/câu",
file_path="easy-mode.py",
time_per_question=EASY_TIME,
),
"2": ModeConfig(
key="medium",
label="Medium (Trung bình) - 30s/câu",
file_path="medium-mode.py",
time_per_question=MEDIUM_TIME,
),
"3": ModeConfig(
key="hard",
label="Hard (Khó) - 20s/câu",
file_path="hard-mode.py",
time_per_question=HARD_TIME,
),
"4": ModeConfig(
key="genius",
label="Genius (Thiên tài) - 10s/câu",
file_path="genius-mode.py",
time_per_question=GENIUS_TIME,
),
}
# ====================== Tiện ích nạp module =======================
def load_module_from_file(name: str, path: str) -> ModuleType:
"""Nạp một file .py bất kỳ (kể cả tên file có dấu gạch ngang)."""
if not os.path.exists(path):
raise FileNotFoundError(f"Không tìm thấy file: {path}")
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Không thể nạp module từ: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore[call-arg]
return module
def get_question_functions(module: ModuleType) -> List[Callable[[], None]]:
"""Lấy danh sách các hàm câu hỏi trong module.
Theo các file hiện có, hàm câu hỏi đều có dạng tên bắt đầu bằng
"cau" (ví dụ: cau1_a, cau2_a, cau10_c, ...).
"""
question_funcs: List[Callable[[], None]] = []
for name in dir(module):
if not name.startswith("cau"):
continue
attr = getattr(module, name)
if callable(attr):
question_funcs.append(attr)
# Sắp xếp theo tên để ổn định (cau1_, cau2_, ..., cau60_)
question_funcs.sort(key=lambda f: f.__name__)
return question_funcs
# ===================== Input có giới hạn thời gian =====================
class QuestionTimeout(Exception):
"""Ném ra khi hết thời gian cho một câu hỏi."""
class QuestionExit(Exception):
"""Dùng để thay thế sys.exit() bên trong các file câu hỏi."""
def timed_input(prompt: str, timeout: int) -> str:
"""Nhận input từ người chơi với thời gian đếm ngược.
- Hiển thị bộ đếm thời gian đơn giản (giảm dần từng giây).
- Nếu hết thời gian mà người chơi chưa nhập => ném QuestionTimeout.
Sử dụng select.select trên stdin (chạy tốt trên môi trường Unix / Linux).
Lưu ý: nếu người chơi nhập các lệnh đặc biệt như !rule, !stop, !skip, !main, !setting
thì giá trị đó sẽ được trả nguyên về cho caller để xử lý tiếp.
"""
# Nếu tắt timer: không đếm ngược, nhập bình thường
if not SETTINGS.timer:
sys.stdout.write(prompt)
sys.stdout.flush()
return builtins.input()
sys.stdout.write(prompt)
sys.stdout.flush()
start = time.time()
remaining = timeout
# In dòng thông báo đầu tiên
sys.stdout.write(f"\n⏳ Bạn có {timeout} giây để trả lời. Hãy nhập đáp án (A/B/C/D):\n")
sys.stdout.flush()
# Vòng lặp đếm ngược
while True:
now = time.time()
elapsed = int(now - start)
remaining = timeout - elapsed
if remaining <= 0:
sys.stdout.write("\n⏰ Hết thời gian!\n")
sys.stdout.flush()
raise QuestionTimeout("Time is up")
# Hiển thị thời gian còn lại (ghi đè trên cùng một dòng)
sys.stdout.write(f"\r Còn lại: {remaining:2d} giây ")
sys.stdout.flush()
# Chờ tối đa 1 giây hoặc đến khi có dữ liệu nhập
wait_time = min(1, remaining)
rlist, _, _ = select.select([sys.stdin], [], [], wait_time)
if rlist:
# Người chơi đã nhập gì đó
line = sys.stdin.readline()
sys.stdout.write("\n")
sys.stdout.flush()
return line.rstrip("\n")
def ask_one_question(func: Callable[[], None], timeout: int):
"""Chạy một hàm câu hỏi dưới cơ chế:
- Dùng timed_input() để giới hạn thời gian.
- Chặn sys.exit() trong các file câu hỏi để không thoát toàn bộ chương trình.
- Bắt dòng "Wrong answer" in ra để biết người chơi trả lời sai.
Trả về:
"correct" -> trả lời đúng
"wrong" -> trả lời sai hoặc hết thời gian
"skip" -> người chơi nhập !skip
"stop" -> người chơi nhập !stop
"main" -> người chơi nhập !main
"rule" -> người chơi nhập !rule
"""
original_input = builtins.input
original_print = builtins.print
original_exit = sys.exit
state = {"wrong": False, "command": None}
def capture_print(*args, **kwargs): # type: ignore[override]
text = " ".join(str(a) for a in args)
if "Wrong answer" in text:
state["wrong"] = True
# Gọi print thật để vẫn hiển thị ra màn hình
original_print(*args, **kwargs)
def fake_exit(code: int = 0): # thay cho sys.exit bên trong câu hỏi
raise QuestionExit(code)
def question_input(prompt: str = "") -> str:
# Bọc timed_input để ném QuestionTimeout khi hết thời gian
ans = timed_input(prompt, timeout)
# Xử lý các lệnh đặc biệt
cmd = ans.strip().lower()
if cmd in {"!rule", "!stop", "!skip", "!main", "!setting"}:
state["command"] = cmd
return ans
# Gắn monkey-patch
builtins.print = capture_print
builtins.input = question_input
sys.exit = fake_exit
try:
try:
func() # chạy hàm câu hỏi gốc
except QuestionTimeout:
original_print("⏰ Bạn đã hết thời gian cho câu hỏi này!")
return "wrong"
except QuestionExit:
# Hàm câu hỏi đã tự gọi sys.exit() vì sai => coi là sai
return "wrong"
finally:
# Khôi phục lại các hàm gốc để không ảnh hưởng phần còn lại của chương trình
builtins.print = original_print
builtins.input = original_input
sys.exit = original_exit
# Nếu người chơi nhập lệnh đặc biệt, ưu tiên trả về command
if state["command"] is not None:
cmd = state["command"]
if cmd == "!skip":
return "skip"
if cmd == "!stop":
return "stop"
if cmd == "!main":
return "main"
if cmd == "!rule":
return "rule"
if cmd == "!setting":
return "setting"
# Nếu chạy xong mà không timeout & không gọi sys.exit nhưng có in "Wrong answer"
if state["wrong"]:
return "wrong"
return "correct"
# ========================= Vòng chơi chính =========================
def open_settings_menu() -> None:
"""Menu cài đặt cho các tính năng: effect, color, sound, timer."""
while True:
print("\n⚙️ CÀI ĐẶT:")
print(f" 1. Hiệu ứng text (typing, trail): {'BẬT' if SETTINGS.effects else 'TẮT'}")
print(f" 2. Màu chữ (color text): {'BẬT' if SETTINGS.colors else 'TẮT'}")
print(f" 3. Âm thanh (sound): {'BẬT' if SETTINGS.sound else 'TẮT'}")
print(f" 4. Giới hạn thời gian (timer): {'BẬT' if SETTINGS.timer else 'TẮT'}")
print(" 0. Quay lại câu hỏi")
choice = input("Chọn (0-4): ").strip()
if choice == "0":
break
elif choice == "1":
SETTINGS.effects = not SETTINGS.effects
elif choice == "2":
SETTINGS.colors = not SETTINGS.colors
elif choice == "3":
SETTINGS.sound = not SETTINGS.sound
elif choice == "4":
SETTINGS.timer = not SETTINGS.timer
else:
print("Lựa chọn không hợp lệ, vui lòng thử lại.")
def print_banner() -> None:
clear_screen()
print(style("=" * 60, color="blue"))
for line in ASCII_LOGO:
print(style(line, color="gold"))
print(style("=" * 60, color="blue"))
type_print(
"Dựa trên chương trình 'Ai là triệu phú' – trả lời 10 câu hỏi để trở thành TRIỆU PHÚ!",
delay=0.01,
color="cyan",
)
type_print("All In One| Copyright (c) 2025 ZDEV", delay=0.02, color="yellow")
print()
def choose_mode() -> ModeConfig:
print("Chọn chế độ độ khó:")
# Màu cho từng mode: càng khó càng gắt
mode_colors = {
"1": ("green_dim", "green"), # easy: nhẹ
"2": ("cyan", "cyan"), # medium: trung bình
"3": ("orange", "red"), # hard: gắt hơn
"4": ("magenta", "gold"), # genius: đặc biệt
}
# In danh sách mode với màu riêng, riêng Genius dùng lighting trail loop
for key in sorted(MODES.keys()):
mode = MODES[key]
base_color, strong_color = mode_colors.get(key, ("white", "white"))
if mode.key == "genius" and SETTINGS.effects:
# hiệu ứng lighting trail loop cho dòng Genius (nếu bật effects)
label_text = f" {key}. {mode.label}"
trail_print(
label_text,
main_color=base_color,
trail_color=strong_color,
ghosts=4,
delay=0.03,
cycles=2,
)
else:
if SETTINGS.colors:
c = COLORS.get(base_color, COLORS["white"])
sys.stdout.write(f"{c}{BRIGHT} {key}. {mode.label}{RESET}\n")
else:
sys.stdout.write(f" {key}. {mode.label}\n")
sys.stdout.flush()
print()
while True:
choice = input("Nhập lựa chọn (1-4): ").strip()
if choice in MODES:
return MODES[choice]
print("Lựa chọn không hợp lệ, vui lòng thử lại.\n")
def run_game_once() -> None:
print_banner()
mode = choose_mode()
type_print(f"\n👉 Bạn đã chọn chế độ: {mode.label}", delay=0.015, color="yellow")
type_print("Mỗi câu trả lời sai HOẶC hết thời gian sẽ kết thúc lượt chơi.", delay=0.01, color="magenta")
type_print("Trả lời đúng để nâng dần stack tiền thưởng!\n", delay=0.01, color="green")
# Nạp module tương ứng chế độ
module_name = f"{mode.key}_module"
module = load_module_from_file(module_name, mode.file_path)
all_questions = get_question_functions(module)
if len(all_questions) < 10:
print("❌ Chế độ này không có đủ 10 câu hỏi để chơi.")
return
# Chọn ngẫu nhiên 10 câu KHÔNG trùng nhau
selected_questions = random.sample(all_questions, 10)
current_prize = 0
for index, question_func in enumerate(selected_questions, start=1):
header = (
f"Câu hỏi {index}/10 | Thời gian: {mode.time_per_question}s | "
f"Stack hiện tại: {current_prize:_} đ"
)
print("-" * 60)
trail_print(header, main_color="cyan", trail_color="white", ghosts=2, delay=0.01, cycles=1)
print("-" * 60)
result = ask_one_question(question_func, mode.time_per_question)
# Xử lý các lệnh đặc biệt trước
if result == "rule":
print("\n📜 LUẬT CHƠI:")
print("- Trả lời đúng: nâng stack thưởng, tiếp tục câu tiếp theo.")
print("- Trả lời sai hoặc hết thời gian: kết thúc lượt chơi.")
print("- Các lệnh:")
print(" !rule : xem lại luật chơi")
print(" !skip : bỏ qua câu hiện tại (không tính sai, chuyển sang câu khác)")
print(" !stop : dừng cuộc chơi, nhận số tiền hiện tại")
print(" !main : quay về menu chính (kết thúc lượt chơi hiện tại)")
print(" !setting : bật/tắt hiệu ứng, màu sắc, âm thanh, giới hạn thời gian")
# Sau khi in luật, cho làm lại chính câu hỏi này
continue
if result == "setting":
open_settings_menu()
# Sau khi đổi setting, hỏi lại chính câu này
continue
if result == "main":
print("\n🔙 Quay về menu chính theo yêu cầu của bạn...")
return
if result == "stop":
print("\n" + style("⏹ Bạn đã chọn dừng cuộc chơi.", color="yellow"))
print(style(f"👉 Bạn ra về với số tiền thưởng: {current_prize:_} đ", color="gold"))
type_print("Cảm ơn bạn đã tham gia Millionaire Game!\n", delay=0.01, color="cyan")
return
if result == "skip":
print()
type_print("⏭ Bạn đã chọn bỏ qua câu hỏi này (không bị tính sai).", delay=0.01, color="yellow")
# không thay đổi stack, tiếp tục sang câu tiếp theo
time.sleep(0.5)
continue
if result == "wrong":
print()
play_wrong_sound()
trail_print(
"💥 Rất tiếc! Bạn đã trả lời sai hoặc hết thời gian.",
main_color="red",
trail_color="white",
ghosts=3,
delay=0.02,
cycles=2,
)
type_print(f"👉 Bạn ra về với số tiền thưởng: {current_prize:_} đ", delay=0.01, color="yellow")
type_print("Cảm ơn bạn đã tham gia Millionaire Game!\n", delay=0.01, color="cyan")
return
# Trả lời đúng
current_prize = PRIZE_LADDER[index - 1]
message = f"✅ Chính xác! Stack của bạn đã được nâng lên: {current_prize:_} đ"
print()
play_correct_sound()
trail_print(
message,
main_color="green",
trail_color="white",
ghosts=3,
delay=0.02,
cycles=1,
)
# Hiển thị câu chúc mừng khoảng 1 giây rồi xóa màn hình trước khi sang câu mới
time.sleep(1)
clear_screen()
# Trả lời đúng cả 10 câu
print(style("=" * 60, color="blue"))
trail_print(
"🎉 XUẤT SẮC! BẠN ĐÃ TRẢ LỜI ĐÚNG TẤT CẢ 10 CÂU HỎI! 🎉",
main_color="yellow",
trail_color="gold",
ghosts=3,
delay=0.02,
cycles=2,
)
type_print(f"🏆 Số tiền thưởng cuối cùng: {current_prize:_} đ", delay=0.02, color="gold")
type_print("Bạn chính là TRIỆU PHÚ của chương trình hôm nay!", delay=0.02, color="green")
print(style("=" * 60, color="blue"))
def main() -> None:
while True:
run_game_once()
again = input("\nBạn có muốn chơi lại không? (y/n): ").strip().lower()
if again != "y":
type_print("Tạm biệt và hẹn gặp lại trong Millionaire Game!", delay=0.02, color="yellow")
type_print("All In One| By ZDEV", delay=0.02, color="yellow")
break
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n👋 Đã thoát Millionaire Game.")