예제 #1
0
 def getMatchQuality(self):
     try :
         gameInfo = GameInfo()
         calculator = FactorGraphTrueSkillCalculator()
         return calculator.calculateMatchQuality(gameInfo, self.finalTeams)
     except :
         return None
예제 #2
0
 def getMatchQuality(self, player1, player2):
     
     matchup = [player1, player2]
     
     gameInfo = GameInfo()
     calculator = FactorGraphTrueSkillCalculator()
     return calculator.calculateMatchQuality(gameInfo, matchup)
예제 #3
0
    def computeResults(self, update=True):
        self.log.debug("Computing results")
        if update :
            self.updateTrueskill()
        
        results = []
        for teams in self.finalTeams :
            curScore = 0
            for players in teams.getAllPlayers() :
                id = str(players.getId())

                if id in str(self.gameResult) :

                    resultPlayer = self.gameResult[str(id)]

                    curScore =  curScore + resultPlayer
                else :
                    return 0

            results.append(curScore)
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()
        try :
            newRatings = calculator.calculateNewRatings(gameInfo, self.finalTeams, results)
            return newRatings
        except :
            return 0
예제 #4
0
    def computeResults(self, update=True):
        self.log.debug("Computing results")
        if update:
            self.updateTrueskill()

        results = []
        for teams in self.finalTeams:
            curScore = 0
            for players in teams.getAllPlayers():
                id = str(players.getId())

                if id in str(self.gameResult):

                    resultPlayer = self.gameResult[str(id)]

                    curScore = curScore + resultPlayer
                else:
                    return 0

            results.append(curScore)
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()
        try:
            newRatings = calculator.calculateNewRatings(
                gameInfo, self.finalTeams, results)
            return newRatings
        except:
            return 0
예제 #5
0
    def getMatchQuality(self, player1, player2):

        matchup = [player1, player2]

        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()
        return calculator.calculateMatchQuality(gameInfo, matchup)
예제 #6
0
 def getMatchQuality(self):
     try:
         gameInfo = GameInfo()
         calculator = FactorGraphTrueSkillCalculator()
         return calculator.calculateMatchQuality(gameInfo, self.finalTeams)
     except:
         return None
예제 #7
0
 def computeResults1v1(self):
     self.updateTrueskillFor1v1()
     self.computeScoreFor1v1()
     gameInfo = GameInfo()
     calculator = FactorGraphTrueSkillCalculator()
     
     try :
         newRatings = calculator.calculateNewRatings(gameInfo, self.finalTeams1v1, self.results)
         return newRatings
     except :
         return 0
예제 #8
0
    def computeResults1v1(self):
        self.updateTrueskillFor1v1()
        self.computeScoreFor1v1()
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()

        try:
            newRatings = calculator.calculateNewRatings(
                gameInfo, self.finalTeams1v1, self.results)
            return newRatings
        except:
            return 0
