async def load_game_by_id(game_id): g = Game(game_id=game_id) res = await db.execute(Search.sql_load_game_by_id(game_id)) if len(res) == 0: raise RuntimeError(f'Could not find game game_id({g.id})') res = res[0] g.date = datetime.datetime.strptime(res[0], '%Y-%m-%d %H:%M:%S') g.score_won = res[1] g.score_lost = res[2] res = await db.execute(Search.sql_load_game_players_by_id(game_id)) for record in res: won = record[1] p = await Search.load_player_by_id(player_id=record[0]) if won: g.nicks_won.append(p.nick) else: g.nicks_lost.append(p.nick) res = await db.execute( Search.sql_rating_change(g.id, p.id, ratingSystem)) if len(res) == 0: raise RuntimeError( f'Could not find rating change for game_id({g.id}), player_id({p.id})' ) g.set_rating_before(p.nick, Rating(value=res[0][0], accuracy=res[0][2])) g.set_rating_after(p.nick, Rating(value=res[0][1], accuracy=res[0][3])) logger.debug(f'load_game_by_id {g}') return g
async def post_game(self, args: typing.Dict): logger.debug(f'post_game {args}') request = valid_request_from_dict(AddGameRequest, args) players = [] for nick in request.nicks_won + request.nicks_lost: player = await self._search.load_player_by_nick(nick) if player is None: raise RuntimeError(f'Player not found: {nick}') if player.get_rating() is None: raise RuntimeError(f'Player rating is not set') players.append(player) game = Game(nicks_won=request.nicks_won, nicks_lost=request.nicks_lost, score_won=request.score_won, score_lost=request.score_lost, date=datetime.now()) for player in players: game.set_rating_before(player.nick, player.get_rating()) self.ranking.calculate(game) await self._manage.save_game(game) for player in players: player.set_rating(game.rating_after(player.nick)) await self._manage.save_player(player) return game.as_dict()
def test_add_game_ok_2(server_credentials): host, port = server_credentials client = RestClient('localhost', 8080) err, response = client.add_game(game=Game(nicks_won=['p1', 'p2'], nicks_lost=['p3', 'p4'], score_won=15, score_lost=13)) assert type(response).__name__ == 'Game'
async def get_games(self, args: typing.Dict): request = valid_request_from_dict(GamesRequest, args) return [Game( nicks_won=[request.nick, request.with_nicks[0]], nicks_lost=[request.vs_nicks[0], 'p9'], score_won=16, score_lost=14, date=datetime.datetime.now() ).as_dict()]
async def test_all(): g = None team_won = [] team_lost = [] try: # create players for i in range(0, 4): p = Player(nick=f'NewPlayer{i}') p.set_rating(Rating(value=1200, accuracy=0)) await Manage.delete_player(p) await Manage.save_player(p) if i < 2: team_won.append(p) else: team_lost.append(p) g = Game(date=datetime.now(), nicks_won=[p.nick for p in team_won], nicks_lost=[p.nick for p in team_lost], score_won=23, score_lost=21) for p in team_won: g.set_rating_before(p.nick, p.get_rating()) p.set_rating(Rating(value=1300, accuracy=0)) g.set_rating_after(p.nick, p.get_rating()) for p in team_lost: g.set_rating_before(p.nick, p.get_rating()) p.set_rating(Rating(value=1100, accuracy=0)) g.set_rating_after(p.nick, p.get_rating()) await Manage.save_game(g) test_g = await Search.load_game_by_id(g.id) assert test_g.nicks_won == ['NewPlayer0', 'NewPlayer1'] assert test_g.nicks_lost == ['NewPlayer2', 'NewPlayer3'] for nick in test_g.nicks_won: assert test_g.rating_before(nick) == Rating(value=1200, accuracy=0) assert test_g.rating_after(nick) == Rating(value=1300, accuracy=0) for nick in test_g.nicks_lost: assert test_g.rating_before(nick) == Rating(value=1200, accuracy=0) assert test_g.rating_after(nick) == Rating(value=1100, accuracy=0) assert test_g.score_won == 23 assert test_g.score_lost == 21 finally: # clear await Manage.delete_game(g) for p in team_won + team_lost: await Manage.delete_player(p)
def game(self, user_input=None, processing_message=None): logger.debug('players') if user_input is None or len(user_input) == 0 and self.state.is_init: return self.game_add(processing_message=processing_message) if user_input is not None: params = user_input.split(';') nicks_won = params[0:2] nicks_lost = params[2:4] score_won = params[4] score_lost = params[5] self._game = Game(nicks_won=nicks_won, nicks_lost=nicks_lost, score_won=score_won, score_lost=score_lost) for nick in params[0:3]: err, p = self.backend.get_player(nick=nick) self._check_error_is_fatal(err, processing_message) if err is not None: return self.goto_init( message=self.text.nick_not_exists() + '\n' + self.text.cancel(), processing_message=processing_message) self._game.set_rating_before(nick=nick, rating=p.get_rating()) err, g = self.backend.add_game(game=self._game, who=processing_message.ids.user_id) self._check_error_is_fatal(err, processing_message) if err is not None: return self.goto_init(message=self.text.game_save_fail(err), processing_message=processing_message) self._game = g self.show_message(message=self.text.game_saved(), processing_message=processing_message)
async def test_all(): # create players team_won = [] team_lost = [] g = None try: for i in range(0, 4): p = Player(nick=f'NewPlayer{i}', phone=f'7916123456{i}') p.set_rating(Rating(value=1200 + i, accuracy=1)) if i < 2: team_won.append(p) else: team_lost.append(p) await Manage.delete_player(p) await Manage.save_player(p) # find players LIKE players = await Search.load_players_nick_like('New') assert len(players) == 4 players = await Search.load_players_nick_like('NewNotExists') assert len(players) == 0 # game g = Game(date=datetime.now(), nicks_won=[p.nick for p in team_won], nicks_lost=[p.nick for p in team_lost], score_won=15, score_lost=10) for p in team_won: g.set_rating_before(p.nick, p.get_rating()) p.set_rating(Rating(value=p.get_rating().value + 100, accuracy=p.get_rating().accuracy)) g.set_rating_after(p.nick, p.get_rating()) await Manage.save_player(p) for p in team_lost: g.set_rating_before(p.nick, p.get_rating()) p.set_rating(Rating(value=p.get_rating().value - 100, accuracy=p.get_rating().accuracy)) g.set_rating_after(p.nick, p.get_rating()) await Manage.save_player(p) await Manage.save_game(g) # find game res = await Search.games(player=team_lost[0]) assert res[0].id == g.id # find games vs res = await Search.games(player=team_won[0], vs_players=[team_lost[0]]) assert len(res) == 1 assert res[0].id == g.id # not find games vs res = await Search.games(player=team_lost[0], vs_players=[team_lost[1]]) assert len(res) == 0 # find games with res = await Search.games(player=team_lost[1], with_players=[team_lost[0]]) assert len(res) == 1 assert res[0].id == g.id # not find games with res = await Search.games(player=team_lost[0], with_players=[team_won[1]]) assert len(res) == 0 # find games vs and with res = await Search.games(player=team_lost[0], vs_players=[team_won[0]], with_players=[team_lost[1]]) assert len(res) == 1 assert res[0].id == g.id # not find games vs res = await Search.games(player=team_lost[1], vs_players=[team_won[1]], with_players=[team_won[0]]) assert len(res) == 0 res = await Search.games(player=team_lost[0], vs_players=[team_lost[1]], with_players=[team_lost[1]]) assert len(res) == 0 finally: # clear await Manage.delete_game(g) for player in team_lost + team_won: await Manage.delete_player(player)
def import_game(app_id: str, key: str) -> Game: store_info = fetch_store_info(app_id) # Create Graph object for game game = Game() game.steam_app_id = app_id if str(app_id) not in store_info or "data" not in store_info[str(app_id)]: log.info( "Could not retrieve store information for %d. Flagging game as incomplete.", app_id) # Create a dummy game for incomplete data game.name = str(app_id) game.incomplete = True else: # Take name from store API game.name = store_info[str(app_id)]["data"]["name"] # Check, if the game incomplete or has achievements, otherwise, we're done now if game.incomplete is True or ( "achievements" in store_info[str(app_id)]["data"] and store_info[str(app_id)]["data"]["achievements"]["total"] > 0): # Get schema for game schema = get_schema_for_game(app_id, key) # If the schema also does not contain any name, we can only return now if "gameName" not in schema["game"]: return game # If its an incomplete game, at least try to find a name from the schema (although it might be a wierd test name) if game.incomplete is True: game.name = schema["game"]["gameName"] # If the name is valid, i.e. not a ValveTestAppName, we can take away the incomplete flag if game.name != ("ValveTestApp" + str(app_id)): log.info( "Found a valid name for %d. Recovered from incomplete state.", app_id) game.incomplete = False # Save the game so its available game.save() try: log.info("Need to insert %d achievements for %s", len(schema["game"]["availableGameStats"]["achievements"]), game.name) # Walk thru all achievements for game and save into game for a in schema["game"]["availableGameStats"]["achievements"]: achievement = Achievement() # achievement "names" are not globally unique # achievement.id = str(game.id) + "_" + a["name"] achievement.api_name = a["name"] achievement.name = a["displayName"] achievement.source = "Steam" # Description is optional if "description" in a: achievement.description = a["description"] # save the achievement achievement.save() game.achievements.connect(achievement) except Exception: log.error( "Could not parse achievement data for %s. Maybe the game does not contain any achievements.", game.name, exception) return game
def game_add(self, user_input=None, processing_message=None): logger.debug('game_add') self._game = Game() self.show_message(message=self.text.game(), processing_message=processing_message)