Exemple #1
0
 def rateGame(self, game):
   """
     Takes a game with 2 players and alters their ratings
     based on the result of the game.
     Returns self.
     Side effects:
       Changes the game's players' ratings in the database.
   """
   player1 = game.players[0]
   player2 = game.players[1]
   # TODO: Support draws. Since it's impossible to draw in the game currently,
   # the database model, and therefore this code, requires a winner.
   # The Elo implementation does not, however.
   result = 1 if player1 == game.winner else -1
   rating_adjustment1 = get_rating_adjustment(player1.rating, player2.rating,
     len(player1.games), len(player2.games), result)
   rating_adjustment2 = get_rating_adjustment(player2.rating, player1.rating,
     len(player2.games), len(player1.games), result * -1)
   if result == 1:
     resultQualitative = "won"
   elif result == 0:
     resultQualitative = "drew"
   else:
     resultQualitative = "lost"
   name1 = '@'.join(player1.jid.split('@')[:-1])
   name2 = '@'.join(player2.jid.split('@')[:-1])
   self.lastRated = "A rated game has ended. %s %s against %s. Rating Adjustment: %s (%s -> %s) and %s (%s -> %s)."%(name1, 
     resultQualitative, name2, name1, player1.rating, player1.rating + rating_adjustment1,
     name2, player2.rating, player2.rating + rating_adjustment2)
   player1.rating += rating_adjustment1
   player2.rating += rating_adjustment2
   db.commit()
   return self
Exemple #2
0
    def rateGame(self, game):
        """
      Takes a game with 2 players and alters their ratings
      based on the result of the game.
      Returns self.
      Side effects:
        Changes the game's players' ratings in the database.
    """
        player1 = game.players[0]
        player2 = game.players[1]
        # TODO: Support draws. Since it's impossible to draw in the game currently,
        # the database model, and therefore this code, requires a winner.
        # The Elo implementation does not, however.
        result = 1 if player1 == game.winner else -1
        # Player's ratings are -1 unless they have played a rated game.
        if player1.rating == -1:
            player1.rating = leaderboard_default_rating
        if player2.rating == -1:
            player2.rating = leaderboard_default_rating

        rating_adjustment1 = int(
            get_rating_adjustment(player1.rating, player2.rating, len(player1.games), len(player2.games), result)
        )
        rating_adjustment2 = int(
            get_rating_adjustment(player2.rating, player1.rating, len(player2.games), len(player1.games), result * -1)
        )
        if result == 1:
            resultQualitative = "won"
        elif result == 0:
            resultQualitative = "drew"
        else:
            resultQualitative = "lost"
        name1 = "@".join(player1.jid.split("@")[:-1])
        name2 = "@".join(player2.jid.split("@")[:-1])
        self.lastRated = (
            "A rated game has ended. %s %s against %s. Rating Adjustment: %s (%s -> %s) and %s (%s -> %s)."
            % (
                name1,
                resultQualitative,
                name2,
                name1,
                player1.rating,
                player1.rating + rating_adjustment1,
                name2,
                player2.rating,
                player2.rating + rating_adjustment2,
            )
        )
        player1.rating += rating_adjustment1
        player2.rating += rating_adjustment2
        if not player1.highest_rating:
            player1.highest_rating = -1
        if not player2.highest_rating:
            player2.highest_rating = -1
        if player1.rating > player1.highest_rating:
            player1.highest_rating = player1.rating
        if player2.rating > player2.highest_rating:
            player2.highest_rating = player2.rating
        db.commit()
        return self