예제 #9
0
    def update(self, message, client):
        '''
        Updates this item from the message dictionary supplied
        '''

        foo = message
        message = copy.deepcopy(foo)
        
        self.client  = client

        self.title      = message['title']
        self.host       = message['host']
        self.teams      = dict.copy(message['teams'])
        self.access     = message.get('access', 'public')
        self.mod        = message['featured_mod']
        self.modVersion = message.get('featured_mod_versions', [])
        self.mods       = message.get('sim_mods',{})
        self.options    = message.get('options', [])
        self.numplayers = message.get('num_players', 0) 
        self.slots      = message.get('max_players',12)
        
        oldstate = self.state
        self.state  = message['state']
      

        # Assemble a players & teams lists
        self.teamlist = []
        self.observerlist = []
        self.realPlayers = []
        self.teamsTrueskill = []
        self.gamequality = 0
        self.invalidTS = False
        self.nTeams = 0

        #HACK: Visibility field not supported yet.
        self.private = self.title.lower().find("private") != -1        
        self.setHidden((self.state != 'open') or (self.mod in mod_invisible))        


        # Clear the status for all involved players (url may change, or players may have left, or game closed)        
        for player in self.players:
            if player in client.urls:
                del client.urls[player]


        # Just jump out if we've left the game, but tell the client that all players need their states updated
        if self.state == "closed":
            client.usersUpdated.emit(self.players)
            return
            
        self.players = []
        for team in self.teams:
            self.players.extend(self.teams[team])


        # Map preview code
        if self.mapname != message['mapname']:
            self.mapname = message['mapname']
            self.mapdisplayname = maps.getDisplayName(self.mapname)
            refresh_icon = True
        else:
            refresh_icon = False
                    
        #Resolve pretty display name
        self.moddisplayname = self.mod
        self.modoptions = []
        
        if self.mod in mods :
            self.moddisplayname = mods[self.mod].name 
            self.modoptions = mods[self.mod].options
        

        #Checking if the mod has options

        #Alternate icon: If private game, use game_locked icon. Otherwise, use preview icon from map library.
        if refresh_icon:
            if self.access == "password" or self.private:
                icon = util.icon("games/private_game.png")
            else:            
                icon = maps.preview(self.mapname)
                if not icon:
                    self.client.downloader.downloadMap(self.mapname, self)
                    icon = util.icon("games/unknown_map.png")
                             
            self.setIcon(icon)
        

        # Used to differentiate between newly added / removed and previously present players            
        oldplayers = set(self.players)
        
       
        self.playerIncluded = False
        
        
        if self.state == "open" :
            if "1" in self.teams and "2" in self.teams and self.client.login != None and self.client.login not in self.teams["1"] and self.client.login not in self.teams["2"] :
                if len(self.teams["1"]) < len(self.teams["2"]) :
                    self.teams["1"].append(self.client.login)
                    self.playerIncluded = True

                elif len(self.teams["1"]) > len(self.teams["2"]) :
                    self.teams["2"].append(self.client.login)
                    self.playerIncluded = True

        if self.state == "open" and  "1" in self.teams and "2" in self.teams :
            for team in self.teams:
                if team != "-1" :
                    self.realPlayers.extend(self.teams[team])
                    if team == 0 :
                        for player in self.teams[team] :
                            curTeam = Team()
                            if player in self.client.players :
                                mean = self.client.players[player]["rating_mean"]
                                dev = self.client.players[player]["rating_deviation"]
                                curTeam.addPlayer(player, Rating(mean, dev))
                            else :
                                self.invalidTS = True
                            self.teamsTrueskill.append(curTeam)
                    else :
                        curTeam = Team()

                        if team == "1" and (len(self.teams["1"]) < len(self.teams["2"])) and self.playerIncluded == True :
                            if self.client.login in self.client.players :
                                curTeam.addPlayer(self.client.login, Rating(self.client.players[self.client.login]["rating_mean"], self.client.players[self.client.login]["rating_deviation"]))
                        
                        if team == "2" and (len(self.teams["1"]) > len(self.teams["2"])) and self.playerIncluded == True :
                            if self.client.login in self.client.players :
                                curTeam.addPlayer(self.client.login, Rating(self.client.players[self.client.login]["rating_mean"], self.client.players[self.client.login]["rating_deviation"]))


                        for player in self.teams[team] :          
                            if player in self.client.players :
                                if self.client.isFoe(player) :
                                    self.hasFoe = True
                                mean = self.client.players[player]["rating_mean"]
                                dev = self.client.players[player]["rating_deviation"]
                                curTeam.addPlayer(player, Rating(mean, dev))
                            else :
                                self.invalidTS = True
                                

                        self.teamsTrueskill.append(curTeam)
                    
                # computing game quality :
                if len(self.teamsTrueskill) > 1 and self.invalidTS == False :
                    self.nTeams = 0
                    for t in self.teams :
                        if int(t) != -1 :
                            self.nTeams += 1

                    realPlayers = len(self.realPlayers)

                    if realPlayers % self.nTeams == 0 :

                        gameInfo = GameInfo()
                        calculator = FactorGraphTrueSkillCalculator()
                        gamequality = calculator.calculateMatchQuality(gameInfo, self.teamsTrueskill)
                        if gamequality < 1 :
                            self.gamequality = round((gamequality * 100), 2)

        strQuality = ""
        
        if self.gamequality == 0 :
            strQuality = "? %"
        else :
            strQuality = str(self.gamequality)+" %"


        if len(self.players) == 1:
            playerstring = "player"
        else:
            playerstring = "players"
        
        
        self.numplayers = len(self.players)
        
        self.playerIncludedTxt = ""
        if self.playerIncluded :
            self.playerIncludedTxt = "(with you)"
            
        color = client.getUserColor(self.host)
        
        for player in self.players :
            if self.client.isFoe(player) :
                color = client.getUserColor(player)

        self.editTooltip()
        
        

        if self.mod == "faf" or self.mod == "balancetesting" and not self.mods:
            self.setText(self.FORMATTER_FAF.format(color=color, mapslots = self.slots, mapdisplayname=self.mapdisplayname, title=self.title, host=self.host, players=self.numplayers, playerstring=playerstring, gamequality = strQuality, playerincluded = self.playerIncludedTxt))
        else:
            if not self.mods:
                modstr = self.mod
            else:
                if self.mod == 'faf': modstr = ", ".join(self.mods.values())
                else: modstr = self.mod + " & " + ", ".join(self.mods.values())
                if len(modstr) > 20: modstr = modstr[:15] + "..."
            self.setText(self.FORMATTER_MOD.format(color=color, mapslots = self.slots, mapdisplayname=self.mapdisplayname, title=self.title, host=self.host, players=self.numplayers, playerstring=playerstring, gamequality = strQuality, playerincluded = self.playerIncludedTxt, mod=modstr))
        
        if self.uid == 0:
            return
                
        #Spawn announcers: IF we had a gamestate change, show replay and hosting announcements 
        if (oldstate != self.state):            
            if (self.state == "playing"):
                QtCore.QTimer.singleShot(5*60000, self.announceReplay) #The delay is there because we have a 5 minutes delay in the livereplay server
            elif (self.state == "open"):
                QtCore.QTimer.singleShot(35000, self.announceHosting)   #The delay is there because we currently the host needs time to choose a map

        # Update player URLs
        for player in self.players:
            client.urls[player] = self.url(player)

        # Determine which players are affected by this game's state change            
        newplayers = set(self.players)            
        affectedplayers = oldplayers | newplayers
        client.usersUpdated.emit(list(affectedplayers))
