def close(self): diff = self._difference(self._last, self._current) self._last = self._current self._current = copy_board(self._last) self._changes.append(diff) index = len(self) - 1 if index % self._cache_frequency == 0: self._store(index, self._last)
def _compute_game_state(self, current_board, in_index, out_index): length = len(self._changes) board = copy_board(current_board) if in_index < out_index: for i in range(in_index, out_index): changes = self._changes[i] self._forward(board, changes, copy=False) elif in_index > out_index: for i in range(in_index - 1, out_index - 1, -1): changes = self._changes[i] self._backward(board, changes, copy=False) return board
def get_state(self, index): assert 0 <= index < len(self), "Invalid index" found = False if index in self._cache: out_board = self._cache[index] found = True if not found: origin = index - index % self._cache_frequency print index, origin in_board = self._cache[origin] out_board = self._compute_game_state(in_board, origin, index) found = True return copy_board(out_board)
def _backward(self, current, changes, copy=True): if copy: future = copy_board(current) else: future = current for key in changes: change = changes[key] # reverse order add = change // BASE remove = change % BASE if add == EMPTY and key in future: del future[key] else: future[key] = add return future
def _forward(self, current, changes, copy=True): if copy: future = copy_board(current) else: future = current for key in changes: change = changes[key] # extract removed and added colors from 2 digit number remove = change // BASE add = change % BASE if add == EMPTY and key in future: del future[key] else: future[key] = add return future