Repository navigation
Expand file tree
/
Copy pathgame.py
More file actions
632 lines (571 loc) · 21.7 KB
/
Copy pathgame.py
File metadata and controls
632 lines (571 loc) · 21.7 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
import pygame
import queue
import threading
import tracemalloc
from pathlib import Path
from time import perf_counter
import puzzle
import ui
from algos.uninformed import bfs, dfs, ids, ucs
from algos.informed import astar, greedy_best_first, weighted_astar
from algos.extra import divide_and_conquer
from algos.heuristics import HEURISTICS
DEFAULT_PUZZLE_SIZE = 20
DEFAULT_SCRAMBLE_STEPS = 24
PUZZLE_SIZE_OPTIONS = (10, 20)
RECOMMENDED_MAX_SIZE = 20
BFS_MAX_SIZE = 10
DFS_MAX_SIZE = 10
BFS_MAX_NODES = 300000
DFS_MAX_DEPTH = 180
DFS_MAX_NODES = 450000
IDS_MAX_DEPTH = 120
IDS_MAX_NODES = 300000
UCS_MAX_NODES = 220000
BFS_MAX_SECONDS = 8.0
DFS_MAX_SECONDS = 8.0
IDS_MAX_SECONDS = 8.0
UCS_MAX_SECONDS = 8.0
ASTAR_MAX_NODES = 500000
ASTAR_MAX_SECONDS = 8.0
ASTAR_WEIGHT = 2.0
GREEDY_MAX_NODES = 500000
GREEDY_MAX_SECONDS = 8.0
WASTAR_MAX_NODES = 500000
WASTAR_MAX_SECONDS = 8.0
WASTAR_WEIGHT = 2.0
HINT_MAX_NODES = 180000
HINT_MAX_SECONDS = 3.0
HINT_WEIGHT = 2.2
DC_MAX_NODES = 150000
UI_RESULTS_FILE = Path("results/ui_solver_runs.txt")
def newPuzzle(n):
scramble_steps = DEFAULT_SCRAMBLE_STEPS
if n <= 10:
scramble_steps = 12
elif n >= 20:
scramble_steps = 36
p = puzzle.Puzzle(n, tuple(range(1, n+1)))
p.genRandom(scramble_steps=scramble_steps)
return p
def solve_fastest(puzzle_obj, state: tuple[int, ...]) -> tuple[list[str], str]:
"""Try multiple solvers and pick the quickest valid result by wall-clock time."""
candidates: list[tuple[str, callable]] = [
(
"A*",
lambda p: astar(
p,
max_nodes=ASTAR_MAX_NODES,
max_seconds=ASTAR_MAX_SECONDS,
heuristic_weight=ASTAR_WEIGHT,
),
),
(
"Greedy",
lambda p: greedy_best_first(
p,
max_nodes=GREEDY_MAX_NODES,
max_seconds=GREEDY_MAX_SECONDS,
),
),
(
"W-A*",
lambda p: weighted_astar(
p,
max_nodes=WASTAR_MAX_NODES,
max_seconds=WASTAR_MAX_SECONDS,
heuristic_weight=WASTAR_WEIGHT,
),
),
("D&C", lambda p: divide_and_conquer(p, max_nodes=DC_MAX_NODES)),
]
if puzzle_obj.size <= BFS_MAX_SIZE:
candidates.append(
(
"BFS",
lambda p: bfs(
p,
max_nodes=BFS_MAX_NODES,
max_seconds=BFS_MAX_SECONDS,
),
)
)
if puzzle_obj.size <= DFS_MAX_SIZE:
candidates.append(
(
"DFS",
lambda p: dfs(
p,
max_depth=DFS_MAX_DEPTH,
max_nodes=DFS_MAX_NODES,
max_seconds=DFS_MAX_SECONDS,
),
)
)
candidates.append(
(
"IDS",
lambda p: ids(
p,
max_depth=IDS_MAX_DEPTH,
max_nodes=IDS_MAX_NODES,
max_seconds=IDS_MAX_SECONDS,
),
)
)
if puzzle_obj.size <= 10:
candidates.append(
(
"UCS",
lambda p: ucs(p, max_nodes=UCS_MAX_NODES),
)
)
best_name = ""
best_solution: list[str] | None = None
best_time = float("inf")
for name, solver in candidates:
puzzle_obj.initial_state = state
t0 = perf_counter()
result = solver(puzzle_obj)
dt = perf_counter() - t0
if result is None:
continue
if best_solution is None or len(result) < len(best_solution) or (
len(result) == len(best_solution) and dt < best_time
):
best_time = dt
best_name = name
best_solution = result
if best_solution is None:
return [], "No solver found a path"
return best_solution, f"Best: {best_name} ({len(best_solution)} moves, {best_time:.3f}s)"
def solve_fastest_for_state(size: int, state: tuple[int, ...]) -> tuple[list[str], str]:
"""Try multiple solvers from an immutable state snapshot."""
candidates: list[tuple[str, callable]] = [
(
"A*",
lambda p: astar(
p,
max_nodes=ASTAR_MAX_NODES,
max_seconds=ASTAR_MAX_SECONDS,
heuristic_weight=ASTAR_WEIGHT,
),
),
(
"Greedy",
lambda p: greedy_best_first(
p,
max_nodes=GREEDY_MAX_NODES,
max_seconds=GREEDY_MAX_SECONDS,
),
),
(
"W-A*",
lambda p: weighted_astar(
p,
max_nodes=WASTAR_MAX_NODES,
max_seconds=WASTAR_MAX_SECONDS,
heuristic_weight=WASTAR_WEIGHT,
),
),
("D&C", lambda p: divide_and_conquer(p, max_nodes=DC_MAX_NODES)),
]
if size <= BFS_MAX_SIZE:
candidates.append(
(
"BFS",
lambda p: bfs(
p,
max_nodes=BFS_MAX_NODES,
max_seconds=BFS_MAX_SECONDS,
),
)
)
if size <= DFS_MAX_SIZE:
candidates.append(
(
"DFS",
lambda p: dfs(
p,
max_depth=DFS_MAX_DEPTH,
max_nodes=DFS_MAX_NODES,
max_seconds=DFS_MAX_SECONDS,
),
)
)
candidates.append(
(
"IDS",
lambda p: ids(
p,
max_depth=IDS_MAX_DEPTH,
max_nodes=IDS_MAX_NODES,
max_seconds=IDS_MAX_SECONDS,
),
)
)
if size <= 10:
candidates.append(("UCS", lambda p: ucs(p, max_nodes=UCS_MAX_NODES)))
best_name = ""
best_solution: list[str] | None = None
best_time = float("inf")
for name, solver in candidates:
p = puzzle.Puzzle(size, state)
t0 = perf_counter()
result = solver(p)
dt = perf_counter() - t0
if result is None:
continue
if best_solution is None or len(result) < len(best_solution) or (
len(result) == len(best_solution) and dt < best_time
):
best_time = dt
best_name = name
best_solution = result
if best_solution is None:
return [], "No solver found a path"
return best_solution, f"Best: {best_name} ({len(best_solution)} moves, {best_time:.3f}s)"
def solve_fastest_time_for_state(size: int, state: tuple[int, ...]) -> tuple[list[str], str]:
"""Try multiple solvers and pick the one that returns first (by wall-clock time)."""
candidates: list[tuple[str, callable]] = [
("A*", lambda p: astar(p, max_nodes=ASTAR_MAX_NODES, max_seconds=ASTAR_MAX_SECONDS, heuristic_weight=ASTAR_WEIGHT)),
("Greedy",lambda p: greedy_best_first(p, max_nodes=GREEDY_MAX_NODES, max_seconds=GREEDY_MAX_SECONDS)),
("W-A*", lambda p: weighted_astar(p, max_nodes=WASTAR_MAX_NODES, max_seconds=WASTAR_MAX_SECONDS, heuristic_weight=WASTAR_WEIGHT)),
("D&C", lambda p: divide_and_conquer(p, max_nodes=DC_MAX_NODES)),
]
if size <= BFS_MAX_SIZE:
candidates.append(("BFS", lambda p: bfs(p, max_nodes=BFS_MAX_NODES, max_seconds=BFS_MAX_SECONDS)))
if size <= DFS_MAX_SIZE:
candidates.append(("DFS", lambda p: dfs(p, max_depth=DFS_MAX_DEPTH, max_nodes=DFS_MAX_NODES, max_seconds=DFS_MAX_SECONDS)))
candidates.append(("IDS", lambda p: ids(p, max_depth=IDS_MAX_DEPTH, max_nodes=IDS_MAX_NODES, max_seconds=IDS_MAX_SECONDS)))
if size <= 10:
candidates.append(("UCS", lambda p: ucs(p, max_nodes=UCS_MAX_NODES)))
best_name = ""
best_solution: list[str] | None = None
best_time = float("inf")
for name, solver in candidates:
p = puzzle.Puzzle(size, state)
t0 = perf_counter()
result = solver(p)
dt = perf_counter() - t0
if result is None:
continue
if dt < best_time:
best_time = dt
best_name = name
best_solution = result
if best_solution is None:
return [], "No solver found a path"
return best_solution, f"Fastest: {best_name} ({len(best_solution)} moves, {best_time:.3f}s)"
def compute_hint(puzzle_obj, state: tuple[int, ...]) -> tuple[str, str]:
"""Return a one-step hint and source algorithm info."""
puzzle_obj.initial_state = state
plan = astar(
puzzle_obj,
max_nodes=HINT_MAX_NODES,
max_seconds=HINT_MAX_SECONDS,
heuristic_weight=HINT_WEIGHT,
) or []
if not plan:
if puzzle_obj.checkEnd(state):
return "Already solved", "A*"
return "No hint found", "A*"
return plan[0], "A*"
def save_ui_solver_result(
label: str,
size: int,
solved: bool,
moves: int,
elapsed: float,
peak_kib: float,
):
UI_RESULTS_FILE.parent.mkdir(parents=True, exist_ok=True)
if not UI_RESULTS_FILE.exists():
UI_RESULTS_FILE.write_text(
"algorithm,size,solved,moves,time_s,peak_kib\n",
encoding="utf-8",
)
with UI_RESULTS_FILE.open("a", encoding="utf-8") as f:
f.write(
f"{label},{size},{int(solved)},{moves},{elapsed:.6f},{peak_kib:.2f}\n"
)
def main():
pygame.init()
screen = pygame.display.set_mode((ui.WIN_W, ui.WIN_H))
pygame.display.set_caption("Top Spin")
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 20, bold=True)
font_small = pygame.font.SysFont("arial", 13)
selected_size = DEFAULT_PUZZLE_SIZE
size_index = PUZZLE_SIZE_OPTIONS.index(selected_size)
active_heuristic = "combined_score"
p = newPuzzle(selected_size)
state = p.initial_state
solution = [] # pending moves from solver
status_text = f"New game size={selected_size}"
hint_text = ""
run = True
solver_busy = False
solver_job_id = 0
solver_result_queue: queue.Queue = queue.Queue()
algo_scroll = 0
def apply(action: str):
nonlocal state
if action == "rotate_left":
state = p.rotate_left(state)
p.addToLog("LeftR")
elif action == "rotate_right":
state = p.rotate_right(state)
p.addToLog("RightR")
elif action == "switch":
state = p.switch(state)
p.addToLog("Switch")
initial_state = p.initial_state
solveAssist = False
def start_new_game(size: int):
nonlocal p, state, initial_state, solution, solveAssist
nonlocal solver_busy, solver_job_id, status_text, hint_text
p = newPuzzle(size)
state = p.initial_state
initial_state = p.initial_state
solution = []
solveAssist = False
solver_busy = False
solver_job_id += 1
scramble = 12 if size <= 10 else (36 if size >= 30 else DEFAULT_SCRAMBLE_STEPS)
status_text = f"New game size={size} ({scramble} scramble steps)"
hint_text = ""
def start_solver(label: str, solver_fn):
nonlocal solver_busy, solver_job_id, status_text, hint_text, solveAssist, solution
if solver_busy:
status_text = "A solver is already running"
return
solver_busy = True
solver_job_id += 1
current_job = solver_job_id
solveAssist = True
solution = []
hint_text = ""
status_text = f"Solving with {label}..."
def worker(job_id: int):
expanded_ref = [0]
tracemalloc.start()
t0 = perf_counter()
raw = solver_fn(expanded_ref)
dt = perf_counter() - t0
_, peak_bytes = tracemalloc.get_traced_memory()
tracemalloc.stop()
peak_kib = peak_bytes / 1024.0
if isinstance(raw, tuple):
moves, msg = raw
else:
moves, msg = (raw or []), ""
solver_result_queue.put((job_id, label, moves, msg, dt, peak_kib, expanded_ref[0]))
threading.Thread(target=worker, args=(current_job,), daemon=True).start()
def run_dfs_with_fallback(size: int, snapshot: tuple[int, ...]):
primary = dfs(
puzzle.Puzzle(size, snapshot),
max_depth=DFS_MAX_DEPTH,
max_nodes=DFS_MAX_NODES,
max_seconds=DFS_MAX_SECONDS,
)
if primary is not None:
return primary
return ids(
puzzle.Puzzle(size, snapshot),
max_depth=IDS_MAX_DEPTH,
max_nodes=IDS_MAX_NODES,
max_seconds=IDS_MAX_SECONDS,
)
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEWHEEL:
if event.y != 0:
algo_scroll = max(0, min(ui.algo_scroll_max(), algo_scroll - event.y * 36))
elif event.type == pygame.MOUSEBUTTONDOWN and event.button in (4, 5):
delta = -36 if event.button == 4 else 36
algo_scroll = max(0, min(ui.algo_scroll_max(), algo_scroll + delta))
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
apply("rotate_left")
elif event.key == pygame.K_RIGHT:
apply("rotate_right")
elif event.key in (pygame.K_SPACE,):
apply("switch")
elif event.key in (pygame.K_1, pygame.K_KP1):
size_index = 0
selected_size = PUZZLE_SIZE_OPTIONS[size_index]
start_new_game(selected_size)
elif event.key in (pygame.K_2, pygame.K_KP2):
if len(PUZZLE_SIZE_OPTIONS) > 1:
size_index = 1
selected_size = PUZZLE_SIZE_OPTIONS[size_index]
start_new_game(selected_size)
elif event.key in (pygame.K_3, pygame.K_KP3):
if len(PUZZLE_SIZE_OPTIONS) > 2:
size_index = 2
selected_size = PUZZLE_SIZE_OPTIONS[size_index]
start_new_game(selected_size)
elif event.key in (pygame.K_3, pygame.K_KP3, pygame.K_4, pygame.K_KP4, pygame.K_5, pygame.K_KP5):
# Size presets are intentionally capped at 10/20.
continue
else:
for i, btn in enumerate(ui.heuristic_btns):
if btn.is_clicked(event):
active_heuristic = ui.HEURISTIC_KEYS[i]
status_text = f"Heuristic: {ui.HEURISTIC_LABELS[i]}"
if ui.bfs_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
if size > BFS_MAX_SIZE:
status_text = f"BFS disabled for size>{BFS_MAX_SIZE}"
continue
start_solver(
"BFS",
lambda er: bfs(puzzle.Puzzle(size, snapshot), max_nodes=BFS_MAX_NODES, max_seconds=BFS_MAX_SECONDS, expanded_ref=er),
)
elif ui.ids_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
if size > DFS_MAX_SIZE:
status_text = f"IDS disabled for size>{DFS_MAX_SIZE}"
continue
start_solver(
"IDS",
lambda er: ids(puzzle.Puzzle(size, snapshot), max_depth=IDS_MAX_DEPTH, max_nodes=IDS_MAX_NODES, max_seconds=IDS_MAX_SECONDS, expanded_ref=er),
)
elif ui.ucs_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
if size > 10:
status_text = "UCS disabled for size>10"
continue
start_solver(
"UCS",
lambda er: ucs(puzzle.Puzzle(size, snapshot), max_nodes=UCS_MAX_NODES, expanded_ref=er),
)
elif ui.dfs_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
if size > DFS_MAX_SIZE:
status_text = f"DFS disabled for size>{DFS_MAX_SIZE}"
continue
start_solver(
"DFS",
lambda _er: run_dfs_with_fallback(size, snapshot),
)
elif ui.greedy_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
h_fn = HEURISTICS[active_heuristic]
start_solver(
f"Greedy({ui.HEURISTIC_LABELS[ui.HEURISTIC_KEYS.index(active_heuristic)]})",
lambda er, h=h_fn: greedy_best_first(puzzle.Puzzle(size, snapshot), max_nodes=GREEDY_MAX_NODES, max_seconds=GREEDY_MAX_SECONDS, heuristic_fn=h, expanded_ref=er),
)
elif ui.astar_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
h_fn = HEURISTICS[active_heuristic]
start_solver(
f"A*({ui.HEURISTIC_LABELS[ui.HEURISTIC_KEYS.index(active_heuristic)]})",
lambda er, h=h_fn: astar(puzzle.Puzzle(size, snapshot), max_nodes=ASTAR_MAX_NODES, max_seconds=ASTAR_MAX_SECONDS, heuristic_weight=ASTAR_WEIGHT, heuristic_fn=h, expanded_ref=er),
)
elif ui.wastar_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
h_fn = HEURISTICS[active_heuristic]
start_solver(
f"W-A*({ui.HEURISTIC_LABELS[ui.HEURISTIC_KEYS.index(active_heuristic)]})",
lambda er, h=h_fn: weighted_astar(puzzle.Puzzle(size, snapshot), max_nodes=WASTAR_MAX_NODES, max_seconds=WASTAR_MAX_SECONDS, heuristic_weight=WASTAR_WEIGHT, heuristic_fn=h, expanded_ref=er),
)
elif ui.dc_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
start_solver(
"D&C",
lambda _er: divide_and_conquer(puzzle.Puzzle(size, snapshot), max_nodes=DC_MAX_NODES),
)
elif ui.fast_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
start_solver("Best", lambda: solve_fastest_for_state(size, snapshot))
elif ui.fastest_btn.is_clicked(event, algo_scroll):
snapshot = state
size = p.size
start_solver("Fastest", lambda: solve_fastest_time_for_state(size, snapshot))
elif ui.hint_btn.is_clicked(event, algo_scroll):
move, source = compute_hint(p, state)
hint_text = f"{move} ({source})"
status_text = "Hint ready"
elif ui.new_btn.is_clicked(event, algo_scroll):
start_new_game(selected_size)
elif ui.size_minus_btn.is_clicked(event, algo_scroll):
size_index = (size_index - 1) % len(PUZZLE_SIZE_OPTIONS)
selected_size = PUZZLE_SIZE_OPTIONS[size_index]
start_new_game(selected_size)
elif ui.size_plus_btn.is_clicked(event, algo_scroll):
size_index = (size_index + 1) % len(PUZZLE_SIZE_OPTIONS)
selected_size = PUZZLE_SIZE_OPTIONS[size_index]
start_new_game(selected_size)
elif ui.reset_btn.is_clicked(event, algo_scroll):
state = initial_state
p.log = {}
solution = []
solveAssist = False
solver_busy = False
solver_job_id += 1
status_text = "Reset"
hint_text = ""
while not solver_result_queue.empty():
job_id, label, moves, msg, elapsed, peak_kib, expanded = solver_result_queue.get()
if job_id != solver_job_id:
continue
solver_busy = False
solution = moves
solved = bool(moves)
move_count = len(moves) if moves else -1
save_ui_solver_result(
label=label,
size=p.size,
solved=solved,
moves=move_count,
elapsed=elapsed,
peak_kib=peak_kib,
)
if msg:
status_text = msg
elif moves:
exp_str = f", {expanded} expanded" if expanded > 0 else ""
status_text = (
f"{label}: {len(moves)} moves ({elapsed:.3f}s{exp_str}, {peak_kib:.1f} KiB)"
)
else:
status_text = (
f"{label}: no solution found ({elapsed:.3f}s, {peak_kib:.1f} KiB)"
)
# Animate one solution step per frame
if solution:
apply(solution.pop(0))
puzzle_solved = p.checkEnd(state)
if puzzle_solved and not solveAssist and status_text not in ("Reset",) and "Solved" not in status_text:
status_text = "Solved! Press New Game to play again."
ui.draw(
screen,
state,
p,
font,
font_small,
status_text,
hint_text,
current_size=selected_size,
recommended_max_size=RECOMMENDED_MAX_SIZE,
algo_scroll=algo_scroll,
active_heuristic=active_heuristic,
puzzle_solved=puzzle_solved,
)
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()