예제 #10
0
    def on_draw(self):
        """ Redraws the figure
        """
        str = unicode(self.textbox.text())
        
        x = self.mu + self.sigma*np(50000)

        self.axes.clear()        
        
        self.axes.grid(self.grid_cb.isChecked())
        
                
        self.axes.set_xlabel("Skill")
        self.axes.set_ylabel("Probability %")
        #self.ylabel('')
        self.axes.set_title("performance graph of %s"% self.name)


#
        ## the histogram of the data
        n, bins, patches = self.axes.hist(x, 100, normed=1, facecolor='green', alpha=0.55) 
        
        

        
        y = normpdf( bins, self.mu, self.sigma) * 100 

        text ="This is the potential rating of %s.\n66 percent chances to be between %i and %i." % (self.name,int(self.mu-self.sigma), int(self.mu+self.sigma))

        self.textbox.setText(text + "\n%.2f percent chances to be %i" % (round((max(y)*100),2), int(self.mu)))
        self.textbox.setText(self.textbox.text() + "\nThe worst rating possible is the one in the leaderboard : %i" % int(self.mu-3*self.sigma))
        
        self.axes.axis([self.mu-4*self.sigma, self.mu+4*self.sigma, 0, (100 + (max(y)*100)*1.5) / 2])
        #self.axes.hist(x, bins, normed=1, facecolor='green',)
        self.axes.plot(bins, y*100, linewidth=.5, linestyle = 'None', color = 'red', alpha = 1.0) 
        self.axes.fill(bins, y*100, 'r--', linewidth=0,  alpha=.5,  facecolor='red') 
        
        self.axes.annotate(('%s maximum rating (%i)' % (self.name, self.mu)), xy=(self.mu, max(y)*100),  xycoords='data',  xytext=(-50, 30), textcoords='offset points', arrowprops=dict(arrowstyle="wedge", facecolor='red', linewidth=0),  size = 7, alpha = 0.5, backgroundcolor='lightgrey')
        
        if not self.compare_cb.isChecked() :
            self.axes.fill_between(bins, y*100 ,0, where=bins>self.mu+self.sigma, facecolor='darkred',  interpolate=True)
            self.axes.fill_between(bins, y*100 ,0, where=bins<self.mu-self.sigma, facecolor='darkred', interpolate=True )
        

        if self.compare_cb.isChecked() :
            
            self.axes.set_title("performance graph of %s VS you " % self.name )

            x = self.playermu + self.playersigma*np(50000)
            n, bins, patches = self.axes.hist(x, 100, normed=1, facecolor='green', alpha=0.55)
            y2 = normpdf( bins, self.playermu, self.playersigma) * 100
            self.axes.axis([min(self.mu-4*self.sigma, self.playermu-4*self.playersigma) , max(self.mu+4*self.sigma, self.playermu+4*self.playersigma), 0, max((100 + (max(y)*100)*1.5) / 2,(100 + (max(y2)*100)*1.5) / 2)])
            self.axes.plot(bins, y2*100, linewidth=.5, linestyle = 'None', color = 'blue', alpha = 1.0) 
            self.axes.fill(bins, y2*100, 'r--', linewidth=0,  alpha=.5,  facecolor='blue')
            #self.axes.fill_between(bins, y2*100 ,0, where=bins>self.playermu+self.playersigma, facecolor='darkblue',  interpolate=True)
            #self.axes.fill_between(bins, y2*100 ,0, where=bins<self.playermu-self.playersigma, facecolor='darkblue', interpolate=True )            

            self.axes.annotate('Your most probable rating (%i)' % int(self.playermu), xy=(self.playermu, max(y2)*100),  xycoords='data',  xytext=(-50, 30), textcoords='offset points', arrowprops=dict(arrowstyle="wedge", facecolor='blue', linewidth=0),  size = 7, alpha = 0.5, backgroundcolor='lightgrey')
            
            text ="This is the potential rating of %s.\n66 percent chances to be between %i and %i. (you : between %i and %i)" % (self.name,int(self.mu-self.sigma), int(self.mu+self.sigma), int(self.playermu-self.playersigma), int(self.playermu+self.playersigma))
            self.textbox.setText(text + "\n%.2f percent chances to be %i (You : \n%.2f percent chances to be %i)" % (round((max(y)*100),2), int(self.mu), round((max(y2)*100),2), int(self.playermu)))
            self.textbox.setText(self.textbox.text() + "\nThe worst rating possible is the one in the leaderboard : %i (you : %i)" % (int(self.mu-3*self.sigma), int(self.playermu-3*self.playersigma)))
            
            teamsTrueskill = []
            Team1 = Team()
            Team1.addPlayer("1", Rating(self.mu, self.sigma))
            Team2 = Team()
            Team2.addPlayer("2", Rating(self.playermu, self.playersigma))
            teamsTrueskill.append(Team1)
            teamsTrueskill.append(Team2)
            gameInfo = GameInfo()
            calculator = FactorGraphTrueSkillCalculator()
            gamequality = calculator.calculateMatchQuality(gameInfo, teamsTrueskill) * 100
            self.textbox.setText(self.textbox.text() + "\nProbabilites of having a even match : %.2f percent" % gamequality )
            
            
        self.canvas.draw()
