-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
203 lines (162 loc) · 5.85 KB
/
Copy pathmain.py
File metadata and controls
203 lines (162 loc) · 5.85 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
"""
WordPy Solver — Command Line Interface
=======================================
Run a game from the terminal with full control over word, font, theme, and word list.
Usage examples
--------------
# Basic: random word, default Michigan theme
python main.py
# Specific target word
python main.py --word FIELD
# Custom theme
python main.py --word CRANE --theme dark
# Custom font (name from assets/fonts/)
python main.py --font Poppins-Bold --word STATE
# Custom word list (e.g. the 5-word demo list)
python main.py --words assets/words.txt --word DOGGY
# Save rendered PNG images of each guess to demo_output/
python main.py --word FIELD --save-images
# List all available fonts
python main.py --list-fonts
# Run 10 automated games and report solve rate
python main.py --benchmark 10
"""
import argparse
import os
import sys
import random
# Allow running from repo root: python main.py
sys.path.insert(0, os.path.dirname(__file__))
from wordpy import GameEngine, Bot, DisplaySpecification, list_available_fonts
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="WordPy autonomous solver bot",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--word", "-w",
type=str, default=None,
metavar="WORD",
help="Target word to solve (default: random from word list)",
)
parser.add_argument(
"--words",
type=str, default="assets/words.txt",
metavar="FILE",
help="Path to word list file (default: assets/words.txt)",
)
parser.add_argument(
"--theme", "-t",
choices=["michigan", "dark", "contrast", "neon"],
default="michigan",
help="Visual theme for the board renderer (default: michigan)",
)
parser.add_argument(
"--font", "-f",
type=str, default=None,
metavar="FONT_NAME",
help="Font name from assets/fonts/, e.g. Poppins-Bold, Caladea-Bold, Lora-Bold",
)
parser.add_argument(
"--font-size",
type=int, default=48,
metavar="PT",
help="Font size in points (default: 48)",
)
parser.add_argument(
"--save-images",
action="store_true",
help="Save each guess feedback image as PNG in demo_output/",
)
parser.add_argument(
"--list-fonts",
action="store_true",
help="List all available fonts in assets/fonts/ and exit",
)
parser.add_argument(
"--benchmark",
type=int, default=0,
metavar="N",
help="Run N automated games and report solve rate (disables verbose output)",
)
return parser.parse_args()
def build_display_spec(args: argparse.Namespace) -> DisplaySpecification:
"""Construct a DisplaySpecification from CLI arguments."""
theme_map = {
"michigan": DisplaySpecification.michigan,
"dark": DisplaySpecification.dark_mode,
"contrast": DisplaySpecification.high_contrast,
"neon": DisplaySpecification.neon,
}
spec = theme_map[args.theme]()
if args.font:
spec.font_name = args.font
spec.font_size = args.font_size
return spec
def run_single_game(args: argparse.Namespace) -> None:
"""Run one game and print results."""
spec = build_display_spec(args)
print("\n" + spec.describe())
if args.font or args.theme != "michigan":
loaded = spec.get_font()
print(f" Loaded font : {getattr(loaded, 'path', '(PIL default)')}\n")
engine = GameEngine(
display_spec=spec,
word_list_file=args.words,
save_images=args.save_images,
)
bot = Bot(word_list_file=args.words, display_spec=spec)
success = engine.play(bot, target_word=args.word)
if args.save_images and success:
print(f"\nGuess images saved to: demo_output/")
def run_benchmark(args: argparse.Namespace, n_games: int) -> None:
"""Run N games silently and report success rate + average guesses."""
spec = build_display_spec(args)
# Load word list once
word_list = GameEngine._load_word_list(args.words)
if not word_list:
print(f"ERROR: Could not load word list from '{args.words}'")
return
print(f"\nBenchmarking {n_games} games...")
solved = 0
total_guesses = 0
for i in range(n_games):
target = random.choice(word_list)
# Suppress print output by redirecting stdout temporarily
import io, contextlib
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
engine = GameEngine(display_spec=spec, word_list_file=args.words)
bot = Bot(word_list_file=args.words, display_spec=spec)
success = engine.play(bot, target_word=target)
if success:
solved += 1
total_guesses += len(engine.prev_guesses)
# Progress
if (i + 1) % max(1, n_games // 10) == 0:
pct = (i + 1) / n_games * 100
print(f" {i+1}/{n_games} games complete ({pct:.0f}%)", flush=True)
rate = solved / n_games * 100
avg_guesses = total_guesses / solved if solved > 0 else 0
print(f"\nResults over {n_games} games:")
print(f" Solved : {solved}/{n_games} ({rate:.1f}%)")
print(f" Avg guesses : {avg_guesses:.2f} (when solved)")
def main() -> None:
args = parse_args()
if args.list_fonts:
fonts = list_available_fonts()
if fonts:
print(f"\nFonts available in assets/fonts/ ({len(fonts)} total):\n")
for name in fonts:
print(f" --font {name}")
else:
print("No fonts found in assets/fonts/. Add .ttf files there.")
print()
return
if args.benchmark > 0:
run_benchmark(args, args.benchmark)
else:
run_single_game(args)
if __name__ == "__main__":
main()