-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_sim.py
57 lines (50 loc) · 1.97 KB
/
game_sim.py
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
from board import Board, BoardCache
# A smaller board for performance profiling
small_starting_board = [
[None, 'X', 'X', 'X', None],
['X', 'X', 'X', 'X', 'X'],
['X', 'X', 'O', 'X', 'X'],
['X', 'X', 'X', 'X', 'X'],
[None, 'X', 'X', 'X', None],
]
# The standard peg solitaire starting board, English version
starting_board = [
[None, None, 'X', 'X', 'X', None, None],
[None, None, 'X', 'X', 'X', None, None],
['X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'O', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'X', 'X'],
[None, None, 'X', 'X', 'X', None, None],
[None, None, 'X', 'X', 'X', None, None],
]
# The weird peg solitaire starting board I found on the weekend away
other_starting_board = [
[None, None, None, 'X', 'X', 'X', None, None, None],
[None, None, None, 'X', 'X', 'X', None, None, None],
[None, None, None, 'X', 'X', 'X', None, None, None],
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
[None, None, None, 'X', 'X', 'X', None, None, None],
[None, None, None, 'X', 'X', 'X', None, None, None],
[None, None, None, 'X', 'X', 'X', None, None, None],
]
# There are a lot of possible moves, but a lot less possible board states.
# If we keep a cache of all the board states we have visited, we don't
# need to revisit them, because we know where they lead, eliminating
# a lot of unnecessary calculation.
board = Board(starting_board)
board_cache = BoardCache([board])
# Depth first search because we only want to find one solution
def get_moves(board):
if board.win:
return board.history
for move in board.moves:
new_board = Board.from_board(board)
new_board.move(*move)
if new_board not in board_cache:
solution = get_moves(new_board)
if solution is not None:
return solution
return None
print get_moves(board)