예제 #11
0
    def getBestMatchup(self):

        #getting number of current teams
        nTeams = self.getTeamsCount()
        if nTeams == 0:

            return "No teams formed yet"
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()

        if len(self.trueSkillPlayers) % nTeams:
            return "Missing players for this number of teams (%i)" % (
                int(nTeams))

        platoon = len(self.trueSkillPlayers) / nTeams

        matchs = []
        for perm in list(self.permutations(self.trueSkillPlayers)):
            match = []
            for j in range(nTeams):
                team = []
                for i in range(platoon):
                    index = i + platoon * j
                    team.append(perm[index])
                team = sorted(team)
                match.append(team)
            matchs.append(match)

        a = []

        matchQuality = 0
        winningTeam = None

        for item in matchs:
            if not item[0] in a:
                a.append(item[0])

                Teams = []
                for i in range(nTeams):
                    resultTeam = Team()
                    for j in range(len(item[i])):

                        for player in item[i][j].getAllPlayers():
                            resultTeam.addPlayer(player,
                                                 item[i][j].getRating())

                    Teams.append(resultTeam)

                curQual = calculator.calculateMatchQuality(gameInfo, Teams)
                if curQual > matchQuality:
                    matchQuality = curQual
                    winningTeam = Teams

        msg = "The best composition for teams is \n"

        for teams in winningTeam:
            msg = msg + 'team %i' % i + '\n'

            for player in teams.getAllPlayers():

                msg = msg + "player " + str(player.getId()) + "(" + str(
                    teams.getRating(player)) + ")\n"
            i = i + 1

        msg = msg + "Game Quality : " + str(matchQuality * 100) + '%'
        return msg
예제 #12
0
    def getBestMatchup(self):
        

        
        if not self.state == "open":
            return "game in play"
        
        nTeams = 0
        for t in  self.teamlist :
            if t != -1 :
                nTeams += 1
        
        
        if nTeams != 2 or len(self.players) <= 2 :
            return "No teams formed yet"
        
       
        if len(self.players) % nTeams :
            return "Missing players for this number of teams (%i)" % (int(nTeams))
        if (len(self.players) / nTeams) == 1 :
            
            return "Only one player per team" 
            
        playerlist =  {}  
        for player in self.players :
            mean = self.client.players[player]["rating_mean"]
            dev = self.client.players[player]["rating_deviation"]
            rating = mean - 3 * dev
            playerlist[player] = rating
        
        i = 0
        
        bestTeams = {}
        bestTeams[1] = []
        bestTeams[2] = []
        
        for key, value in sorted(playerlist.iteritems(), key=lambda (k,v): (v,k), reverse=True):
            bestTeams[self.assignToTeam(i)].append(key)
            i = i + 1

        msg = ""
#        i = 0
#        for teams in winningTeam :
#            
        msg += ", ".join(bestTeams[1])
