def deserialize(self, objStr, gameInst=None): obj = json.loads(objStr.decode('UTF8')) self.key = obj["key"] #self.knownGameState = obj["knownGameState"] if gameInst is not None: self.game = gameInst else: if obj['gameKey'] is not None and Db.instance().keyExists(obj["gameKey"]): self.game = Game(obj["gameKey"]) else: self.game = None
def findNew(player): db = Db.instance() game = None # check if there are any games waiting for second player if db.lenList(GAME_WAITING_QUEUE) > 0: # if there are, remove one from queue gameKey = db.listPopLeft(GAME_WAITING_QUEUE) game = Game(gameKey) else: # if not, create new game and append it to waiting list game = Game() game.state = GameState.searchingPlayers db.listAppend(GAME_WAITING_QUEUE, game.key) game.addPlayer(player) game.update() return game
def cleanup(): """ This function should run in separate greenlet with some time interval. It iterates through games queue and checks if they have at least one player. If they dont, it removes given games from list """ db = Db.instance() numCleaned = 0 gamesQueue = db.retrieveList(GAME_WAITING_QUEUE) if gamesQueue is None: return for gameKey in gamesQueue: game = Game(gameKey) if len(game.players) == 0: db.removeFromList(GAME_WAITING_QUEUE, gameKey) numCleaned += 1 return numCleaned
def __init__(self, playerId=None, gameInst=None, knownGameState=0): self.key = playerId # app-wide unique key if knownGameState is not None: self.knownGameState = knownGameState # increments as player receives updates else: self.knownGameState = 0 self.game = None # the game this player currently bound to db = Db.instance() # Generate key if needed if self.key is None: self.key = db.generateKey() # Check if player with such key exists. If he does, retrieve his # info from db. If he does not, create him if db.keyExists(self.key): self.deserialize(db.retrieve(self.key), gameInst) else: db.store(self.key, self.serialize())
def __init__(self, key=None): self.key = key self.players = [] # player[0] is 'o', player[1] is 'x' self.activePlayer = None # whose turn is now? self.grid = ['' for _ in range(9)] # 3x3 game grid # This variable is needed to keep in sync with both players. It is # incremented each time game state is updated (e.g. player makes a move). # Each player stores his value of stateFrame, so if player's copy is # less than game's, his game state is considered outdated self.stateFrame = 0 self.winner = None self.state = GameState.idle db = Db.instance() if self.key is None or db.retrieve(self.key) is None: self.key = db.generateKey() else: self.deserialize(db.retrieve(self.key)) self.checkIfPlayersActive()
def dbSave(self): """ This method is called whenever player state needs to be saved in database """ Db.instance().store(self.key, self.serialize())
def dbSave(self): Db.instance().store(self.key, self.serialize())