Exemple #3
0
    def rateGame(self, game):
        """
      Takes a game with 2 players and alters their ratings
      based on the result of the game.
      Returns self.
      Side effects:
        Changes the game's players' ratings in the database.
    """
        player1 = game.players[0]
        player2 = game.players[1]
        # TODO: Support draws. Since it's impossible to draw in the game currently,
        # the database model, and therefore this code, requires a winner.
        # The Elo implementation does not, however.
        result = 1 if player1 == game.winner else -1
        # Player's ratings are -1 unless they have played a rated game.
        if player1.rating == -1:
            player1.rating = leaderboard_default_rating
        if player2.rating == -1:
            player2.rating = leaderboard_default_rating

        rating_adjustment1 = int(
            get_rating_adjustment(player1.rating, player2.rating,
                                  len(player1.games), len(player2.games),
                                  result))
        rating_adjustment2 = int(
            get_rating_adjustment(player2.rating, player1.rating,
                                  len(player2.games), len(player1.games),
                                  result * -1))
        if result == 1:
            resultQualitative = "won"
        elif result == 0:
            resultQualitative = "drew"
        else:
            resultQualitative = "lost"
        name1 = '@'.join(player1.jid.split('@')[:-1])
        name2 = '@'.join(player2.jid.split('@')[:-1])
        self.lastRated = "A rated game has ended. %s %s against %s. Rating Adjustment: %s (%s -> %s) and %s (%s -> %s)." % (
            name1, resultQualitative, name2, name1, player1.rating,
            player1.rating + rating_adjustment1, name2, player2.rating,
            player2.rating + rating_adjustment2)
        player1.rating += rating_adjustment1
        player2.rating += rating_adjustment2
        if not player1.highest_rating:
            player1.highest_rating = -1
        if not player2.highest_rating:
            player2.highest_rating = -1
        if player1.rating > player1.highest_rating:
            player1.highest_rating = player1.rating
        if player2.rating > player2.highest_rating:
            player2.highest_rating = player2.rating
        db.commit()
        return self
Exemple #4
0
 def getOrCreatePlayer(self, JID):
   """
     Stores a player(JID) in the database if they don't yet exist.
     Returns either the newly created instance of
     the Player model, or the one that already
     exists in the database.
   """
   players = db.query(Player).filter_by(jid=str(JID))
   if not players.first():
     player = Player(jid=str(JID), rating=-1)
     db.add(player)
     db.commit()
     return player
   return players.first()
Exemple #5
0
 def getOrCreatePlayer(self, JID):
   """
     Stores a player(JID) in the database if they don't yet exist.
     Returns either the newly created instance of
     the Player model, or the one that already
     exists in the database.
   """
   players = db.query(Player).filter_by(jid=str(JID))
   if not players.first():
     player = Player(jid=str(JID), rating=-1)
     db.add(player)
     db.commit()
     return player
   return players.first()
Exemple #6
0
  def addGame(self, gamereport):
    """
      Adds a game to the database and updates the data
      on a player(JID) from game results.
      Returns the created Game object, or None if
      the creation failed for any reason.
      Side effects:
        Inserts a new Game instance into the database.
    """
    # Discard any games still in progress.
    if any(map(lambda state: state == 'active',
               dict.values(gamereport['playerStates']))):
      return None

    players = map(lambda jid: db.query(Player).filter_by(jid=jid).first(),
                  dict.keys(gamereport['playerStates']))

    winning_jid = list(dict.keys({jid: state for jid, state in
                                  gamereport['playerStates'].items()
                                  if state == 'won'}))[0]

    def get(stat, jid):
      return gamereport[stat][jid]

    stats = {'civ': 'civs', 'foodGathered': 'foodGathered', 'foodUsed': 'foodUsed',
             'woodGathered': 'woodGathered', 'woodUsed': 'woodUsed',
             'stoneGathered': 'stoneGathered', 'stoneUsed': 'stoneUsed',
             'metalGathered': 'metalGathered', 'metalUsed': 'metalUsed'}

    playerInfos = []
    for player in players:
      jid = player.jid
      playerinfo = PlayerInfo(player=player)
      for dbname, reportname in stats.items():
        setattr(playerinfo, dbname, get(reportname, jid))
      playerInfos.append(playerinfo)

    game = Game(map=gamereport['mapName'], duration=int(gamereport['timeElapsed']))
    game.players.extend(players)
    game.player_info.extend(playerInfos)
    game.winner = db.query(Player).filter_by(jid=winning_jid).first()
    db.add(game)
    db.commit()
    return game