#            i = i + 1
#            if i != len(winningTeam) :
        msg += "<br/>Vs<br/>"
        msg += ", ".join(bestTeams[2])
        
        teamsTrueskill = []
        invalidTS = False
        
        for player in bestTeams[1] :
            curTeam = Team()
            if player in self.client.players :
                mean = self.client.players[player]["rating_mean"]
                dev = self.client.players[player]["rating_deviation"]
                curTeam.addPlayer(player, Rating(mean, dev))
            else :
                self.invalidTS = True
            teamsTrueskill.append(curTeam)

        for player in bestTeams[2] :
            curTeam = Team()
            if player in self.client.players :
                mean = self.client.players[player]["rating_mean"]
                dev = self.client.players[player]["rating_deviation"]
                curTeam.addPlayer(player, Rating(mean, dev))
            else :
                self.invalidTS = True
            teamsTrueskill.append(curTeam)
    
        # computing game quality :
        if  invalidTS == False :

            gameInfo = GameInfo()
            calculator = FactorGraphTrueSkillCalculator()
            gamequality = calculator.calculateMatchQuality(gameInfo, teamsTrueskill)
            if gamequality < 1 :
                gamequality = round((gamequality * 100), 2)

        
        
                msg = msg + "<br/>Game Quality will be : " + str(gamequality) + '%' 
        return msg
예제 #13
0
    def getBestMatchup(self):
        
        #getting number of current teams
        nTeams = self.getTeamsCount()
        if nTeams == 0 :
            
            return "No teams formed yet"
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()
        
        if len(self.trueSkillPlayers) % nTeams :
            return "Missing players for this number of teams (%i)" % (int(nTeams))

        platoon = len(self.trueSkillPlayers) / nTeams
            
        matchs = []   
        for perm in list(self.permutations(self.trueSkillPlayers)) :
             match = []
             for j in range(nTeams) :
                team = []
                for i in range(platoon) :
                    index = i+platoon*j
                    team.append(perm[index])
                team=sorted(team)
                match.append(team)
             matchs.append(match)
             
        a = []

        matchQuality = 0
        winningTeam = None
        
        for item in matchs:
            if not item[0] in a:
                a.append(item[0])


                Teams = []
                for i in range(nTeams) :
                    resultTeam = Team()
                    for j in range(len(item[i])) :
        
                        for player in item[i][j].getAllPlayers() : 
                                resultTeam.addPlayer(player, item[i][j].getRating())
        
                    Teams.append(resultTeam)
                    

                curQual = calculator.calculateMatchQuality(gameInfo, Teams)
                if curQual > matchQuality :
                    matchQuality = curQual
                    winningTeam = Teams

        msg = "The best composition for teams is \n"

        for teams in winningTeam :
            msg = msg + 'team %i' %i + '\n'
        
            for player in teams.getAllPlayers() :
                
                msg = msg + "player "  + str(player.getId()) + "(" + str(teams.getRating(player)) + ")\n"
            i = i + 1
        
        
        msg = msg + "Game Quality : " + str(matchQuality * 100) + '%' 
        return msg
예제 #14
0
    def getMatchQuality(self, team1, team2):

        matchup = [team1.getTrueskillTeam(), team2.getTrueskillTeam()]
        gameInfo = GameInfo()
        calculator = FactorGraphTrueSkillCalculator()
        return calculator.calculateMatchQuality(gameInfo, matchup)
예제 #15
0
    def getBestMatchup(self):

        if not self.state == "open":
            return "game in play"

        nTeams = 0
        for t in self.teamlist:
            if t != -1:
                nTeams += 1

        if nTeams != 2 or len(self.players) <= 2:
            return "No teams formed yet"

        if len(self.players) % nTeams:
            return "Missing players for this number of teams (%i)" % (
                int(nTeams))
        if (len(self.players) / nTeams) == 1:

            return "Only one player per team"

        playerlist = {}
        for player in self.players:
            mean = self.client.players[player]["rating_mean"]
            dev = self.client.players[player]["rating_deviation"]
            rating = mean - 3 * dev
            playerlist[player] = rating

        i = 0

        bestTeams = {}
        bestTeams[1] = []
        bestTeams[2] = []

        for key, value in sorted(playerlist.iteritems(),
                                 key=lambda (k, v): (v, k),
                                 reverse=True):
            bestTeams[self.assignToTeam(i)].append(key)
            i = i + 1

        msg = ""
        #        i = 0
        #        for teams in winningTeam :
        #
        msg += ", ".join(bestTeams[1])
        #            i = i + 1
        #            if i != len(winningTeam) :
        msg += "<br/>Vs<br/>"
        msg += ", ".join(bestTeams[2])

        teamsTrueskill = []
        invalidTS = False

        for player in bestTeams[1]:
            curTeam = Team()
            if player in self.client.players:
                mean = self.client.players[player]["rating_mean"]
                dev = self.client.players[player]["rating_deviation"]
                curTeam.addPlayer(player, Rating(mean, dev))
            else:
                self.invalidTS = True
            teamsTrueskill.append(curTeam)

        for player in bestTeams[2]:
            curTeam = Team()
            if player in self.client.players:
                mean = self.client.players[player]["rating_mean"]
                dev = self.client.players[player]["rating_deviation"]
                curTeam.addPlayer(player, Rating(mean, dev))
            else:
                self.invalidTS = True
            teamsTrueskill.append(curTeam)

        # computing game quality :
        if invalidTS == False:

            gameInfo = GameInfo()
            calculator = FactorGraphTrueSkillCalculator()
            gamequality = calculator.calculateMatchQuality(
                gameInfo, teamsTrueskill)
            if gamequality < 1:
                gamequality = round((gamequality * 100), 2)

                msg = msg + "<br/>Game Quality will be : " + str(
                    gamequality) + '%'
        return msg
