-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmorsecode.py
More file actions
651 lines (573 loc) · 22.6 KB
/
morsecode.py
File metadata and controls
651 lines (573 loc) · 22.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
import json
import os
import platform
import random
import shutil
import subprocess
import signal
from typing import Optional
from ascii_letters import ascii_letter
SETTINGS_FILE = "morse_settings.json"
# === 3rd Party Modules ===
try:
import pygame
except ImportError:
print("Error: Pygame is not installed. Run: pip install pygame")
exit(1)
try:
import numpy as np
except ImportError:
print("Error: NumPy is not installed. Run: pip install numpy")
exit(1)
try:
import pyttsx3
except ImportError:
print("Error: pyttsx3 is not installed. Run: pip install pyttsx3")
exit(1)
# === Settings File Functions ===
def load_settings():
default_settings = {
"current_frequency": 500, # Hz
"current_wpm": 25, # character (dot) speed
"farnsworth_wpm": 5.0, # effective speed via spacing
"farnsworth_gap_mult": 2.0, # extra stretch for inter-char/word
"show_morse": False,
"show_text": True,
"flash_card_mode_enabled": True,
"voice_enabled": False
}
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, 'r') as f:
settings = json.load(f)
else:
settings = {}
# Ensure all keys exist (backward compatible)
for k, v in default_settings.items():
settings.setdefault(k, v)
# Write back if we added anything
with open(SETTINGS_FILE, 'w') as f:
json.dump(settings, f, indent=2)
return settings
def save_settings():
settings = {
"current_frequency": current_frequency,
"current_wpm": current_wpm,
"farnsworth_wpm": farnsworth_wpm,
"farnsworth_gap_mult": farnsworth_gap_mult,
"show_morse": show_morse,
"show_text": show_text,
"flash_card_mode_enabled": flash_card_mode_enabled,
"voice_enabled": voice_enabled
}
with open(SETTINGS_FILE, 'w') as f:
json.dump(settings, f, indent=2)
# === Robust Pygame init (CoreAudio on macOS) ===
def init_audio():
system = platform.system()
if system == "Darwin":
os.environ["SDL_AUDIODRIVER"] = "coreaudio"
elif system == "Windows":
os.environ["SDL_AUDIODRIVER"] = "directsound"
else:
os.environ.setdefault("SDL_AUDIODRIVER", "alsa")
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
try:
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=1024)
pygame.init()
pygame.mixer.init(frequency=44100, size=-16, channels=1, buffer=1024)
except pygame.error as e:
print(f"Audio init error with driver '{os.environ.get('SDL_AUDIODRIVER')}': {e}")
print("Retrying with SDL default...")
try:
os.environ.pop("SDL_AUDIODRIVER", None)
pygame.mixer.quit(); pygame.quit()
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=1024)
pygame.init()
pygame.mixer.init(frequency=44100, size=-16, channels=1, buffer=1024)
except pygame.error as e2:
print(f"Default driver failed: {e2}")
print("Falling back to 'dummy' (no-sound) so timing still runs.")
os.environ["SDL_AUDIODRIVER"] = "dummy"
pygame.mixer.quit(); pygame.quit()
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=1024)
pygame.init()
pygame.mixer.init(frequency=44100, size=-16, channels=1, buffer=1024)
init_audio()
# === Load Settings ===
settings = load_settings()
current_frequency = settings["current_frequency"]
current_wpm = settings["current_wpm"] # character speed
farnsworth_wpm = settings["farnsworth_wpm"] # effective speed
farnsworth_gap_mult = settings["farnsworth_gap_mult"] # extra stretch
show_morse = settings["show_morse"]
show_text = settings["show_text"]
flash_card_mode_enabled = settings["flash_card_mode_enabled"]
voice_enabled = settings["voice_enabled"]
timeout_supported = True
# === Morse Code Map ===
morse_code = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..',
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
'.': '.-.-.-', ',': '--..--', '?': '..--..', '/': '-..-.'
}
week_letters = {
1: 'ETIANM',
2: 'SURWDK',
3: 'GOHVFL',
4: 'PJBXC',
5: 'YZQ1234567890',
6: '.,?/',
7: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.,?/',
8: '0123456789',
9: '.,?/'
}
week1_words = ["MAN", "TEN", "TAME", "MEAT", "TEAM", "MINE", "AMEN", "ANTI", "ITEM"]
week1_sentences = ["A MAN MET ME", "AN ANT ATE ME", "I AM IN A TENT"]
week12_words = ["WIND", "MASK", "TANK", "STRAW", "MURDER", "WARM", "SAND", "DARK", "UNDER", "SWIM"]
week12_sentences = ["I SAW A DARK WIND", "WE MUST STAND", "MARK WENT UNDER"]
week123_words = ["FARM", "GLOVE", "WOLF", "SHADOW", "GHOST", "DISH", "NORTH", "LADDER", "FLASH", "FORK"]
week123_sentences = ["GO HUNT FOR A SHADOW", "THE WOLF MOVES FAST", "HIS FARM HAD A LADDER"]
week1234_words = ["BLOCK", "JUMP", "CAMP", "PACK", "BRICK", "JAW", "SCRUB", "DUMP", "BACKUP", "SCARF"]
week1234_sentences = ["PACK A BACKUP FOR CAMP", "THE BRICK WALL WAS SCRUBBED", "JUMP INTO THE DARK CAMP"]
week7_words = ["THE", "QUICK", "BROWN", "FOX", "JUMPS", "OVER", "LAZY", "DOG", "PACK", "MY", "BOX", "WITH", "FIVE", "DOZEN", "LIQUOR", "JUGS"]
week7_sentences = ["THE QUICK BROWN FOX JUMPS OVER LAZY DOG.", "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS."]
all_words = week1_words + week12_words + week123_words + week1234_words
call_signs = ["WA7SPY/QRP", "KB1FJZ", "N8FIT", "KA2UTL", "W4ZX", "N3BKQ", "WA5PRY/M", "N6OQN", "W8GSH"]
# === Timing helpers (Farnsworth) ===
def dot_duration_seconds(char_wpm: float) -> float:
# Standard: 1 dot = 1.2 / WPM seconds
return 1.2 / float(char_wpm)
def farnsworth_scale(char_wpm: float, eff_wpm: float) -> float:
eff_wpm = max(1e-6, eff_wpm)
return max(1.0, float(char_wpm) / float(eff_wpm))
def space_durations(char_wpm: float, eff_wpm: float, mult: float):
d = dot_duration_seconds(char_wpm)
scale = farnsworth_scale(char_wpm, eff_wpm) * max(0.1, float(mult))
intra = d * 1.0 # 1 dot between elements (fixed)
inter_char = d * 3.0 * scale # 3 dots * scale
inter_word = d * 7.0 * scale # 7 dots * scale
return d, intra, inter_char, inter_word
def timing_now():
return space_durations(current_wpm, farnsworth_wpm, farnsworth_gap_mult)
# === Utility Functions ===
def prompt_for_pause(duration_seconds=3.0) -> str:
"""Wait for specified duration, but allow Enter to pause or 'q' to quit."""
global timeout_supported
if timeout_supported != True:
pygame.time.wait(int(duration_seconds * 1000))
return 'continue'
try:
import select, sys
if select.select([sys.stdin], [], [], duration_seconds)[0]:
user_input = input().strip().lower()
if user_input == 'q':
return 'quit'
elif user_input == "":
print_blue("PAUSED - Press Enter to continue, or type 'q' to quit...")
user_input = input().strip().lower()
if user_input == 'q':
return 'quit'
else:
print_blue("RESUMED")
return 'continue'
else:
return 'continue'
except:
try:
import msvcrt, time
start = time.time()
while time.time() - start < duration_seconds:
if msvcrt.kbhit():
key = msvcrt.getch()
if key == b'\r':
print_blue("PAUSED - Press Enter to continue, or type 'q' to quit...")
user_input = input().strip().lower()
if user_input == 'q':
return 'quit'
else:
print_blue("RESUMED")
return 'continue'
elif key == b'q':
return 'quit'
time.sleep(0.05)
return 'continue'
except:
timeout_supported = False
print_blue("Press Enter to continue, or type 'q' to quit...")
user_input = input().strip().lower()
if user_input == 'q':
return 'quit'
return 'continue'
def print_blue(text):
print(f"\033[97m{text}\033[0m")
# === Tone generation (mono int16) ===
def generate_tone(frequency, duration, sample_rate=44100):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
wave = np.sin(2 * np.pi * frequency * t).astype(np.float32)
# 5 ms ramp to avoid key clicks
ramp_len = max(1, int(0.005 * sample_rate))
ramp = np.linspace(0.0, 1.0, ramp_len, dtype=np.float32)
wave[:ramp_len] *= ramp
wave[-ramp_len:] *= ramp[::-1]
wave_int16 = np.int16(wave * 32767)
return wave_int16 # 1-D mono
# === Core playback (fixed intra-character spacing + Farnsworth) ===
def play_morse(letter, include_farnsworth=True) -> str:
"""Play the elements of one character with proper 1-dot gaps BETWEEN elements only."""
if letter == ' ':
return 'continue'
code = morse_code.get(letter, '')
dot_s, intra_gap, _, _ = timing_now()
for i, symbol in enumerate(code):
dur = dot_s * (3.0 if symbol == '-' else 1.0)
tone = generate_tone(current_frequency, dur)
sound = pygame.sndarray.make_sound(tone)
sound.play()
result = prompt_for_pause(dur)
if result == 'quit':
return 'quit'
# 1 dot gap only if NOT the last element
if i < len(code) - 1:
result = prompt_for_pause(intra_gap)
if result == 'quit':
return 'quit'
return 'continue'
# === Voice ===
def speak_text(text) -> None:
system = platform.system()
if system == "Darwin": # macOS
os.system(f"say '{text.lower()}'")
elif system == "Linux":
if shutil.which("espeak"):
subprocess.run(["espeak", text])
elif system == "Windows" and pyttsx3 is not None:
try:
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
engine.stop()
except Exception:
pass
# === Play Letter ===
def play_letter(letter, include_farnsworth=True) -> str:
dot_s, _, inter_char_gap, inter_word_gap = timing_now()
if letter == ' ':
return prompt_for_pause(inter_word_gap)
show_msg = ""
if flash_card_mode_enabled:
show_msg = "\n\n"
show_msg += ascii_letter(letter)
elif show_morse or show_text:
show_msg += "Sending:"
if show_text:
show_msg += f" {letter}"
if show_morse:
show_msg += f" ({morse_code[letter]})"
print_blue(show_msg)
# Play elements
result = play_morse(letter, include_farnsworth)
if result == 'quit':
return 'quit'
# Optional voice reveal
if voice_enabled:
result = prompt_for_pause(dot_s * 6)
if result == 'quit':
return 'quit'
speak_text(letter)
# Inter-character spacing ONCE here
if include_farnsworth == False:
return
return prompt_for_pause(inter_char_gap)
# === High-level send ===
def play_text(text) -> str:
for char in text.upper():
if char in morse_code or char == ' ':
result = play_letter(char)
if result == 'quit':
return 'quit'
return 'continue'
def practice_week_letters_continuously(week_num) -> str:
letters = week_letters[week_num]
i = 0
while True:
letter = random.choice(letters)
if letter == ' ':
continue
# After 5 letters, play a space.
if i >= 5:
result = play_letter(' ')
if result == 'quit':
break
i = 0
result = play_letter(letter)
if result == 'quit':
break
i += 1
def play_random_text(text_list, count=1) -> str:
if count > 1:
selection = random.sample(text_list, min(count, len(text_list)))
text = " ".join(selection)
else:
text = random.choice(text_list)
play_text(text)
def quiz_mode(week_num) -> str:
global flash_card_mode_enabled, voice_enabled, show_text
print("Disabling Flash Card Mode")
flash_card_mode_enabled = False
print("Disabling Voice")
voice_enabled = False
show_text = False
letters = week_letters[week_num]
while True:
letter = random.choice(letters)
if letter == ' ':
continue
result = play_letter(letter, False)
if result == 'quit':
break
# Get user guess
guess = input("Guess (type 'quit' to quit): ").upper()
if guess == letter.upper():
print("CORRECT!")
elif guess == "QUIT":
break
else:
print("Not quite! That was a", letter)
show_text = True
# === File utilities (NEW) ===
def resolve_path(p: str) -> str:
"""Expand ~ and env vars; return absolute path."""
p = os.path.expanduser(os.path.expandvars(p.strip()))
if not os.path.isabs(p):
p = os.path.abspath(p)
return p
def load_text_file(p: str) -> Optional[str]:
try:
with open(p, "r", encoding="utf-8", errors="replace") as f:
return f.read()
except Exception as e:
print_blue(f"File error: {e}")
return None
# === Setting modifications ===
def adjust_frequency():
global current_frequency
try:
new_frequency = int(input("Enter new frequency (400-1000 Hz): "))
if 400 <= new_frequency <= 1000:
current_frequency = new_frequency
save_settings()
print(f"Frequency set to {current_frequency} Hz.")
else:
print("Invalid frequency.")
except ValueError:
print("Invalid input.")
# === Menus (original layout + new file option) ===
def settings_menu():
global current_wpm, farnsworth_wpm, farnsworth_gap_mult
global show_morse, show_text, flash_card_mode_enabled, voice_enabled
while True:
print_blue("\nSettings Menu")
print_blue("0. Return to Main Menu")
print_blue("1. Adjust Frequency")
print_blue(f"2. Set WPM (character/dot speed) [current: {current_wpm}]")
print_blue(f"3. Toggle Morse Display (currently {'ON' if show_morse else 'OFF'})")
print_blue(f"4. Toggle Flash Card Mode (currently {'ON' if flash_card_mode_enabled else 'OFF'})")
print_blue(f"5. Toggle Voice Mode (currently {'ON' if voice_enabled else 'OFF'})")
print_blue(f"6. Set Farnsworth WPM (effective) [current: {farnsworth_wpm}]")
print_blue(f"7. Set Farnsworth gap multiplier (0.5–5.0) [current: {farnsworth_gap_mult:.2f}]")
choice = input("Choice: ").strip().lower()
if choice == '1':
adjust_frequency()
elif choice == '2':
try:
w = int(input("Enter Character WPM (5–60): ").strip())
if 5 <= w <= 60:
current_wpm = w
save_settings()
print(f"Character WPM set to {current_wpm}")
else:
print("Invalid WPM.")
except ValueError:
print("Invalid input.")
elif choice == '3':
show_morse = not show_morse
save_settings()
print(f"Morse display is now {'ON' if show_morse else 'OFF'}")
elif choice == '4':
flash_card_mode_enabled = not flash_card_mode_enabled
if flash_card_mode_enabled:
show_morse = False
save_settings()
print(f"Flash Card Mode is now {'ON' if flash_card_mode_enabled else 'OFF'}")
elif choice == '5':
voice_enabled = not voice_enabled
save_settings()
print(f"Voice Mode is now {'ON' if voice_enabled else 'OFF'}")
elif choice == '6':
try:
fw = float(input("Enter Farnsworth WPM (effective, 2–40): ").strip())
if 2.0 <= fw <= 40.0:
farnsworth_wpm = fw
save_settings()
print(f"Farnsworth WPM set to {farnsworth_wpm}")
else:
print("Invalid Farnsworth WPM.")
except ValueError:
print("Invalid input.")
elif choice == '7':
try:
m = float(input("Farnsworth gap multiplier (0.5–5.0): ").strip())
if 0.5 <= m <= 5.0:
farnsworth_gap_mult = m
save_settings()
print(f"Farnsworth gap multiplier set to {farnsworth_gap_mult:.2f}")
else:
print("Invalid multiplier.")
except ValueError:
print("Invalid input.")
elif choice == '0':
break
else:
print("Invalid choice.")
def practice_week_menu():
print_blue("\nPractice Week Letters")
print_blue("0. Return to Main Menu")
for i in range(1, 8):
letters = week_letters[i]
display = letters if i in [1, 2, 3, 4] else ''.join(sorted(set(letters)))
print_blue(f"{i}. Week {i} ({display})")
choice = input("Choice: ").lower()
if choice == '0':
return
elif choice in [str(i) for i in range(1, 8)]:
practice_week_letters_continuously(int(choice))
else:
print("Invalid choice.")
def random_word_menu():
print_blue("\nRandom Word Menu")
print_blue("0. Return to Main Menu")
print_blue("1. Week 1 Words: " + ", ".join(week1_words))
print_blue("2. Weeks 1+2 Words: " + ", ".join(week12_words))
print_blue("3. Weeks 1–3 Words: " + ", ".join(week123_words))
print_blue("4. Weeks 1–4 Words: " + ", ".join(week1234_words))
print_blue("5. All Words: " + ", ".join(all_words))
choice = input("Choice: ").lower()
if choice == '0':
return
elif choice == '1':
play_random_text(week1_words, count=3)
elif choice == '2':
play_random_text(week12_words, count=3)
elif choice == '3':
play_random_text(week123_words, count=3)
elif choice == '4':
play_random_text(week1234_words, count=3)
elif choice == '5':
play_random_text(all_words, count=3)
else:
print("Invalid choice.")
def random_sentence_menu():
print_blue("\nRandom Sentence Menu")
print_blue("0. Return to Main Menu")
print_blue("1. Week 1 Sentences: " + "; ".join(week1_sentences))
print_blue("2. Weeks 1+2 Sentences: " + "; ".join(week12_sentences))
print_blue("3. Weeks 1–3 Sentences: " + "; ".join(week123_sentences))
print_blue("4. Weeks 1–4 Sentences: " + "; ".join(week1234_sentences))
print_blue("5. Week 7 Sentences: " + "; ".join(week7_sentences))
choice = input("Choice: ").lower()
if choice == '0':
return
elif choice == '1':
play_random_text(week1_sentences)
elif choice == '2':
play_random_text(week12_sentences)
elif choice == '3':
play_random_text(week123_sentences)
elif choice == '4':
play_random_text(week1234_sentences)
elif choice == '5':
play_random_text(week7_sentences)
else:
print("Invalid choice.")
def quiz_mode_menu():
print_blue("\nPop Quiz Mode")
print_blue("0. Return to Main Menu")
for i in range(1, 8):
letters = week_letters[i]
display = letters if i in [1, 2, 3, 4] else ''.join(sorted(set(letters)))
print_blue(f"{i}. Week {i} ({display})")
choice = input("Choice: ").lower()
if choice == '0':
return
elif choice in [str(i) for i in range(1, 8)]:
quiz_mode(int(choice))
else:
print("Invalid choice.")
def show_main_menu():
while True:
print_blue("\n --------------------------------")
print_blue("| Morse Code Trainer - Main Menu |")
print_blue(" --------------------------------")
print_blue("0. Exit")
print_blue("1. Practice Week Letters")
print_blue("2. Random Word")
print_blue("3. Random Sentence")
print_blue("4. Random Call Sign")
print_blue("5. Random Numbers (" + week_letters[8] + ")")
print_blue("6. Random Punctuation (" + week_letters[9] + ")")
print_blue("7. Enter Custom Text")
print_blue("8. Settings")
print_blue("9. Send from a text file")
print_blue("10. Quiz Mode")
dot_s, _, inter_char_gap, inter_word_gap = timing_now()
print(f"\nPress [Enter] to Pause. Press [q] then [Enter] to Stop.")
print(f"\nDisplay: {'ON' if show_morse else 'OFF'} | Flash: {'ON' if flash_card_mode_enabled else 'OFF'} | Voice: {'ON' if voice_enabled else 'OFF'}"
f" | WPM: {current_wpm} | Farnsworth: {farnsworth_wpm} | GapMult: {farnsworth_gap_mult:.2f} | Frequency: {current_frequency}Hz")
choice = input("Choice: ").lower()
if choice == '1':
practice_week_menu()
elif choice == '2':
random_word_menu()
elif choice == '3':
random_sentence_menu()
elif choice == '4':
play_random_text(call_signs)
elif choice == '5':
practice_week_letters_continuously(8)
elif choice == '6':
practice_week_letters_continuously(9)
elif choice == '7':
text = input("Enter custom text: ")
play_text(text)
elif choice == '8':
settings_menu()
elif choice == '9': # NEW
p = input("Enter path to text file (e.g., ~/Desktop/qso.txt): ").strip()
rp = resolve_path(p)
txt = load_text_file(rp)
if txt is None:
print_blue("Could not read file. Double-check the full path.")
else:
# Normalize whitespace: collapse runs of whitespace to single spaces
cleaned = ' '.join(txt.split())
print_blue(f"\nSending file: {rp}\n")
play_text(cleaned)
elif choice == '10':
quiz_mode_menu()
elif choice == '0':
print("Goodbye!")
try:
pygame.mixer.quit()
except Exception:
pass
pygame.quit()
break
else:
print("Invalid choice.")
# === Main Program ===
if __name__ == "__main__":
show_main_menu()