-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathengine.py
More file actions
1211 lines (993 loc) · 58.6 KB
/
Copy pathengine.py
File metadata and controls
1211 lines (993 loc) · 58.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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import json
import os
import re
import shutil
import time
import concurrent.futures
from typing import List, Dict, Optional, Tuple
from datetime import datetime
from models import Player, HumanPlayer
from api_clients import UnifiedLLMClient
from schemas import GameState, LogEntry, TurnOutput
from config import (
TTS_ENABLED, AUTO_CONTINUE, MEMORY_ENABLED, REVEAL_ROLE_ON_DEATH,
NARRATOR_VOICE, ROLE_EMOJIS, PHASE_EMOJIS, ROSTER_CONFIG
)
from tts_engine import TTSEngine
from input_listener import InputListener
class GameEngine:
def __init__(self, tts_enabled: bool = TTS_ENABLED):
# Clean Logs - User requested logs/ be wiped on new game
if os.path.exists("logs"):
shutil.rmtree("logs")
os.makedirs("logs", exist_ok=True)
# Create persistent games directory
os.makedirs("games", exist_ok=True)
# Create memories directory
os.makedirs("memories", exist_ok=True)
# Initialize Game Log as a flat file in games/
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self.game_log_path = os.path.join("games", f"game_{timestamp}.txt")
with open(self.game_log_path, "w", encoding='utf-8') as f:
f.write(f"=== MAFIA GAME LOG ({timestamp}) ===\n")
# Restore individual player logs in logs/ dir
self.client = UnifiedLLMClient(debug=True, log_dir="logs")
self.state = GameState(reveal_role_on_death=REVEAL_ROLE_ON_DEATH)
self.players: List[Player] = []
self.active_players: Dict[str, Player] = {} # Name -> Player obj
# Initialize TTS
self.tts = TTSEngine(enabled=tts_enabled)
# Human player mode tracking
self.human_mode = False
self.human_player: Optional[Player] = None
self.human_role: Optional[str] = None
self.listener: Optional[InputListener] = None # Set in run()
def _log_to_file(self, text: str):
"""Write to game log file only"""
try:
with open(self.game_log_path, "a", encoding='utf-8') as f:
f.write(str(text) + "\n")
except:
pass
def _print_console(self, text: str):
"""Print to console only"""
print(text)
def _is_human_alive(self) -> bool:
"""Check if human player is still alive (for spoiler filtering)"""
return self.human_player is not None and self.human_player.state.is_alive
def _print(self, text: str, spoiler: bool = False):
"""Print to both console and file. If spoiler=True and human alive, console is skipped."""
self._log_to_file(text)
# Show all spoilers if human is dead (spectator mode)
if not (spoiler and self.human_mode and self._is_human_alive()):
self._print_console(text)
def _announce(self, text: str, background: bool = False):
"""Speak system announcement with narrator voice"""
self.tts.speak(text, voice=NARRATOR_VOICE, background=background)
def log(self, phase: str, actor: str, action: str, content: str, is_secret: bool = False, vote_target: str = None, target_log: str = None):
# Determine display name with number if actor is a player
actor_display = actor
player = next((p for p in self.players if p.state.name == actor), None)
if player:
idx = self.players.index(player) + 1
actor_display = f"{idx}. {actor}:"
# Add role icon for terminal display only
# In human mode, only show icon for human's own role or partner (unless human is dead = spectator)
if player.state.role in ("Mafia", "Cop"):
show_icon = (not self.human_mode or
not self._is_human_alive() or
(self.human_player and player.state.name == self.human_player.state.name) or
(self.human_role == "Mafia" and self.human_player and player.state.name == self.human_player.partner_name))
if show_icon:
actor_display = f"{self._get_role_emoji(player.state.role)} {actor_display}"
# Append vote text to content for persistent history
if vote_target:
vote_marker = "(Secret Vote)" if is_secret else f"[VOTE: {vote_target}]"
if "Voted for" not in content and "Suggests killing" not in content and "[Nominated" not in content and "[Suggests" not in content:
content = f"{content} {vote_marker}"
entry = LogEntry(
turn=self.state.turn,
phase=phase,
actor=actor,
action=action,
content=content
)
# Add Phase Icon
phase_icon = PHASE_EMOJIS.get(phase, "")
# Append vote visual
vote_str = ""
if vote_target:
icon = "🔪" if is_secret else "🗳️"
vote_str = f" [{icon} {vote_target}]"
# Determine Display Icon Rules
# DEFAULT: No icon
display_icon = ""
# Rule 1: Phase Start ALWAYS gets the phase icon
if action == "PhaseStart":
display_icon = phase_icon
# Rule 2: Speaking events get specific icons
elif phase == "Day" and action == "speak":
display_icon = "🗣️ "
elif phase == "Night" and action == "whisper":
display_icon = "🌚 "
# Rule 3: Short/Intense phases always use their icon for visibility
elif phase in ["Trial", "Setup", "Reflection"]:
display_icon = phase_icon
# Rule 4: Day/Night System messages (Info, etc) -> NO ICON
# This prevents the "sun/moon on every line" issue.
if is_secret:
# Route secret logs to correct private log based on actor/context
effective_target = target_log # Track for spoiler determination
# Explicit override
if target_log == "Cop":
self.state.cop_logs.append(entry)
elif target_log == "Mafia":
self.state.mafia_logs.append(entry)
# Auto-detect Cop actions
elif (player and player.state.role == "Cop") or action == "investigate":
self.state.cop_logs.append(entry)
effective_target = "Cop"
# Auto-detect Cop System logs
elif str(content).startswith("Investigation Result") or str(content).startswith("Investigation failed"):
self.state.cop_logs.append(entry)
effective_target = "Cop"
# Default: Mafia (including System messages for Night phase calls)
else:
self.state.mafia_logs.append(entry)
effective_target = "Mafia"
# Determine if this is a spoiler for human
is_spoiler = True
if self.human_mode and self.human_role:
if effective_target == "Mafia" and self.human_role == "Mafia":
is_spoiler = False
elif effective_target == "Cop" and self.human_role == "Cop":
is_spoiler = False
display_content = content.replace("[Nominated", "[👉 Nominated").replace("[Suggests killing", "[🔪 Suggests killing").replace("[Defense]", "[🛡️ Defense]").replace("votes guilty", "👎 votes guilty").replace("votes innocent", "👍 votes innocent").replace("abstains", "⏸️ abstains")
self._print(f"\n{display_icon}{actor_display} {vote_str} {display_content}", spoiler=is_spoiler)
else:
self.state.public_logs.append(entry)
display_content = content.replace("[Nominated", "[👉 Nominated").replace("[Suggests killing", "[🔪 Suggests killing").replace("[Defense]", "[🛡️ Defense]").replace("votes guilty", "👎 votes guilty").replace("votes innocent", "👍 votes innocent").replace("abstains", "⏸️ abstains")
self._print(f"\n{display_icon}{actor_display}{vote_str} {display_content}")
def setup_game(self):
self._print("Initializing Game...")
# 1. Filter active players and randomize order
roster = [p for p in ROSTER_CONFIG if p.get("active", True)]
random.shuffle(roster)
player_count = len(roster)
if player_count < 3:
raise ValueError(f"Need at least 3 active players, got {player_count}")
# 2. Assign Roles (2 Mafia, 1 Cop, rest Villagers)
# First respect role preferences from config, then fill randomly
indices = list(range(player_count))
mafia_indices = set()
cop_index = -1
# Collect preferred roles
for i, config in enumerate(roster):
pref = config.get("role", "random").lower()
if pref == "mafia" and len(mafia_indices) < 2:
mafia_indices.add(i)
elif pref == "cop" and cop_index == -1:
cop_index = i
# Fill remaining Mafia slots randomly
remaining = [i for i in indices if i not in mafia_indices and i != cop_index]
while len(mafia_indices) < 2 and remaining:
pick = random.choice(remaining)
# Skip if this player wanted cop/villager specifically
pref = roster[pick].get("role", "random").lower()
if pref in ("cop", "villager"):
remaining.remove(pick)
continue
mafia_indices.add(pick)
remaining.remove(pick)
# Fill Cop slot randomly if not set
if cop_index == -1:
remaining = [i for i in indices if i not in mafia_indices]
# Prefer players who didn't specify a different role
candidates = [i for i in remaining if roster[i].get("role", "random").lower() in ("random", "cop")]
if candidates:
cop_index = random.choice(candidates)
elif remaining:
cop_index = random.choice(remaining)
mafia_names = []
# Create Players
for i, config in enumerate(roster):
role = "Villager"
if i in mafia_indices:
role = "Mafia"
elif i == cop_index:
role = "Cop"
# Check if this is a human player
if config.get("provider") == "human":
p = HumanPlayer(
name=config["name"],
role=role,
player_index=i+1
)
self.human_mode = True
self.human_player = p
self.human_role = role
self.client.suppress_console = True # Hide debug prints in human mode
else:
p = Player(
name=config["name"],
role=role,
provider=config["provider"],
model_name=config["model"],
client=self.client,
player_index=i+1,
use_cli=config.get("use_cli", True),
memory_enabled=MEMORY_ENABLED
)
self.players.append(p)
self.state.players.append(p.state)
self.active_players[p.state.name] = p
# Register TTS voice for player
self.tts.register_player(config["name"], config.get("voice", "en-US-AriaNeural"))
if role == "Mafia":
mafia_names.append(p.state.name)
# Introduce Partners
for p in self.players:
if p.state.role == "Mafia":
partner = [n for n in mafia_names if n != p.state.name]
if partner:
p.set_partner(partner[0])
# Show human their role privately
if self.human_mode and self.human_player:
role_emoji = self._get_role_emoji(self.human_role)
self._print_console(f"\n{'='*40}")
self._print_console(f"You are {self.human_player.state.name}")
self._print_console(f"Your role: {role_emoji} {self.human_role}")
if self.human_role == "Mafia" and self.human_player.partner_name:
self._print_console(f"Your partner: {self.human_player.partner_name}")
self._print_console(f"{'='*40}\n")
# Log mafia reveal (spoiler for human unless they're mafia)
self._print(f"[System] Game Initialized. Mafia are: {', '.join(mafia_names)}", spoiler=True)
self.log("Setup", "System", "MafiaReveal", f"Mafia: {', '.join(mafia_names)}", is_secret=True, target_log="Mafia")
cop_names = [p.state.name for p in self.players if p.state.role == "Cop"]
if cop_names:
self.log("Setup", "System", "CopReveal", f"Cop: {cop_names[0]}", is_secret=True, target_log="Cop")
def _get_living_players(self) -> List[Player]:
return [p for p in self.players if p.state.is_alive]
def _pause_game(self, listener):
"""Handle pause state - wait for SPACE to resume"""
self._print("\n[PAUSED] Press SPACE to resume...")
while True:
if listener.check_for_space():
self._print("[RESUMED]")
return
time.sleep(0.1)
def _wait_for_speech_with_pause(self, listener):
"""Wait for TTS to finish while checking for SPACE to pause"""
while self.tts._current_thread and self.tts._current_thread.is_alive():
if listener and listener.check_for_space():
self._pause_game(listener)
time.sleep(0.1)
def _wait_for_next(self, listener=None):
if AUTO_CONTINUE:
# Poll for SPACE key during sleep
steps = 20 # 2 seconds / 0.1s
for _ in range(steps):
if listener and listener.check_for_space():
self._pause_game(listener)
return
time.sleep(0.1)
return
input("\n[PRESS ENTER TO CONTINUE NEXT ACTION] >> ")
# --- HELPER METHODS ---
def _get_role_emoji(self, role: str) -> str:
"""Get emoji for role. Single source of truth."""
return ROLE_EMOJIS.get(role, "👤")
def _get_strategy_prefix(self, player: Player) -> str:
"""Get prefix for strategy display (includes role emoji for Mafia/Cop)."""
if player.state.role == "Mafia":
return "👺 "
elif player.state.role == "Cop":
return "👮 "
return ""
def _print_strategy(self, player: Player, output: TurnOutput) -> None:
"""Print strategy with role-appropriate prefix."""
if output.strategy:
prefix = self._get_strategy_prefix(player)
strategy_line = f"\n💭 {prefix}{player.state.name} Strategy: {output.strategy}"
# In human mode, all strategies are spoilers (hidden from console)
self._print(strategy_line, spoiler=self.human_mode)
def _take_player_turn(self, player: Player) -> TurnOutput:
"""Take a player's turn, handling terminal mode for human players."""
is_human = isinstance(player, HumanPlayer)
if is_human:
# Wait for TTS to finish before showing human prompt
self.tts.wait_for_speech()
# Announce it's their turn
self._announce("Your turn")
self.tts.wait_for_speech()
if self.listener:
self.listener.pause_for_input()
try:
output = player.take_turn(self.state, self.state.turn)
finally:
if is_human and self.listener:
self.listener.resume_cbreak()
return output
def _start_background_turn(self, player: Player) -> Tuple[Optional[concurrent.futures.Future], Optional[concurrent.futures.ThreadPoolExecutor]]:
"""Start a player's turn in background thread. Returns (future, executor)."""
if not player:
return None, None
# Don't background human players - they need interactive input
if isinstance(player, HumanPlayer):
return None, None
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
future = executor.submit(player.take_turn, self.state, self.state.turn)
return future, executor
def _get_background_result(self, future: Optional[concurrent.futures.Future], executor: Optional[concurrent.futures.ThreadPoolExecutor]) -> Optional[TurnOutput]:
"""Get result from background turn and cleanup executor."""
if not future:
return None
result = future.result()
if executor:
executor.shutdown()
return result
def _check_game_ends_after_death(self, victim_name: str) -> bool:
"""Check if game would end after this player's death."""
future_living = [p for p in self._get_living_players() if p.state.name != victim_name]
future_mafia = sum(1 for p in future_living if p.state.role == "Mafia")
future_town = sum(1 for p in future_living if p.state.role != "Mafia")
return (future_mafia == 0) or (future_mafia >= future_town)
def _collect_votes_concurrently(self, voters: List[Player], all_votes: dict, listener, nominees: List[str]):
"""Collect votes from all voters in up to 4 concurrent processes"""
def collect_voter_vote(voter: Player):
"""Collect one voter's single vote for a nominee (MANDATORY)"""
try:
# Set phase to Trial for voting context (they're voting on nominees)
output = voter.take_turn(self.state, self.state.turn)
if output.strategy:
prefix = self._get_strategy_prefix(voter)
strategy_line = f"\n💭 {prefix}{voter.state.name} Strategy: {output.strategy}"
self._print(strategy_line, spoiler=self.human_mode)
# Get the player name they vote for - MANDATORY, no abstain
vote = (output.vote or "").lower().strip()
# Validate: must be a nominee, not just any living player
valid_targets = [n.lower() for n in nominees]
if vote and vote in valid_targets:
# Return with proper capitalization
target = next(n for n in nominees if n.lower() == vote)
return voter.state.name, target
else:
# Invalid vote - default to first nominee
default_target = nominees[0]
self._print(f"[WARN] {voter.state.name} invalid vote '{vote}'. Defaulting to {default_target}")
return voter.state.name, default_target
except Exception as e:
self._print(f"Error voting for {voter.state.name}: {e}")
default_target = nominees[0]
return voter.state.name, default_target
# Separate human player from AI voters
human_voter = None
ai_voters = []
for voter in voters:
if isinstance(voter, HumanPlayer):
human_voter = voter
else:
ai_voters.append(voter)
# Collect human vote first (needs terminal input)
if human_voter:
voter_name, vote = None, None
try:
output = self._take_player_turn(human_voter)
vote = (output.vote or "").lower().strip()
valid_targets = [n.lower() for n in nominees]
if vote and vote in valid_targets:
vote = next(n for n in nominees if n.lower() == vote)
else:
vote = nominees[0]
self._print(f"[WARN] Invalid vote. Defaulting to {vote}")
voter_name = human_voter.state.name
except Exception as e:
self._print(f"Error voting for {human_voter.state.name}: {e}")
vote = nominees[0]
voter_name = human_voter.state.name
all_votes[voter_name] = vote
self.log("Trial", voter_name, "vote", f"votes for {vote}")
# Use ThreadPoolExecutor with max 4 workers for concurrent AI voting
if ai_voters:
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(collect_voter_vote, voter) for voter in ai_voters]
for future in concurrent.futures.as_completed(futures):
voter_name, vote = future.result()
all_votes[voter_name] = vote
self.log("Trial", voter_name, "vote", f"votes for {vote}")
def _save_game_stats(self, winner: str):
"""Save game stats to game_stats.json"""
stats_path = "game_stats.json"
# Load existing stats or create new
if os.path.exists(stats_path):
with open(stats_path, "r", encoding="utf-8") as f:
stats = json.load(f)
else:
stats = {"games": []}
# Build game record
game_id = os.path.basename(self.game_log_path).replace("game_", "").replace(".txt", "")
mafia_names = [p.state.name for p in self.players if p.state.role == "Mafia"]
game_record = {
"id": game_id,
"winner": winner,
"turns": self.state.turn,
"mafia": mafia_names,
"players": [
{
"name": p.state.name,
"role": p.state.role,
"survived": p.state.is_alive,
"provider": p.state.provider,
"model": p.state.model_name
}
for p in self.players
]
}
stats["games"].append(game_record)
with open(stats_path, "w", encoding="utf-8") as f:
json.dump(stats, f, indent=2)
self._print(f"[Stats] Game saved to {stats_path}")
def check_game_over(self) -> bool:
mafia_count = sum(1 for p in self._get_living_players() if p.state.role == "Mafia")
town_count = sum(1 for p in self._get_living_players() if p.state.role != "Mafia")
if mafia_count == 0:
self._print("\n🎉 TOWN WINS! All Mafia eliminated. 🎉")
self._announce("Town wins! All Mafia have been eliminated")
self._save_game_stats("Town")
self._run_reflection("Town")
return True
if mafia_count >= town_count:
self._print("\n💀 MAFIA WINS! They have parity with Town. 💀")
self._announce("Mafia wins!")
self._save_game_stats("Mafia")
self._run_reflection("Mafia")
return True
return False
def run(self):
with InputListener() as listener:
self.listener = listener # Store for human input handling
self.setup_game()
while True:
# Wait for any remaining TTS before checking win
self.tts.wait_for_speech()
# Check Win Condition
if self.check_game_over():
break
# --- DAY PHASE ---
self.state.phase = "Day"
self.log("Day", "System", "PhaseStart", f"Day {self.state.turn}")
self._announce(f"Day {self.state.turn} begins")
# Determine Speaking Order (Rotate based on Day)
# Day 1 start index 0, Day 2 start index 1, etc.
start_idx = (self.state.turn - 1) % len(self.players)
rotated_roster = self.players[start_idx:] + self.players[:start_idx]
ordered_living = [p for p in rotated_roster if p.state.is_alive]
# 1. Speaking Round
living = self._get_living_players()
# Track nominations (suggestions)
nominations = {} # PlayerName -> VoteTarget
# Log speaking order BEFORE starting first speaker (so they see it)
phase_flow = " -> Night" if self.state.turn == 1 else " -> Trial -> Night"
self.log("Day", "System", "Info", f"Speaking order: {', '.join(p.state.name for p in ordered_living)}{phase_flow}")
# Start first speaker's turn in background while announcement plays
first_speaker_future, executor = self._start_background_turn(
ordered_living[0] if ordered_living else None
)
for i, player in enumerate(ordered_living):
# Double-check aliveness just in case state drifted
if not player.state.is_alive:
self._print(f"[DEBUG] Skipping dead player {player.state.name} in speaking order.")
continue
try:
# Use pre-generated output for first speaker if available
if i == 0 and first_speaker_future:
output = self._get_background_result(first_speaker_future, executor)
else:
# Generate while previous TTS might still be playing
output = self._take_player_turn(player)
# Prepare TTS immediately (before waiting for previous to finish)
speech = output.speech or ""
# Capture nomination if present (no nominations on Day 1)
spoken_action = ""
if self.state.turn > 1 and output.vote and output.vote not in ("null", "None", "skip", "Skip"):
nominations[player.state.name] = output.vote
spoken_action = f"{player.state.name} nominates {output.vote}."
tts_text = f"{speech} {spoken_action}".strip() if speech else spoken_action
audio_path = None
if tts_text:
# This blocks MAIN thread but runs while PREV TTS thread is playing
audio_path = self.tts.prepare_speech(tts_text, player.state.name, announce_name=True)
# Wait for previous TTS before displaying new output
self._wait_for_speech_with_pause(listener)
self._print_strategy(player, output)
# Construct content with bracketed action if present
action_part = f"[Nominated {output.vote}] " if spoken_action else ""
content = f"{action_part}{speech}"
self.log("Day", player.state.name, "speak", content)
# Play pre-generated audio
if audio_path:
self.tts.play_file(audio_path, background=True)
except Exception as e:
self.log("Day", player.state.name, "error", f"Failed to speak: {e}")
# User can press Enter while TTS plays to trigger next generation
self._wait_for_next(listener)
# 2. Trial Round
# Identify Nominees (anyone with at least one nomination)
nominee_counts = {}
for target in nominations.values():
# Case-insensitive match, use proper name capitalization
matched = next((p.state.name for p in living if p.state.name.lower() == target.lower()), None)
if matched:
nominee_counts[matched] = nominee_counts.get(matched, 0) + 1
if not nominee_counts:
self.log("Day", "System", "Info", "No nominations")
else:
# Wait for last speaker to finish
self.tts.wait_for_speech()
# Sort by nomination count (least to most votes)
sorted_nominees = sorted(nominee_counts.items(), key=lambda x: x[1])
nominee_display = [f"{n} ({c})" for n, c in sorted_nominees]
voter_count = len(self._get_living_players())
self.log("Trial", "System", "PhaseStart", f"Nominees: {', '.join(nominee_display)} | Voters: {voter_count}")
self._announce(f"Nominees for trial: {', '.join(nominee_display)}")
# --- DEFENSE PHASE ---
# All nominees speak their defense one after another
self.state.phase = "Trial"
accused_players = []
# Start first defendant's turn in background while announcements happen
first_future = None
executor = None
if sorted_nominees:
first_name = sorted_nominees[0][0]
first_accused = self.active_players.get(first_name)
if first_accused and first_accused.state.is_alive:
self.state.on_trial = first_name
# Announce first defendant BEFORE starting their turn
self._print(f"\n⚖️ {first_name} speaks for defense ⚖️")
# NOW start their turn in background while announcements play
first_future, executor = self._start_background_turn(first_accused)
for i, (accused_name, nom_count) in enumerate(sorted_nominees):
accused = self.active_players.get(accused_name)
if not accused or not accused.state.is_alive:
self._print(f"[DEBUG] Skipping defense for {accused_name} (Dead or invalid).")
continue
accused_players.append(accused)
self.state.on_trial = accused_name
# For non-first defendants, announce here
if i > 0:
self._print(f"\n⚖️ {accused_name} speaks for defense ⚖️")
# Defense - accused speaks
try:
# Use pre-generated output for first defendant if available
if i == 0 and first_future:
output = self._get_background_result(first_future, executor)
else:
output = self._take_player_turn(accused)
# Prepare TTS immediately (before waiting for previous)
speech = output.speech or ""
audio_path = None
if speech:
audio_path = self.tts.prepare_speech(speech, accused_name, announce_name=True)
# Wait for previous TTS while current is being prepared
self._wait_for_speech_with_pause(listener)
self._print_strategy(accused, output)
self.log("Trial", accused_name, "speak", f"[Defense] {speech}")
# Play current TTS in background (next defendant can prepare while this plays)
if audio_path:
self.tts.play_file(audio_path, background=True)
except Exception as e:
self._print(f"Error in defense: {e}")
self._wait_for_next(listener)
# --- CONCURRENT VOTING PHASE ---
self.tts.wait_for_speech()
self.state.on_trial = None # Clear so defendants get voter prompt, not defend prompt
self._print(f"\n🗳️ VOTING TIME 🗳️")
self._announce(f"Voting time.")
# Get all living voters
voters = self._get_living_players()
# Dictionary to store votes: {voter_name: target_player_name}
all_votes = {}
# Extract nominee names from sorted_nominees (list of (name, count) tuples)
nominee_names = [name for name, count in sorted_nominees]
# Use concurrent voting with up to 4 processes
self._collect_votes_concurrently(voters, all_votes, listener, nominee_names)
self._wait_for_next(listener)
# --- RESULTS PHASE ---
self.tts.wait_for_speech()
# Tally votes by target player (no abstains - all votes count)
vote_tally = {} # target_player: [voters who voted for them]
for voter_name, target in all_votes.items():
if target not in vote_tally:
vote_tally[target] = []
vote_tally[target].append(voter_name)
# Determine who gets eliminated FIRST (before announcing)
kill_targets = []
trial_last_words_future = None
trial_lw_executor = None
trial_victim = None
trial_game_ends = False
if vote_tally:
max_votes = max(len(v) for v in vote_tally.values())
most_voted = [k for k, v in vote_tally.items() if len(v) == max_votes]
kill_targets = most_voted
# For first victim, start last words in background while results TTS plays
if kill_targets:
first_target = kill_targets[0]
trial_victim = self.active_players.get(first_target)
if trial_victim and trial_victim.state.is_alive:
# Check if game ends
future_living = [p for p in self._get_living_players() if p.state.name != first_target]
future_mafia = sum(1 for p in future_living if p.state.role == "Mafia")
future_town = sum(1 for p in future_living if p.state.role != "Mafia")
trial_game_ends = (future_mafia == 0) or (future_mafia >= future_town)
if not trial_game_ends:
# Mark dead, set phase, add to logs so victim knows
trial_victim.state.is_alive = False
self.state.phase = "LastWords"
# Determine role emoji
trial_role_emoji = self._get_role_emoji(trial_victim.state.role)
# Add death to public logs so victim sees it (role reveal logged later)
self.state.public_logs.append(LogEntry(
turn=self.state.turn, phase="Trial", actor="System",
action="Death", content=f"{first_target} was voted out"
))
# Start last words in background
trial_last_words_future, trial_lw_executor = self._start_background_turn(trial_victim)
# NOW announce results (TTS plays while last words generates)
self._print(f"\n📊 VOTING RESULTS 📊")
for accused in accused_players:
accused_name = accused.state.name
votes_for_this = vote_tally.get(accused_name, [])
vote_count = len(votes_for_this)
voters_str = ", ".join(votes_for_this) if votes_for_this else "None"
result_msg = f"{accused_name} - {vote_count} votes from ({voters_str})"
self.log("Trial", "System", "VoteSummary", result_msg)
self._announce(f"{accused_name} received {vote_count} votes")
if len(kill_targets) > 1:
self.log("Trial", "System", "TieBreak", f"Tie between {kill_targets}. All are eliminated!")
self._announce(f"Tie! {', '.join(kill_targets)} eliminated.")
# Wait for results TTS to finish
self.tts.wait_for_speech()
# Process eliminations
someone_died = False
for i, kill_target in enumerate(kill_targets):
victim = self.active_players.get(kill_target)
if not victim:
continue
# First victim uses pre-generated last words
if i == 0 and not trial_game_ends:
output = None
if trial_last_words_future:
try:
output = self._get_background_result(trial_last_words_future, trial_lw_executor)
except Exception as e:
self._print(f"Error in last words: {e}")
elif isinstance(trial_victim, HumanPlayer):
# Human player needs interactive input for last words
self._announce(f"{kill_target}, last words.")
try:
output = self._take_player_turn(trial_victim)
except Exception as e:
self._print(f"Error getting human last words: {e}")
if output:
speech = output.speech or ""
audio_path = None
if speech:
audio_path = self.tts.prepare_speech(speech, kill_target, announce_name=True)
if not isinstance(trial_victim, HumanPlayer):
self._announce(f"{kill_target}, last words.")
self._print_strategy(victim, output)
self.log("LastWords", kill_target, "speak", f"[Last Words] {speech}")
if audio_path:
self.tts.play_file(audio_path, background=True)
self._wait_for_next(listener)
self.tts.wait_for_speech()
self.state.phase = "Trial"
elif i > 0 and victim.state.is_alive:
# Additional victims in tie - generate last words normally
future_living = [p for p in self._get_living_players() if p.state.name != kill_target]
future_mafia = sum(1 for p in future_living if p.state.role == "Mafia")
future_town = sum(1 for p in future_living if p.state.role != "Mafia")
game_ends = (future_mafia == 0) or (future_mafia >= future_town)
if not game_ends:
self.state.phase = "LastWords"
victim.state.is_alive = False
self._announce(f"{kill_target}, last words.")
try:
output = self._take_player_turn(victim)
speech = output.speech or ""
audio_path = None
if speech:
audio_path = self.tts.prepare_speech(speech, kill_target, announce_name=True)
self._wait_for_speech_with_pause(listener)
self._print_strategy(victim, output)
self.log("LastWords", kill_target, "speak", f"[Last Words] {speech}")
if audio_path:
self.tts.play_file(audio_path, background=True)
except Exception as e:
self._print(f"Error in last words: {e}")
self._wait_for_next(listener)
self.state.phase = "Trial"
# Mark victim as dead (always, even if game ends)
victim.state.is_alive = False
self.log("Result", "System", "Death", f"{kill_target} eliminated.")
self._announce(f"{kill_target} eliminated.")
if self.state.reveal_role_on_death:
role_emoji = self._get_role_emoji(victim.state.role)
# Role already in public_logs from earlier - just log for display
self.log("Result", "System", "RoleReveal", f"{role_emoji} {kill_target} was a {victim.state.role}!")
someone_died = True
# Clear trial state
self.state.on_trial = None
self._wait_for_next(listener)
# Wait for any remaining TTS before checking win
self.tts.wait_for_speech()
# Check Win again before Night
if self.check_game_over():
break
# --- NIGHT PHASE ---
self.state.phase = "Night"
self.log("Night", "System", "PhaseStart", f"Night {self.state.turn}")
self._announce(f"Night {self.state.turn} begins")
mafia_alive = [p for p in self._get_living_players() if p.state.role == "Mafia"]
if not mafia_alive:
# Game over loop will catch this next iter
pass
else:
# --- MAFIA TURN ---
self.log("Night", "System", "MafiaWake", "Mafia awake", is_secret=True, target_log="Mafia")
# Start first Mafia's turn in background while announcement plays
first_mafia_future, executor = self._start_background_turn(
mafia_alive[0] if mafia_alive else None
)
night_victim = None
mafia_votes = {}
for i, m_player in enumerate(mafia_alive):
if not m_player.state.is_alive:
continue
try:
# Use pre-generated output for first Mafia if available
if i == 0 and first_mafia_future:
output = self._get_background_result(first_mafia_future, executor)
else:
# Generate while previous TTS might still be playing
output = self._take_player_turn(m_player)
target = output.vote
# Normalize: strip "kill " prefix if LLM included it
if target and target.lower().startswith("kill "):
target = target[5:].strip()
action_tag = f"[Suggests killing {target}] " if target else ""
spoken_action = f"{m_player.state.name} suggests killing {target}." if target else ""
# Prepare TTS (skip if human is not Mafia - spoiler)
speech = output.speech or ""
tts_text = f"{speech} {spoken_action}".strip() if speech else spoken_action
audio_path = None
should_play_tts = not self.human_mode or self.human_role == "Mafia"
if tts_text and should_play_tts:
audio_path = self.tts.prepare_speech(tts_text, m_player.state.name, announce_name=True)
# Wait for previous TTS before displaying
self._wait_for_speech_with_pause(listener)
self._print_strategy(m_player, output)
content = f"{action_tag}{output.speech or ''}"
self.log("Night", m_player.state.name, "whisper", content, is_secret=True, target_log="Mafia")
# Play pre-generated audio
if audio_path:
self.tts.play_file(audio_path, background=True)
if target:
mafia_votes[target] = mafia_votes.get(target, 0) + 1
except Exception as e:
self._print(f"Mafia Error: {e}")
# User can press Enter while TTS plays
if m_player != mafia_alive[-1]:
self._wait_for_next(listener)
# Consensus Summary
tally_parts = [f"{k} ({v})" for k,v in mafia_votes.items()]
tally_str = ", ".join(tally_parts) if tally_parts else "No votes"
self.log("Night", "System", "VoteSummary", f"Votes: {tally_str}", is_secret=True, target_log="Mafia")
# Do NOT wait for last mafia TTS here.
# We proceed to Cop generation immediately primarily so Cop generates while Mafia talks.
# self.tts.wait_for_speech()
if mafia_votes:
max_votes = max(mafia_votes.values())
winners = [k for k, v in mafia_votes.items() if v == max_votes]
if len(winners) > 1:
kill_target = random.choice(winners)
self.log("Night", "System", "TieBreak", f"Tie {winners}. Random: {kill_target}", is_secret=True, target_log="Mafia")
else:
kill_target = winners[0]
# Execute Kill (Secretly for now)
if kill_target in self.active_players:
victim = self.active_players[kill_target]
if victim.state.is_alive:
# DELAY DEATH: Don't set is_alive=False yet, so Cop doesn't see it
# victim.state.is_alive = False
night_victim = kill_target
self.log("Night", "System", "Kill", f"Mafia chosen target: {kill_target}", is_secret=True, target_log="Mafia")
else:
self.log("Night", "System", "Fail", f"Target {kill_target} already dead", is_secret=True, target_log="Mafia")
else:
self.log("Night", "System", "Fail", "Invalid target", is_secret=True, target_log="Mafia")
else:
self.log("Night", "System", "Quiet", "No kill", is_secret=True, target_log="Mafia")
# --- COP TURN (After Mafia Kill) ---
cop_alive = [p for p in self._get_living_players() if p.state.role == "Cop"]
for cop in cop_alive:
if not cop.state.is_alive: continue # Safeguard (if died tonight)
try:
# Cop Turn
output = self._take_player_turn(cop)
target_name = output.vote
# Normalize
if target_name and target_name.lower().startswith("investigate "):
target_name = target_name[12:].strip()
# Prepare TTS (skip if human is not Cop - spoiler)