예제 #16
0
    def update(self, message, client):
        '''
        Updates this item from the message dictionary supplied
        '''

        foo = message
        message = copy.deepcopy(foo)

        self.client = client

        self.title = message['title']
        self.host = message['host']
        self.teams = dict.copy(message['teams'])
        self.access = message.get('access', 'public')
        self.mod = message['featured_mod']
        self.modVersion = message.get('featured_mod_versions', [])
        self.mods = message.get('sim_mods', {})
        self.options = message.get('options', [])
        self.numplayers = message.get('num_players', 0)
        self.slots = message.get('max_players', 12)

        oldstate = self.state
        self.state = message['state']

        # Assemble a players & teams lists
        self.teamlist = []
        self.observerlist = []
        self.realPlayers = []
        self.teamsTrueskill = []
        self.gamequality = 0
        self.invalidTS = False
        self.nTeams = 0

        #HACK: Visibility field not supported yet.
        self.private = self.title.lower().find("private") != -1
        self.setHidden((self.state != 'open') or (self.mod in mod_invisible))

        # Clear the status for all involved players (url may change, or players may have left, or game closed)
        for player in self.players:
            if player in client.urls:
                del client.urls[player]

        # Just jump out if we've left the game, but tell the client that all players need their states updated
        if self.state == "closed":
            client.usersUpdated.emit(self.players)
            return

        self.players = []
        for team in self.teams:
            self.players.extend(self.teams[team])

        # Map preview code
        if self.mapname != message['mapname']:
            self.mapname = message['mapname']
            self.mapdisplayname = maps.getDisplayName(self.mapname)
            refresh_icon = True
        else:
            refresh_icon = False

        #Resolve pretty display name
        self.moddisplayname = self.mod
        self.modoptions = []

        if self.mod in mods:
            self.moddisplayname = mods[self.mod].name
            self.modoptions = mods[self.mod].options

        #Checking if the mod has options

        #Alternate icon: If private game, use game_locked icon. Otherwise, use preview icon from map library.
        if refresh_icon:
            if self.access == "password" or self.private:
                icon = util.icon("games/private_game.png")
            else:
                icon = maps.preview(self.mapname)
                if not icon:
                    self.client.downloader.downloadMap(self.mapname, self)
                    icon = util.icon("games/unknown_map.png")

            self.setIcon(icon)

        # Used to differentiate between newly added / removed and previously present players
        oldplayers = set(self.players)

        self.playerIncluded = False

        if self.state == "open":
            if "1" in self.teams and "2" in self.teams and self.client.login != None and self.client.login not in self.teams[
                    "1"] and self.client.login not in self.teams["2"]:
                if len(self.teams["1"]) < len(self.teams["2"]):
                    self.teams["1"].append(self.client.login)
                    self.playerIncluded = True

                elif len(self.teams["1"]) > len(self.teams["2"]):
                    self.teams["2"].append(self.client.login)
                    self.playerIncluded = True

        if self.state == "open" and "1" in self.teams and "2" in self.teams:
            for team in self.teams:
                if team != "-1":
                    self.realPlayers.extend(self.teams[team])
                    if team == 0:
                        for player in self.teams[team]:
                            curTeam = Team()
                            if player in self.client.players:
                                mean = self.client.players[player][
                                    "rating_mean"]
                                dev = self.client.players[player][
                                    "rating_deviation"]
                                curTeam.addPlayer(player, Rating(mean, dev))
                            else:
                                self.invalidTS = True
                            self.teamsTrueskill.append(curTeam)
                    else:
                        curTeam = Team()

                        if team == "1" and (len(self.teams["1"]) < len(
                                self.teams["2"])
                                            ) and self.playerIncluded == True:
                            if self.client.login in self.client.players:
                                curTeam.addPlayer(
                                    self.client.login,
                                    Rating(
                                        self.client.players[
                                            self.client.login]["rating_mean"],
                                        self.client.players[self.client.login]
                                        ["rating_deviation"]))

                        if team == "2" and (len(self.teams["1"]) > len(
                                self.teams["2"])
                                            ) and self.playerIncluded == True:
                            if self.client.login in self.client.players:
                                curTeam.addPlayer(
                                    self.client.login,
                                    Rating(
                                        self.client.players[
                                            self.client.login]["rating_mean"],
                                        self.client.players[self.client.login]
                                        ["rating_deviation"]))

                        for player in self.teams[team]:
                            if player in self.client.players:
                                if self.client.isFoe(player):
                                    self.hasFoe = True
                                mean = self.client.players[player][
                                    "rating_mean"]
                                dev = self.client.players[player][
                                    "rating_deviation"]
                                curTeam.addPlayer(player, Rating(mean, dev))
                            else:
                                self.invalidTS = True

                        self.teamsTrueskill.append(curTeam)

                # computing game quality :
                if len(self.teamsTrueskill) > 1 and self.invalidTS == False:
                    self.nTeams = 0
                    for t in self.teams:
                        if int(t) != -1:
                            self.nTeams += 1

                    realPlayers = len(self.realPlayers)

                    if realPlayers % self.nTeams == 0:

                        gameInfo = GameInfo()
                        calculator = FactorGraphTrueSkillCalculator()
                        gamequality = calculator.calculateMatchQuality(
                            gameInfo, self.teamsTrueskill)
                        if gamequality < 1:
                            self.gamequality = round((gamequality * 100), 2)

        strQuality = ""

        if self.gamequality == 0:
            strQuality = "? %"
        else:
            strQuality = str(self.gamequality) + " %"

        if len(self.players) == 1:
            playerstring = "player"
        else:
            playerstring = "players"

        self.numplayers = len(self.players)

        self.playerIncludedTxt = ""
        if self.playerIncluded:
            self.playerIncludedTxt = "(with you)"

        color = client.getUserColor(self.host)

        for player in self.players:
            if self.client.isFoe(player):
                color = client.getUserColor(player)

        self.editTooltip()

        if self.mod == "faf" or self.mod == "balancetesting" and not self.mods:
            self.setText(
                self.FORMATTER_FAF.format(
                    color=color,
                    mapslots=self.slots,
                    mapdisplayname=self.mapdisplayname,
                    title=self.title,
                    host=self.host,
                    players=self.numplayers,
                    playerstring=playerstring,
                    gamequality=strQuality,
                    playerincluded=self.playerIncludedTxt))
        else:
            if not self.mods:
                modstr = self.mod
            else:
                if self.mod == 'faf': modstr = ", ".join(self.mods.values())
                else: modstr = self.mod + " & " + ", ".join(self.mods.values())
                if len(modstr) > 20: modstr = modstr[:15] + "..."
            self.setText(
                self.FORMATTER_MOD.format(
                    color=color,
                    mapslots=self.slots,
                    mapdisplayname=self.mapdisplayname,
                    title=self.title,
                    host=self.host,
                    players=self.numplayers,
                    playerstring=playerstring,
                    gamequality=strQuality,
                    playerincluded=self.playerIncludedTxt,
                    mod=modstr))

        if self.uid == 0:
            return

        #Spawn announcers: IF we had a gamestate change, show replay and hosting announcements
        if (oldstate != self.state):
            if (self.state == "playing"):
                QtCore.QTimer.singleShot(
                    5 * 60000, self.announceReplay
                )  #The delay is there because we have a 5 minutes delay in the livereplay server
            elif (self.state == "open"):
                QtCore.QTimer.singleShot(
                    35000, self.announceHosting
                )  #The delay is there because we currently the host needs time to choose a map

        # Update player URLs
        for player in self.players:
            client.urls[player] = self.url(player)

        # Determine which players are affected by this game's state change
        newplayers = set(self.players)
        affectedplayers = oldplayers | newplayers
        client.usersUpdated.emit(list(affectedplayers))