Exemple #7
0
  def addGame(self, gamereport):
    """
      Adds a game to the database and updates the data
      on a player(JID) from game results.
      Returns the created Game object, or None if
      the creation failed for any reason.
      Side effects:
        Inserts a new Game instance into the database.
    """
    # Discard any games still in progress.
    if any(map(lambda state: state == 'active',
               dict.values(gamereport['playerStates']))):
      return None

    players = map(lambda jid: db.query(Player).filter(Player.jid.ilike(str(jid))).first(),
                  dict.keys(gamereport['playerStates']))

    winning_jid = list(dict.keys({jid: state for jid, state in
                                  gamereport['playerStates'].items()
                                  if state == 'won'}))[0]
    def get(stat, jid):
      return gamereport[stat][jid]

    singleStats = {'timeElapsed', 'mapName', 'teamsLocked', 'matchID'}
    totalScoreStats = {'economyScore', 'militaryScore', 'totalScore'}
    resourceStats = {'foodGathered', 'foodUsed', 'woodGathered', 'woodUsed', 
            'stoneGathered', 'stoneUsed', 'metalGathered', 'metalUsed', 'vegetarianFoodGathered',
            'treasuresCollected', 'lootCollected', 'tributesSent', 'tributesReceived'}
    unitsStats = {'totalUnitsTrained', 'totalUnitsLost', 'enemytotalUnitsKilled', 'infantryUnitsTrained',
            'infantryUnitsLost', 'enemyInfantryUnitsKilled', 'workerUnitsTrained', 'workerUnitsLost',
            'enemyWorkerUnitsKilled', 'femaleUnitsTrained', 'femaleUnitsLost', 'enemyFemaleUnitsKilled',
            'cavalryUnitsTrained', 'cavalryUnitsLost', 'enemyCavalryUnitsKilled', 'championUnitsTrained',
            'championUnitsLost', 'enemyChampionUnitsKilled', 'heroUnitsTrained', 'heroUnitsLost',
            'enemyHeroUnitsKilled', 'shipUnitsTrained', 'shipUnitsLost', 'enemyShipUnitsKilled', 'traderUnitsTrained',
            'traderUnitsLost', 'enemyTraderUnitsKilled'}
    buildingsStats = {'totalBuildingsConstructed', 'totalBuildingsLost', 'enemytotalBuildingsDestroyed',
            'civCentreBuildingsConstructed', 'civCentreBuildingsLost', 'enemyCivCentreBuildingsDestroyed',
            'houseBuildingsConstructed', 'houseBuildingsLost', 'enemyHouseBuildingsDestroyed',
            'economicBuildingsConstructed', 'economicBuildingsLost', 'enemyEconomicBuildingsDestroyed',
            'outpostBuildingsConstructed', 'outpostBuildingsLost', 'enemyOutpostBuildingsDestroyed',
            'militaryBuildingsConstructed', 'militaryBuildingsLost', 'enemyMilitaryBuildingsDestroyed',
            'fortressBuildingsConstructed', 'fortressBuildingsLost', 'enemyFortressBuildingsDestroyed',
            'wonderBuildingsConstructed', 'wonderBuildingsLost', 'enemyWonderBuildingsDestroyed'}
    marketStats = {'woodBought', 'foodBought', 'stoneBought', 'metalBought', 'tradeIncome'}
    miscStats = {'civs', 'teams', 'percentMapExplored'}

    stats = totalScoreStats | resourceStats | unitsStats | buildingsStats | marketStats | miscStats
    playerInfos = []
    for player in players:
      jid = player.jid
      playerinfo = PlayerInfo(player=player)
      for reportname in stats:
        setattr(playerinfo, reportname, get(reportname, jid.lower()))
      playerInfos.append(playerinfo)

    game = Game(map=gamereport['mapName'], duration=int(gamereport['timeElapsed']), teamsLocked=bool(gamereport['teamsLocked']), matchID=gamereport['matchID'])
    game.players.extend(players)
    game.player_info.extend(playerInfos)
    game.winner = db.query(Player).filter(Player.jid.ilike(str(winning_jid))).first()
    db.add(game)
    db.commit()
    return game
