def apply_grid(self,grid,backwards=False): if not isinstance(grid,Grid): raise TicTacToeHashException( 'grid is not a valid Grid instance. Instead a {}' \ 'instance was passed.Cannot apply Grid'.format(type(grid))) applied_hash = self.hash | grid.hash applied_grid = [Cell.from_hash(hash=h) for h in decompose_grid_hash(hash=applied_hash,mode=self.MODE)] for c in applied_grid: if (self[c.number].player != FREE_SPACE) and (c.player != self[c.number].player): raise CellIsTaken( 'Cell {} has been taken by player {} already, ' \ 'and cannot override Grid.Grid applied ' \ 'failed'.format(c.number,self[c.number].player)) if not backwards: if applied_hash != grid.hash: raise IncompatibleGrid( 'New grid cannot go backwards in moves. Must provide all the '\ 'previous moves plus 1 or more moves.') return self if applied_hash == self.hash else self.GRID_KLASS(hash=applied_hash)
def __init__(self,hash=None): if hash is None: hash = new_game_hash(sum_cells=True,mode=self.MODE) verify_hash(hash=hash,mode=GAME_MODES[self.MODE]['GRID']) self._hash = hash self._binary = None self._hash_map = CELL_HASH_TABLE[self.MODE] self._cells = [self.CELL_KLASS.from_hash(hash=h) for h in decompose_grid_hash(hash=self._hash,mode=self.MODE)] state_hash = sum([ ( 1 << n) for n, c in enumerate(self._cells) if (c.player == PLAYER_1 or c.player == PLAYER_2)]) self._state = self.GRID_STATE_KLASS(hash=state_hash) self.validate_grid()