예제 #17
0
    def on_draw(self):
        """ Redraws the figure
        """
        str = unicode(self.textbox.text())

        x = self.mu + self.sigma * np(50000)

        self.axes.clear()

        self.axes.grid(self.grid_cb.isChecked())

        self.axes.set_xlabel("Skill")
        self.axes.set_ylabel("Probability %")
        #self.ylabel('')
        self.axes.set_title("performance graph of %s" % self.name)

        #
        ## the histogram of the data
        n, bins, patches = self.axes.hist(x,
                                          100,
                                          normed=1,
                                          facecolor='green',
                                          alpha=0.55)

        y = normpdf(bins, self.mu, self.sigma) * 100

        text = "This is the potential rating of %s.\n66 percent chances to be between %i and %i." % (
            self.name, int(self.mu - self.sigma), int(self.mu + self.sigma))

        self.textbox.setText(text + "\n%.2f percent chances to be %i" %
                             (round((max(y) * 100), 2), int(self.mu)))
        self.textbox.setText(
            self.textbox.text() +
            "\nThe worst rating possible is the one in the leaderboard : %i" %
            int(self.mu - 3 * self.sigma))

        self.axes.axis([
            self.mu - 4 * self.sigma, self.mu + 4 * self.sigma, 0,
            (100 + (max(y) * 100) * 1.5) / 2
        ])
        #self.axes.hist(x, bins, normed=1, facecolor='green',)
        self.axes.plot(bins,
                       y * 100,
                       linewidth=.5,
                       linestyle='None',
                       color='red',
                       alpha=1.0)
        self.axes.fill(bins,
                       y * 100,
                       'r--',
                       linewidth=0,
                       alpha=.5,
                       facecolor='red')

        self.axes.annotate(('%s maximum rating (%i)' % (self.name, self.mu)),
                           xy=(self.mu, max(y) * 100),
                           xycoords='data',
                           xytext=(-50, 30),
                           textcoords='offset points',
                           arrowprops=dict(arrowstyle="wedge",
                                           facecolor='red',
                                           linewidth=0),
                           size=7,
                           alpha=0.5,
                           backgroundcolor='lightgrey')

        if not self.compare_cb.isChecked():
            self.axes.fill_between(bins,
                                   y * 100,
                                   0,
                                   where=bins > self.mu + self.sigma,
                                   facecolor='darkred',
                                   interpolate=True)
            self.axes.fill_between(bins,
                                   y * 100,
                                   0,
                                   where=bins < self.mu - self.sigma,
                                   facecolor='darkred',
                                   interpolate=True)

        if self.compare_cb.isChecked():

            self.axes.set_title("performance graph of %s VS you " % self.name)

            x = self.playermu + self.playersigma * np(50000)
            n, bins, patches = self.axes.hist(x,
                                              100,
                                              normed=1,
                                              facecolor='green',
                                              alpha=0.55)
            y2 = normpdf(bins, self.playermu, self.playersigma) * 100
            self.axes.axis([
                min(self.mu - 4 * self.sigma,
                    self.playermu - 4 * self.playersigma),
                max(self.mu + 4 * self.sigma,
                    self.playermu + 4 * self.playersigma), 0,
                max((100 + (max(y) * 100) * 1.5) / 2,
                    (100 + (max(y2) * 100) * 1.5) / 2)
            ])
            self.axes.plot(bins,
                           y2 * 100,
                           linewidth=.5,
                           linestyle='None',
                           color='blue',
                           alpha=1.0)
            self.axes.fill(bins,
                           y2 * 100,
                           'r--',
                           linewidth=0,
                           alpha=.5,
                           facecolor='blue')
            #self.axes.fill_between(bins, y2*100 ,0, where=bins>self.playermu+self.playersigma, facecolor='darkblue',  interpolate=True)
            #self.axes.fill_between(bins, y2*100 ,0, where=bins<self.playermu-self.playersigma, facecolor='darkblue', interpolate=True )

            self.axes.annotate('Your most probable rating (%i)' %
                               int(self.playermu),
                               xy=(self.playermu, max(y2) * 100),
                               xycoords='data',
                               xytext=(-50, 30),
                               textcoords='offset points',
                               arrowprops=dict(arrowstyle="wedge",
                                               facecolor='blue',
                                               linewidth=0),
                               size=7,
                               alpha=0.5,
                               backgroundcolor='lightgrey')

            text = "This is the potential rating of %s.\n66 percent chances to be between %i and %i. (you : between %i and %i)" % (
                self.name,
                int(self.mu - self.sigma), int(self.mu + self.sigma),
                int(self.playermu - self.playersigma),
                int(self.playermu + self.playersigma))
            self.textbox.setText(
                text +
                "\n%.2f percent chances to be %i (You : \n%.2f percent chances to be %i)"
                % (round((max(y) * 100), 2), int(self.mu),
                   round((max(y2) * 100), 2), int(self.playermu)))
            self.textbox.setText(
                self.textbox.text() +
                "\nThe worst rating possible is the one in the leaderboard : %i (you : %i)"
                % (int(self.mu - 3 * self.sigma),
                   int(self.playermu - 3 * self.playersigma)))

            teamsTrueskill = []
            Team1 = Team()
            Team1.addPlayer("1", Rating(self.mu, self.sigma))
            Team2 = Team()
            Team2.addPlayer("2", Rating(self.playermu, self.playersigma))
            teamsTrueskill.append(Team1)
            teamsTrueskill.append(Team2)
            gameInfo = GameInfo()
            calculator = FactorGraphTrueSkillCalculator()
            gamequality = calculator.calculateMatchQuality(
                gameInfo, teamsTrueskill) * 100
            self.textbox.setText(
                self.textbox.text() +
                "\nProbabilites of having a even match : %.2f percent" %
                gamequality)

        self.canvas.draw()
 def getMatchQuality(self, team1, team2):
     
     matchup = [team1.getTrueskillTeam(), team2.getTrueskillTeam()]        
     gameInfo = GameInfo()
     calculator = FactorGraphTrueSkillCalculator()
     return calculator.calculateMatchQuality(gameInfo, matchup)