Implemented sgf file saving, loading, and tracking during play

This commit is contained in:
2012-04-21 23:29:33 -04:00
parent da935d8e46
commit 00448c967f
2 changed files with 56 additions and 5 deletions

View File

@ -33,10 +33,14 @@ class Goban:
self.winner = Goban.EMPTY
self.file_name = file_name
# Track our game in an easily saveable format!
self.sgf_game = None
if self.file_name is not None:
self.load_sgf(file_name)
else:
self.sgf_game = sgf.Sgf_game(self.board_size)
def load_sgf(self, file_name):
@ -56,11 +60,29 @@ class Goban:
for point in white:
self.board[self._real_pos(point)] = Goban.WHITE
for node in self.sgf_game.get_main_sequence():
color, pos = node.get_move()
if color is not None:
self.play_move(color, pos)
if pos == 'pass':
self.pass_move(color)
else:
self.play_move(pos, color)
def save_sgf(self, file_name=None):
'''Saves the current game as an SGF file. If file_name is None, we use the previously specified filename.
If there is no previously specified filename, we raise an exception.'''
if self.file_name is None and file_name is not None:
self.file_name = file_name
if file_name is None:
file_name = self.file_name
if file_name is None:
return # fixme - this should be an exception instead
with open(file_name, 'w') as fn:
fn.write(self.sgf_game.serialise())
def set_hover(self, pos):
@ -88,6 +110,7 @@ class Goban:
self.hover = None
self.elapsed_time = 0
self.winner = Goban.EMPTY
self.sgf_game = sgf.Sgf_game(self.board_size)
def set_board_size(self, new_size):
@ -134,6 +157,9 @@ class Goban:
self.last_move = rpos
self.passed_last = False
node = self.sgf_game.extend_main_sequence()
node.set_move(color, pos)
self.to_move = self._other_color(color)
self.clear_hover()
@ -155,6 +181,9 @@ class Goban:
if self.last_move is not None:
self._changed.append(self.last_move)
node = self.sgf_game.extend_main_sequence()
node.set_move(color, 'pass')
if self.passed_last:
self.to_move = Goban.EMPTY
self.winner = Goban.SCORING
@ -429,7 +458,6 @@ class Goban:
return ret
def _real_pos(self, pos):
x,y = pos
return x * self.board_size + y