-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.py
More file actions
540 lines (440 loc) · 19.5 KB
/
visualizer.py
File metadata and controls
540 lines (440 loc) · 19.5 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
#!/usr/bin/env python3
"""
Terminal Visualizer for Figgie
Provides a rich terminal display of Figgie game state with colors and formatting.
Updated for simultaneous tick model with order book interface.
"""
import os
import time
# ANSI color codes
class Colors:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
# Foreground
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
# Bright foreground
BRIGHT_RED = "\033[91m"
BRIGHT_GREEN = "\033[92m"
BRIGHT_YELLOW = "\033[93m"
BRIGHT_BLUE = "\033[94m"
BRIGHT_MAGENTA = "\033[95m"
BRIGHT_CYAN = "\033[96m"
BRIGHT_WHITE = "\033[97m"
# Background
BG_BLACK = "\033[40m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_BLUE = "\033[44m"
BG_GRAY = "\033[100m"
# Suit display info
SUITS = {
"spades": {"symbol": "♠", "color": Colors.WHITE},
"clubs": {"symbol": "♣", "color": Colors.WHITE},
"hearts": {"symbol": "♥", "color": Colors.BRIGHT_RED},
"diamonds": {"symbol": "♦", "color": Colors.BRIGHT_RED},
}
def clear_screen():
"""Clear terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def hide_cursor():
"""Hide terminal cursor."""
print("\033[?25l", end="")
def show_cursor():
"""Show terminal cursor."""
print("\033[?25h", end="")
class FiggieVisualizer:
"""Rich terminal visualizer for Figgie games."""
def __init__(self, delay: float = 0.3, player_names: list = None):
"""
Initialize visualizer.
Args:
delay: Seconds to pause after each action
player_names: Optional list of player names
"""
self.delay = delay
self.player_names = player_names
def get_player_name(self, player_id: int, num_players: int) -> str:
"""Get display name for player."""
if self.player_names and player_id < len(self.player_names):
return self.player_names[player_id]
return f"P{player_id}"
def format_suit(self, suit: str) -> str:
"""Format suit with symbol and color."""
info = SUITS.get(suit, {"symbol": "?", "color": Colors.WHITE})
return f"{info['color']}{info['symbol']}{Colors.RESET}"
def format_money(self, amount: int, show_sign: bool = False) -> str:
"""Format money with color."""
if show_sign and amount > 0:
return f"{Colors.BRIGHT_GREEN}+${amount}{Colors.RESET}"
elif amount < 0:
return f"{Colors.BRIGHT_RED}-${abs(amount)}{Colors.RESET}"
else:
return f"${amount}"
def render_market_panel(self, game) -> list[str]:
"""Render the market (order books) panel."""
lines = []
lines.append(
f"{Colors.BOLD}{Colors.YELLOW}╔══════════════════════════════════════════════════╗{Colors.RESET}"
)
lines.append(
f"{Colors.BOLD}{Colors.YELLOW}║ O R D E R B O O K S ║{Colors.RESET}"
)
lines.append(
f"{Colors.BOLD}{Colors.YELLOW}╠══════════════════════════════════════════════════╣{Colors.RESET}"
)
# Header
header = f"{Colors.YELLOW}║{Colors.RESET} {'SUIT':^10} │ {'BID':^10} │ {'ASK':^10} │ {'SPREAD':^6} {Colors.YELLOW}║{Colors.RESET}"
lines.append(header)
lines.append(
f"{Colors.YELLOW}║{Colors.RESET}{'─' * 14}┼{'─' * 14}┼{'─' * 14}┼{'─' * 8}{Colors.YELLOW}║{Colors.RESET}"
)
for suit in ["spades", "clubs", "hearts", "diamonds"]:
suit_display = f"{self.format_suit(suit)} {suit.capitalize():8}"
book = game.books[suit]
bid = book.bid if book.bid.is_valid() else None
ask = book.ask if book.ask.is_valid() else None
if bid:
bid_str = f"{Colors.BRIGHT_GREEN}${bid.price:3} (P{bid.player_id}){Colors.RESET}"
else:
bid_str = f"{Colors.DIM} --- {Colors.RESET}"
if ask:
ask_str = f"{Colors.BRIGHT_RED}${ask.price:3} (P{ask.player_id}){Colors.RESET}"
else:
ask_str = f"{Colors.DIM} --- {Colors.RESET}"
# Calculate spread
if bid and ask:
spread = ask.price - bid.price
spread_str = f"${spread}"
else:
spread_str = " - "
line = f"{Colors.YELLOW}║{Colors.RESET} {suit_display} │ {bid_str:^20} │ {ask_str:^20} │ {spread_str:^6} {Colors.YELLOW}║{Colors.RESET}"
lines.append(line)
lines.append(
f"{Colors.BOLD}{Colors.YELLOW}╚══════════════════════════════════════════════════╝{Colors.RESET}"
)
return lines
def render_players_panel(self, game) -> list[str]:
"""Render the players info panel."""
lines = []
lines.append(
f"{Colors.BOLD}{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════╗{Colors.RESET}"
)
lines.append(
f"{Colors.BOLD}{Colors.CYAN}║ P L A Y E R S ║{Colors.RESET}"
)
lines.append(
f"{Colors.BOLD}{Colors.CYAN}╠═══════════════════════════════════════════════════════════════════╣{Colors.RESET}"
)
# Header
header = f"{Colors.CYAN}║{Colors.RESET} {'PLAYER':^8} │ {'MONEY':^8} │ "
for suit in ["spades", "clubs", "hearts", "diamonds"]:
header += f" {self.format_suit(suit)} │"
header += f" {'TOTAL':^5} {Colors.CYAN}║{Colors.RESET}"
lines.append(header)
lines.append(
f"{Colors.CYAN}║{Colors.RESET}{'─' * 10}┼{'─' * 10}┼{'─' * 4}┼{'─' * 4}┼{'─' * 4}┼{'─' * 4}┼{'─' * 7}{Colors.CYAN}║{Colors.RESET}"
)
for pid in range(game.num_players):
name = self.get_player_name(pid, game.num_players)
money = game.money[pid]
hand = game.hands[pid]
total_cards = sum(hand.values())
money_str = self.format_money(money)
line = f"{Colors.CYAN}║{Colors.RESET} {name:^8} │ {money_str:^18} │"
for suit in ["spades", "clubs", "hearts", "diamonds"]:
count = hand.get(suit, 0)
line += f" {count:^2} │"
line += f" {total_cards:^5} {Colors.CYAN}║{Colors.RESET}"
lines.append(line)
lines.append(
f"{Colors.BOLD}{Colors.CYAN}╚═══════════════════════════════════════════════════════════════════╝{Colors.RESET}"
)
return lines
def render_action(self, player_id: int, action: dict, game) -> str:
"""Render the current action."""
name = self.get_player_name(player_id, game.num_players)
action_type = action.get("type", "pass")
if action_type == "pass":
return f"{Colors.DIM}{name} passes{Colors.RESET}"
suit = action.get("suit", "")
suit_fmt = self.format_suit(suit)
if action_type == "bid":
price = action.get("price", 0)
return f"{Colors.BRIGHT_GREEN}{name} BIDS ${price} for {suit_fmt} {suit}{Colors.RESET}"
elif action_type == "ask":
price = action.get("price", 0)
return f"{Colors.BRIGHT_RED}{name} ASKS ${price} for {suit_fmt} {suit}{Colors.RESET}"
elif action_type == "buy":
book = game.books.get(suit)
if book and book.ask.is_valid():
return f"{Colors.BRIGHT_YELLOW}{name} BUYS {suit_fmt} {suit} from P{book.ask.player_id} @ ${book.ask.price}{Colors.RESET}"
return f"{Colors.BRIGHT_YELLOW}{name} BUYS {suit_fmt} {suit}{Colors.RESET}"
elif action_type == "sell":
book = game.books.get(suit)
if book and book.bid.is_valid():
return f"{Colors.BRIGHT_YELLOW}{name} SELLS {suit_fmt} {suit} to P{book.bid.player_id} @ ${book.bid.price}{Colors.RESET}"
return f"{Colors.BRIGHT_YELLOW}{name} SELLS {suit_fmt} {suit}{Colors.RESET}"
return f"{name}: {action}"
def render_trade_history(self, trades: list, limit: int = 5) -> list[str]:
"""Render recent trade history."""
lines = []
lines.append(
f"{Colors.BOLD}{Colors.MAGENTA}┌─── Recent Trades ───┐{Colors.RESET}"
)
recent = trades[-limit:] if len(trades) > limit else trades
if not recent:
lines.append(f"{Colors.DIM}│ No trades yet │{Colors.RESET}")
else:
for trade in reversed(recent):
suit_fmt = self.format_suit(trade.suit)
lines.append(
f"│ {suit_fmt} ${trade.price:2} P{trade.buyer_id}←P{trade.seller_id} T{trade.tick:3} │"
)
lines.append(
f"{Colors.BOLD}{Colors.MAGENTA}└─────────────────────┘{Colors.RESET}"
)
return lines
def render_game_state(
self,
game,
current_tick: int = None,
actions: list = None,
show_goal: bool = False,
) -> None:
"""
Render the full game state to terminal.
Args:
game: FiggieGame instance
current_tick: Current tick number (optional)
actions: List of (player_id, action) tuples from this tick (optional)
show_goal: Whether to reveal the goal suit
"""
clear_screen()
hide_cursor()
# Title
print(
f"\n{Colors.BOLD}{Colors.BRIGHT_YELLOW} ╔═══════════════════════════════════════════╗{Colors.RESET}"
)
print(
f"{Colors.BOLD}{Colors.BRIGHT_YELLOW} ║ F I G G I E T R A D I N G F L O O R ║{Colors.RESET}"
)
print(
f"{Colors.BOLD}{Colors.BRIGHT_YELLOW} ╚═══════════════════════════════════════════╝{Colors.RESET}"
)
print()
# Tick info
tick_info = f" Tick: {Colors.BRIGHT_WHITE}{game.current_tick}{Colors.RESET}"
tick_info += f" │ Model: {Colors.BRIGHT_CYAN}Simultaneous{Colors.RESET}"
if show_goal:
tick_info += (
f" │ Goal: {self.format_suit(game.goal_suit)} {game.goal_suit}"
)
print(tick_info)
print()
# Market panel
for line in self.render_market_panel(game):
print(f" {line}")
print()
# Players panel
for line in self.render_players_panel(game):
print(f" {line}")
print()
# Current actions (all players this tick)
if actions:
print(f" {Colors.BOLD}Actions this tick:{Colors.RESET}")
for player_id, action in actions:
action_str = self.render_action(player_id, action, game)
print(f" ► {action_str}")
print()
# Trade history (side panel concept - just print below for simplicity)
if game.trades:
for line in self.render_trade_history(game.trades):
print(f" {line}")
show_cursor()
if self.delay > 0:
time.sleep(self.delay)
def render_final_scores(self, game, scores: dict) -> None:
"""Render final scores screen."""
clear_screen()
print(
f"\n{Colors.BOLD}{Colors.BRIGHT_YELLOW} ╔═══════════════════════════════════════════╗{Colors.RESET}"
)
print(
f"{Colors.BOLD}{Colors.BRIGHT_YELLOW} ║ G A M E O V E R ║{Colors.RESET}"
)
print(
f"{Colors.BOLD}{Colors.BRIGHT_YELLOW} ╚═══════════════════════════════════════════╝{Colors.RESET}"
)
print()
# Reveal goal suit
print(
f" Goal Suit: {self.format_suit(game.goal_suit)} {Colors.BOLD}{game.goal_suit.upper()}{Colors.RESET}"
)
print(f" Total Trades: {len(game.trades)}")
print(f" Total Ticks: {game.current_tick + 1}")
print()
# Scores table
print(
f" {Colors.BOLD}{Colors.CYAN}╔════════════════════════════════════════════════╗{Colors.RESET}"
)
print(
f" {Colors.BOLD}{Colors.CYAN}║ F I N A L S C O R E S ║{Colors.RESET}"
)
print(
f" {Colors.BOLD}{Colors.CYAN}╠════════════════════════════════════════════════╣{Colors.RESET}"
)
# Sort by score
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for rank, (pid, score) in enumerate(sorted_scores, 1):
name = self.get_player_name(pid, game.num_players)
goal_cards = game.hands[pid].get(game.goal_suit, 0)
# Medal for top 3
if rank == 1:
medal = f"{Colors.BRIGHT_YELLOW}🥇{Colors.RESET}"
elif rank == 2:
medal = f"{Colors.WHITE}🥈{Colors.RESET}"
elif rank == 3:
medal = f"{Colors.YELLOW}🥉{Colors.RESET}"
else:
medal = " "
score_str = self.format_money(score, show_sign=True)
goal_str = f"{self.format_suit(game.goal_suit)}×{goal_cards}"
print(
f" {Colors.CYAN}║{Colors.RESET} {medal} {rank}. {name:^8} │ {score_str:^20} │ {goal_str:^10} {Colors.CYAN}║{Colors.RESET}"
)
print(
f" {Colors.BOLD}{Colors.CYAN}╚════════════════════════════════════════════════╝{Colors.RESET}"
)
print()
def run_visual_game(
player_modules: list, visualizer: FiggieVisualizer = None, player_names: list = None
) -> dict:
"""
Run a game with visualization using simultaneous tick model.
This is a modified version of run_game() that includes visualization.
"""
import random
from engine import (
FiggieGame,
create_deck,
deal_cards,
get_game_state,
validate_action,
execute_action,
calculate_scores,
VALID_PLAYER_COUNTS,
STARTING_MONEY,
MAX_TICKS,
CONSECUTIVE_PASS_LIMIT,
get_ante,
)
num_players = len(player_modules)
if num_players not in VALID_PLAYER_COUNTS:
raise ValueError(
f"Figgie requires {VALID_PLAYER_COUNTS} players, got {num_players}"
)
if visualizer is None:
visualizer = FiggieVisualizer(delay=0.3, player_names=player_names)
ante = get_ante(num_players)
# Create deck and deal
suit_counts, goal_suit = create_deck()
hands = deal_cards(suit_counts, num_players)
# Initialize game state
game = FiggieGame(num_players=num_players)
game.suit_counts = suit_counts
game.goal_suit = goal_suit
for i in range(num_players):
game.hands[i] = hands[i]
game.money[i] = STARTING_MONEY - ante
# Initial state
visualizer.render_game_state(game, show_goal=False)
# Run game with simultaneous tick model
consecutive_all_pass = 0
for tick in range(MAX_TICKS):
game.current_tick = tick
# Phase 1: Collect actions from ALL players
player_actions = []
for player_id in range(num_players):
state = get_game_state(game, player_id)
try:
action = player_modules[player_id].get_action(state)
except Exception:
action = {"type": "pass"}
player_actions.append((player_id, action))
# Phase 2: Shuffle action order (simulates racing)
random.shuffle(player_actions)
# Visualize the tick with all actions
visualizer.render_game_state(game, tick, player_actions, show_goal=False)
# Phase 3: Execute actions in shuffled order
all_passed = True
for player_id, action in player_actions:
# Re-validate (state may have changed)
is_valid, _ = validate_action(game, player_id, action)
if not is_valid:
action = {"type": "pass"}
if action.get("type") != "pass":
all_passed = False
if is_valid:
execute_action(game, player_id, action)
# Check for game end
if all_passed:
consecutive_all_pass += 1
if consecutive_all_pass >= CONSECUTIVE_PASS_LIMIT:
break
else:
consecutive_all_pass = 0
# Calculate final scores
game.final_scores = calculate_scores(game)
# Show final state with goal revealed
visualizer.render_game_state(game, show_goal=True)
if visualizer.delay > 0:
time.sleep(max(1, visualizer.delay * 3))
# Show final scores
visualizer.render_final_scores(game, game.final_scores)
return {
"goal_suit": goal_suit,
"suit_counts": suit_counts,
"final_hands": {i: game.hands[i] for i in range(num_players)},
"final_money": {i: game.money[i] for i in range(num_players)},
"scores": game.final_scores,
"trades": len(game.trades),
"ticks": game.current_tick + 1,
}
if __name__ == "__main__":
# Demo mode - run with sample bot
import argparse
parser = argparse.ArgumentParser(description="Figgie Visualizer Demo")
parser.add_argument("players", nargs="*", help="Paths to player bot files")
parser.add_argument(
"--delay", type=float, default=0.3, help="Delay between frames (seconds)"
)
parser.add_argument("--names", nargs="+", help="Player names")
args = parser.parse_args()
if args.players:
from engine import load_player
player_modules = [load_player(p) for p in args.players]
player_names = args.names or [
os.path.basename(os.path.dirname(p)) for p in args.players
]
else:
# Demo with built-in main.py bot
import main
player_modules = [main] * 4
player_names = ["Alice", "Bob", "Carol", "Dave"]
viz = FiggieVisualizer(delay=args.delay, player_names=player_names)
try:
result = run_visual_game(player_modules, viz, player_names)
print(
f"\nGame completed! Winner: P{max(result['scores'], key=result['scores'].get)}"
)
except KeyboardInterrupt:
show_cursor()
print("\n\nGame interrupted.")