Exemple #8
0
  def addGame(self, gamereport):
    """
      Adds a game to the database and updates the data
      on a player(JID) from game results.
      Returns the created Game object, or None if
      the creation failed for any reason.
      Side effects:
        Inserts a new Game instance into the database.
    """
    # Discard any games still in progress.
    if any(map(lambda state: state == 'active',
               dict.values(gamereport['playerStates']))):
      return None

    players = map(lambda jid: db.query(Player).filter(Player.jid.ilike(str(jid))).first(),
                  dict.keys(gamereport['playerStates']))

    winning_jid = list(dict.keys({jid: state for jid, state in
                                  gamereport['playerStates'].items()
                                  if state == 'won'}))[0]
    def get(stat, jid):
      return gamereport[stat][jid]

    singleStats = {'timeElapsed', 'mapName', 'teamsLocked', 'matchID'}
    totalScoreStats = {'economyScore', 'militaryScore', 'totalScore'}
    resourceStats = {'foodGathered', 'foodUsed', 'woodGathered', 'woodUsed', 
            'stoneGathered', 'stoneUsed', 'metalGathered', 'metalUsed', 'vegetarianFoodGathered',
            'treasuresCollected', 'lootCollected', 'tributesSent', 'tributesReceived'}
    unitsStats = {'totalUnitsTrained', 'totalUnitsLost', 'enemytotalUnitsKilled', 'infantryUnitsTrained',
            'infantryUnitsLost', 'enemyInfantryUnitsKilled', 'workerUnitsTrained', 'workerUnitsLost',
            'enemyWorkerUnitsKilled', 'femaleUnitsTrained', 'femaleUnitsLost', 'enemyFemaleUnitsKilled',
            'cavalryUnitsTrained', 'cavalryUnitsLost', 'enemyCavalryUnitsKilled', 'championUnitsTrained',
            'championUnitsLost', 'enemyChampionUnitsKilled', 'heroUnitsTrained', 'heroUnitsLost',
            'enemyHeroUnitsKilled', 'shipUnitsTrained', 'shipUnitsLost', 'enemyShipUnitsKilled', 'traderUnitsTrained',
            'traderUnitsLost', 'enemyTraderUnitsKilled'}
    buildingsStats = {'totalBuildingsConstructed', 'totalBuildingsLost', 'enemytotalBuildingsDestroyed',
            'civCentreBuildingsConstructed', 'civCentreBuildingsLost', 'enemyCivCentreBuildingsDestroyed',
            'houseBuildingsConstructed', 'houseBuildingsLost', 'enemyHouseBuildingsDestroyed',
            'economicBuildingsConstructed', 'economicBuildingsLost', 'enemyEconomicBuildingsDestroyed',
            'outpostBuildingsConstructed', 'outpostBuildingsLost', 'enemyOutpostBuildingsDestroyed',
            'militaryBuildingsConstructed', 'militaryBuildingsLost', 'enemyMilitaryBuildingsDestroyed',
            'fortressBuildingsConstructed', 'fortressBuildingsLost', 'enemyFortressBuildingsDestroyed',
            'wonderBuildingsConstructed', 'wonderBuildingsLost', 'enemyWonderBuildingsDestroyed'}
    marketStats = {'woodBought', 'foodBought', 'stoneBought', 'metalBought', 'tradeIncome'}
    miscStats = {'civs', 'teams', 'percentMapExplored'}

    stats = totalScoreStats | resourceStats | unitsStats | buildingsStats | marketStats | miscStats
    playerInfos = []
    for player in players:
      jid = player.jid
      playerinfo = PlayerInfo(player=player)
      for reportname in stats:
        setattr(playerinfo, reportname, get(reportname, jid.lower()))
      playerInfos.append(playerinfo)

    game = Game(map=gamereport['mapName'], duration=int(gamereport['timeElapsed']), teamsLocked=bool(gamereport['teamsLocked']), matchID=gamereport['matchID'])
    game.players.extend(players)
    game.player_info.extend(playerInfos)
    game.winner = db.query(Player).filter(Player.jid.ilike(str(winning_jid))).first()
    db.add(game)
    db.commit()
    return game