-
Notifications
You must be signed in to change notification settings - Fork 1
/
game_tree.py
85 lines (69 loc) · 2.68 KB
/
game_tree.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
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
from sgfmill import sgf
import numpy as np
class GameNode:
def __init__(self):
self.state = None
self.parent = None
self.sgf_node = None
def difference_from_parent(self):
try:
diff = self.state - self.parent.state
except AttributeError:
# There is no parent for this state!
return None
changed_coords = np.nonzero(diff)
# Convert coords into a list of moves
# Format: [((2, 1), 'w')]
moves = list(zip(changed_coords[0], changed_coords[1]))
m = ['.', 'b', 'w']
colors = [m[self.state[x[0], x[1]]] for x in moves]
sgf_friendly_moves = list(zip(colors, moves))
return sgf_friendly_moves
class GameTree:
def __init__(self, size):
# For quick access to all gamestates
self.state_map = {}
self.current_state = None
self.sgf_game = sgf.Sgf_game(size=size)
def update(self, state):
"""Update the gametree.
Returns:
bool: True if board state changed, False otherwise.
GameNode: The current GameNode
"""
# Convert state to something hashable
hashable = str(state)
# If this is the same as last time, no action required
if self.current_state == hashable:
return False, self.state_map[hashable]
# If we have not seen this state before..
if not (hashable in self.state_map):
print("Unique state!")
gn = GameNode()
gn.state = state
gn.parent = self.state_map.get(self.current_state, None)
sgf_node = None
if gn.parent:
diffs = gn.difference_from_parent()
if len(diffs) == 1 and gn.parent.sgf_node is not None:
# This could be a valid sgf move.
node = gn.parent.sgf_node.new_child()
try:
# Can throw an error if this move is invalid.
node.set_move(diffs[0][0], diffs[0][1])
sgf_node = node
except ValueError:
print("ERROR: Invalid move.")
print("Further moves on this branch not recordable.")
node.delete()
else:
# This is the first move!
print("made the first move.")
sgf_node = self.sgf_game.get_last_node()
gn.sgf_node = sgf_node
self.state_map[hashable] = gn
else:
print("Rollback!")
# Keep track of the current state
self.current_state = hashable
return True, self.state_map[hashable]