def getPlayerName(self, player): ''' Get the avatar name ''' try : if player.getLogin() in self.avatarNames: return self.avatarNames[player.getLogin()] self.log.debug("getting avatar name for %s (uid %i)" % (player.getLogin(), player.getId()) ) query = QSqlQuery(self.parent.db) uid = int(player.getId()) query.prepare("SELECT name, id FROM galacticwar.`avatars` WHERE `uid` = ? AND `alive` = 1") query.addBindValue(uid) query.exec_() if query.size() == 1 : query.first() name = str(query.value(0)) uid = int(query.value(1)) self.avatarNames[player.getLogin()] = name self.avatarIds[player.getLogin()] = uid self.log.debug("avatar name is %s (uid %i)" % (name, uid) ) return name else : self.avatarNames[player.getLogin()] = player.getLogin() self.avatarIds[player.getLogin()] = player.getId() return player.getLogin() except : self.log.exception("Something awful happened when getting a gw name !")
def load(layout): """"Loads the file and restores the saved state""" # Restore the first day of usage global_vars.DAYFIRST = datetime.date.fromordinal(int(open(paths.savePath).read().splitlines()[0])) filename = os.path.basename(paths.savePath)[:-8] database.setConnection(filename) layout.initTasks(database.getStatuses()) layout.tab.clearAll() # ### Loading main table # # weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] opened = False q = 'SELECT * FROM main' query = QSqlQuery(q) while query.next(): record = query.record() indexes = [] if not record.isEmpty(): for i in range(0, 44): if not record.isNull(i + 1): indexes.append(i) day = str(record.field('weekday').value()).split('_') weekday = day[0] weeknum = int(day[1]) values = {} for index in indexes: q = QSqlQuery("SELECT name FROM tasks WHERE rowid ='" + str(query.value(index + 1)) + "'") q.next() values[index] = q.value(0) if values: opened = True layout.tab.setValues(values, weekdays.index(weekday), weeknum) if not opened: layout.tab.openTab(1) # # ################ # Loading evaluation values # q = 'SELECT * from evaluation' query = QSqlQuery(q) while query.next(): record = query.record() if not record.isEmpty(): week = record.field('week').value() values = [] for day in global_vars.WEEKDAYS: values.append(record.field(day).value()) global_vars.EVAL_VALUES[week] = values database.dropConnection()
def getCurrentDomination(self): query = QSqlQuery(self.parent.db) query.prepare("SELECT dominant, slave FROM `domination` WHERE 1") query.exec_() if query.size() > 0: query.first() dominant = int(query.value(0)) slave = int(query.value(1)) if not slave in self.dominations: self.dominations[slave] = dominant
def getReplaysInfos(self): #general stats self.parent.db.open() self.replayInfo["game_end"] = time.time() query = QSqlQuery(self.parent.db) queryStr = ("SELECT game_featuredMods.gamemod, gameType, filename, gameName, host, login, playerId, AI, team FROM `game_stats` LEFT JOIN game_player_stats ON `game_player_stats`.`gameId` = game_stats.id LEFT JOIN table_map ON `game_stats`.`mapId` = table_map.id LEFT JOIN login ON login.id = `game_player_stats`.`playerId` LEFT JOIN game_featuredMods ON `game_stats`.`gameMod` = game_featuredMods.id WHERE game_stats.id = %i" % self.uid) query.exec_(queryStr) if query.size() != 0: self.replayInfo["num_players"] = query.size() query.first() self.replayInfo["featured_mod"] = str(query.value(0)) self.replayInfo["game_type"] = int(query.value(1) or 0) mapname = str(query.value(2)) self.replayInfo["title"] = str(query.value(3).encode('utf-8')) self.replayInfo["featured_mod_versions"] = {} # checking featured mod version tableMod = "updates_" + str(query.value(0)) tableModFiles = tableMod + "_files" query2 = QSqlQuery(self.parent.db) query2.prepare("SELECT fileId, MAX(version) FROM `%s` LEFT JOIN %s ON `fileId` = %s.id GROUP BY fileId" % (tableModFiles, tableMod, tableMod)) query2.exec_() if query2.size() != 0 : while query2.next() : self.replayInfo["featured_mod_versions"][int(query2.value(0))] = int(query2.value(1)) self.replayInfo["mapname"] = os.path.splitext(os.path.basename(mapname))[0] self.replayInfo["complete"] = True teams = {} while query.next() : team = int(query.value(8)) name = str(query.value(5)) isAi = int(query.value(7)) if int(query.value(4)) == int(query.value(6)) : self.replayInfo["host"] = name if isAi == 0 : if not team in teams : teams[team] = [] teams[team].append(name) self.replayInfo["teams"] = teams self.parent.db.close()
def update(self): '''Updating depots''' self.depots = {} query = QSqlQuery(self.parent.db) query.prepare("SELECT planetuid, influence, reinforcements, money FROM `planets_depots` WHERE 1") query.exec_() if query.size() > 0 : while query.next(): uid = int(query.value(0)) influence = int(query.value(1)) reinforcements = int(query.value(2)) money = int(query.value(3)) if not uid in self.depots: self.depots[uid] = Depot(uid, influence, reinforcements, money, self)
def update(self): query = QSqlQuery(self.parent.db) query.prepare("SELECT id, uid_player, uid_planet, attack_time, faction, defended, IFNULL(dominant,-1) FROM `attacks` LEFT JOIN accounts ON accounts.uid = uid_player LEFT JOIN domination on faction = domination.slave WHERE 1") query.exec_() if query.size() > 0 : allUids = [] while query.next() : uid = int(query.value(0)) playeruid = int(query.value(1)) planetuid = int(query.value(2)) attack = (time.time() - query.value(3).toTime_t()) faction = int(query.value(4)) if int(query.value(6)) != -1: faction = int(query.value(6)) defended = bool(query.value(5)) allUids.append(uid) if not uid in self.attacks : self.addAttack(uid, playeruid, faction, planetuid, attack, defended) else : self.updateAttack(uid, playeruid, attack, defended) toDelete = [] for uid in self.attacks : if not uid in allUids : toDelete.append(uid) for uid in toDelete : del self.attacks[uid] else : self.attacks = {}
def getPopularLadderMaps(self, count): query = QSqlQuery() query.prepare("SELECT `idMap` FROM `ladder_map_selection` GROUP BY `idMap` ORDER BY count(`idUser`) DESC LIMIT %i" % count) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def update(self): self.defenses = {} query = QSqlQuery(self.parent.db) query.prepare("SELECT planetuid, itemuid, amount, description, structure FROM planets_defense LEFT JOIN static_defenses ON static_defenses.id=planets_defense.itemuid WHERE amount != 0") if not query.exec_(): self.log.warning(query.lastError()) if query.size() > 0 : #query.first() while query.next() : planetuid = int(query.value(0)) itemuid = int(query.value(1)) amount = int(query.value(2)) description = str(query.value(3)) structure = str(query.value(4)) if not planetuid in self.defenses: self.defenses[planetuid] = defense(planetuid, self.parent) self.defenses[planetuid].addDefense(itemuid, amount, description, structure)
def getPlayerRealFaction(self, uid): query = QSqlQuery(self.parent.db) query.prepare("SELECT faction FROM galacticwar.`accounts` WHERE `uid` = ?") query.addBindValue(uid) query.exec_() if query.size() == 1 : query.first() return int(query.value(0)) return None
def updateTrueskillFor1v1(self): ''' Update all scores from the DB before updating the results''' try : for team in self.finalTeams1v1 : for member in team.getAllPlayers() : query = QSqlQuery(self.parent.db) query.prepare("SELECT mean, deviation FROM ladder1v1_rating WHERE id = (SELECT id FROM login WHERE login = ?)") query.addBindValue(member.getId()) query.exec_() self.log.debug("updating a player") if query.size() > 0: query.first() team.getRating(member).setMean(query.value(0)) team.getRating(member).setStandardDeviation(query.value(1)) else : self.log.debug("error updating a player") self.log.debug(member.getId()) except : self.log.exception("Something awful happened while updating trueskill!")
def getMapName(self, mapId): query = QSqlQuery(self.db) query.prepare("SELECT filename FROM table_map WHERE id = ?") query.addBindValue(mapId) query.exec_() if query.size() > 0: query.first() return str(query.value(0)).split("/")[1].replace(".zip", "") else: return None
def getSelectedLadderMaps(self, playerId): query = QSqlQuery(self.db) query.prepare("SELECT idMap FROM ladder_map_selection WHERE idUser = ?") query.addBindValue(playerId) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def getSelectedLadderMaps(self, playerId): query = QSqlQuery(self.db) query.prepare( "SELECT idMap FROM ladder_map_selection WHERE idUser = ?") query.addBindValue(playerId) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def getPopularLadderMaps(self, count): query = QSqlQuery() query.prepare( "SELECT `idMap` FROM `ladder_map_selection` GROUP BY `idMap` ORDER BY count(`idUser`) DESC LIMIT %i" % count) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def getPlayerRealFaction(self, uid): query = QSqlQuery(self.parent.db) query.prepare( "SELECT faction FROM galacticwar.`accounts` WHERE `uid` = ?") query.addBindValue(uid) query.exec_() if query.size() == 1: query.first() return int(query.value(0)) return None
def deleteGroup(self, group, player): query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1 : query.first() uid = int(query.value(0)) if not uid in self.deletedGroups: self.deletedGroups[uid] = [] if not group in self.deletedGroups[uid]: self.parent.lobby.sendJSON(dict(command="delete_group", group=group, playeruid=uid)) self.deletedGroups[uid].append(group)
def updateTrueskillFor1v1(self): ''' Update all scores from the DB before updating the results''' try: for team in self.finalTeams1v1: for member in team.getAllPlayers(): query = QSqlQuery(self.parent.db) query.prepare( "SELECT mean, deviation FROM ladder1v1_rating WHERE id = (SELECT id FROM login WHERE login = ?)" ) query.addBindValue(member.getId()) query.exec_() self.log.debug("updating a player") if query.size() > 0: query.first() team.getRating(member).setMean(query.value(0)) team.getRating(member).setStandardDeviation( query.value(1)) else: self.log.debug("error updating a player") self.log.debug(member.getId()) except: self.log.exception( "Something awful happened while updating trueskill!")
def deleteGroup(self, group, player): query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1: query.first() uid = int(query.value(0)) if not uid in self.deletedGroups: self.deletedGroups[uid] = [] if not group in self.deletedGroups[uid]: self.parent.lobby.sendJSON( dict(command="delete_group", group=group, playeruid=uid)) self.deletedGroups[uid].append(group)
def getPlayerName(self, player): ''' Get the avatar name ''' try: if player.getLogin() in self.avatarNames: return self.avatarNames[player.getLogin()] self.log.debug("getting avatar name for %s (uid %i)" % (player.getLogin(), player.getId())) query = QSqlQuery(self.parent.db) uid = int(player.getId()) query.prepare( "SELECT name, id FROM galacticwar.`avatars` WHERE `uid` = ? AND `alive` = 1" ) query.addBindValue(uid) query.exec_() if query.size() == 1: query.first() name = str(query.value(0)) uid = int(query.value(1)) self.avatarNames[player.getLogin()] = name self.avatarIds[player.getLogin()] = uid self.log.debug("avatar name is %s (uid %i)" % (name, uid)) return name else: self.avatarNames[player.getLogin()] = player.getLogin() self.avatarIds[player.getLogin()] = player.getId() return player.getLogin() except: self.log.exception( "Something awful happened when getting a gw name !")
def getGWReplaysInfos(self): self.parent.db.open() self.replayInfo["game_end"] = time.time() query = QSqlQuery(self.parent.db) self.replayInfo["featured_mod"] = "gw" self.replayInfo["game_type"] = 0 query.prepare("SELECT filename, planets.name, avatars.name \ FROM galacticwar.game_stats \ LEFT JOIN galacticwar.game_player_stats ON galacticwar.game_player_stats.`gameId` = galacticwar.game_stats.id \ LEFT JOIN galacticwar.planets ON galacticwar.planets.id = galacticwar.game_stats.planetuid \ LEFT JOIN galacticwar.planet_maps ON galacticwar.planet_maps.planetuid = galacticwar.game_stats.planetuid \ LEFT JOIN faf_lobby.table_map ON galacticwar.planet_maps.`mapuid` = faf_lobby.table_map.id \ LEFT JOIN galacticwar.avatars ON galacticwar.avatars.id = galacticwar.game_player_stats.`avatarId` \ WHERE galacticwar.game_stats.id = ? ") query.addBindValue(self.uid) query.exec_() if query.size() != 0: self.replayInfo["num_players"] = query.size() query.first() mapname = str(query.value(0)) self.replayInfo["title"] = str("battle on " +query.value(1)) self.replayInfo["featured_mod_versions"] = {} tableMod = "updates_gw" tableModFiles = tableMod + "_files" query2 = QSqlQuery(self.parent.db) query2.prepare("SELECT fileId, MAX(version) FROM `%s` LEFT JOIN %s ON `fileId` = %s.id GROUP BY fileId" % (tableModFiles, tableMod, tableMod)) query2.exec_() if query2.size() != 0 : while query2.next() : self.replayInfo["featured_mod_versions"][int(query2.value(0))] = int(query2.value(1)) self.replayInfo["mapname"] = os.path.splitext(os.path.basename(mapname))[0] self.replayInfo["complete"] = True self.parent.db.close()
def getLeague(self, season, player): query = QSqlQuery(self.db) query.prepare("SELECT league FROM %s WHERE idUser = ?" % season) query.addBindValue(player.getId()) query.exec_() if query.size() > 0 : query.first() return int(query.value(0)) # place the player in his league ! else : query.prepare("INSERT INTO %s (`idUser` ,`league` ,`score`) VALUES (?, 1, 0)" % season) query.addBindValue(player.getId()) query.exec_() return 1
def getLeague(self, season, player): query = QSqlQuery(self.db) query.prepare("SELECT league FROM %s WHERE idUser = ?" % season) query.addBindValue(player.getId()) query.exec_() if query.size() > 0: query.first() return int(query.value(0)) # place the player in his league ! else: query.prepare( "INSERT INTO %s (`idUser` ,`league` ,`score`) VALUES (?, 1, 0)" % season) query.addBindValue(player.getId()) query.exec_() return 1
def update(self): query = QSqlQuery(self.parent.db) query.prepare( "SELECT id, uid_player, uid_planet, attack_time, faction, defended, IFNULL(dominant,-1) FROM `attacks` LEFT JOIN accounts ON accounts.uid = uid_player LEFT JOIN domination on faction = domination.slave WHERE 1" ) query.exec_() if query.size() > 0: allUids = [] while query.next(): uid = int(query.value(0)) playeruid = int(query.value(1)) planetuid = int(query.value(2)) attack = (time.time() - query.value(3).toTime_t()) faction = int(query.value(4)) if int(query.value(6)) != -1: faction = int(query.value(6)) defended = bool(query.value(5)) allUids.append(uid) if not uid in self.attacks: self.addAttack(uid, playeruid, faction, planetuid, attack, defended) else: self.updateAttack(uid, playeruid, attack, defended) toDelete = [] for uid in self.attacks: if not uid in allUids: toDelete.append(uid) for uid in toDelete: del self.attacks[uid] else: self.attacks = {}
def addResultPlayer(self, player, faresult, score): if faresult == "recall" : self.log.debug("%s recalled" % player ) if not player in self.recalled: self.recalled.append(player) self.gameResult[player] = -1 self.gameFaResult[player] = faresult if faresult == "autorecall" : self.gameResult[player] = -1 self.gameFaResult[player] = faresult self.log.debug("%s autorecalled" % player ) if not player in self.autorecalled: self.autorecalled.append(player) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1 : query.first() playerUid = int(query.value(0)) self.log.debug(playerUid) self.parent.lobby.sendJSON(dict(command="autorecall", playeruid=playerUid)) if player in self.gameFaResult : self.log.debug("%s previous result : %s " % (player, self.gameFaResult[player])) self.log.debug("%s new result : %s " % (player, faresult)) if self.gameFaResult[player] == "score" : # the play got not decicive result yet, so we can apply it. self.gameFaResult[player] = faresult #self.gameResult[player] = score else : if faresult == "defeat": if player in self.recalled or player in self.autorecalled: self.log.debug("recalled to defeat -> invalid") self.wrongReport = True elif self.gameFaResult[player] == "victory" : if not player in self.invalidPlayers : self.log.debug("victory to defeat !?") #self.invalidPlayers.append(player) elif time.time() - self.startedAt < ((60*4) + 10) : self.log.debug("too soon to die...") self.setInvalid("Game is invalid : Play time was not long enough.") #if we try to set a defeat, but the player was victory.. We've got a disparity problem ! # else : if faresult != "score" : self.gameFaResult[player] = faresult if faresult == "defeat" : self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory" : self.gameResult[player] = 1 elif faresult == "draw" : self.gameResult[player] = -1 else : self.log.debug("%s result : %s " % (player, faresult)) if faresult != "score" : self.gameFaResult[player] = faresult if faresult == "defeat" : self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory" : self.gameResult[player] = 1 elif faresult == "draw" : self.gameResult[player] = -1
def addResultPlayer(self, player, faresult, score): if faresult == "recall": self.log.debug("%s recalled" % player) if not player in self.recalled: self.recalled.append(player) self.gameResult[player] = -1 self.gameFaResult[player] = faresult if faresult == "autorecall": self.gameResult[player] = -1 self.gameFaResult[player] = faresult self.log.debug("%s autorecalled" % player) if not player in self.autorecalled: self.autorecalled.append(player) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1: query.first() playerUid = int(query.value(0)) self.log.debug(playerUid) self.parent.lobby.sendJSON( dict(command="autorecall", playeruid=playerUid)) if player in self.gameFaResult: self.log.debug("%s previous result : %s " % (player, self.gameFaResult[player])) self.log.debug("%s new result : %s " % (player, faresult)) if self.gameFaResult[player] == "score": # the play got not decicive result yet, so we can apply it. self.gameFaResult[player] = faresult #self.gameResult[player] = score else: if faresult == "defeat": if player in self.recalled or player in self.autorecalled: self.log.debug("recalled to defeat -> invalid") self.wrongReport = True elif self.gameFaResult[player] == "victory": if not player in self.invalidPlayers: self.log.debug("victory to defeat !?") #self.invalidPlayers.append(player) elif time.time() - self.startedAt < ((60 * 4) + 10): self.log.debug("too soon to die...") self.setInvalid( "Game is invalid : Play time was not long enough.") #if we try to set a defeat, but the player was victory.. We've got a disparity problem ! # else: if faresult != "score": self.gameFaResult[player] = faresult if faresult == "defeat": self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory": self.gameResult[player] = 1 elif faresult == "draw": self.gameResult[player] = -1 else: self.log.debug("%s result : %s " % (player, faresult)) if faresult != "score": self.gameFaResult[player] = faresult if faresult == "defeat": self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory": self.gameResult[player] = 1 elif faresult == "draw": self.gameResult[player] = -1
def specialEnding(self, logger, db, players): try: self.log.debug("special ending.") if len(self.invalidPlayers ) == self.numPlayers or self.wrongReport == True: if self.wrongReport: self.log.debug( "Recalled player declared defeated.. Player recalled:") for p in self.recalled: self.log.debug(p) self.log.debug("Scores") self.log.debug(self.gameResult) self.log.debug("Recalled player declared defeated..") else: self.log.debug( "Invalid : self.invalidPlayers == numPlayer") self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) return False #computing winning team teams = self.finalTeams teamsResults = {} teamsResults[1] = {} teamsResults[2] = {} teamsResults[1]["players"] = {} teamsResults[2]["players"] = {} for teams in self.finalTeams: curScore = 0 for player in teams.getAllPlayers(): uid = player.getId() self.log.debug("searching") self.log.debug(uid) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(uid) query.exec_() playerUid = 1 if query.size() == 1: query.first() self.log.debug("found uid") playerUid = int(query.value(0)) self.log.debug(playerUid) if playerUid in self.attackers: i = 1 else: i = 2 if uid in str(self.gameResult): resultPlayer = self.gameResult[uid] if resultPlayer <= -1: if uid in self.recalled: teamsResults[i]["players"][playerUid] = 0 elif uid in self.autorecalled: teamsResults[i]["players"][playerUid] = -1 else: teamsResults[i]["players"][playerUid] = -2 else: teamsResults[i]["players"][playerUid] = 1 curScore = curScore + resultPlayer else: self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) self.log.debug("score not found for %s" % str(uid)) return 0 teamsResults[i]["score"] = curScore if self.desync < 2: results = json.dumps(teamsResults) self.log.debug(teamsResults) self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results=results)) else: self.log.debug(self.getInvalidReason()) self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) except: self.log.exception( "Something awful happened when finishing a gw game !")
def specialEnding(self, logger, db, players): if len(self.invalidPlayers) == 2: self.setInvalid( "Scores not validated. Possible reason : Disconnection between players." ) if self.isValid(): if self.isDraw(): query = QSqlQuery(db) queryStr = ("SELECT id FROM table_map WHERE filename LIKE '%" + self.getGameMap() + "%'") query.exec_(queryStr) if query.size() == 1: query.first() mapId = query.value(0) queryStr = ( "UPDATE table_map_features set num_draws = (num_draws +1) WHERE map_id LIKE " + str(mapId)) query.exec_(queryStr) # tsresults = self.computeResults() # tsplayers = self.getTrueSkillPlayers() # self.trueSkillUpdate(tsresults, tsplayers, logger, db, players) tsresults = self.computeResults1v1() tsplayers = self.getTrueSkill1v1Players() self.trueSkillUpdate(tsresults, tsplayers, logger, db, players, playerFnc="setladder1v1Rating", table="ladder1v1_rating", winner=True, sendScore=False) # and for the ladder ! evenLeague = True maxleague = max(self.leagues.iteritems(), key=operator.itemgetter(1))[1] if len(set(self.leagues.values())) != 1: evenLeague = False if not self.isDraw(): query = QSqlQuery(db) for player in self.gameResult: if self.isWinner(player): # if not even league: scoreToAdd = 1 if not evenLeague: if self.leagues[player] == maxleague: scoreToAdd = 0.5 else: scoreToAdd = 1.5 query.prepare( "UPDATE %s SET score = (score + ?) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToAdd) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) else: # if not even league: scoreToRemove = 0.5 if not evenLeague: if self.leagues[player] == maxleague: scoreToRemove = 1 else: scoreToRemove = 0 query.prepare( "UPDATE %s SET score = GREATEST(0,(score - ?)) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToRemove) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) #check if the user must be promoted query.prepare( "SELECT league, score FROM %s WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() if query.size() != 0: update = False query.first() pleague = int(query.value(0)) pscore = float(query.value(1)) if pleague == 1 and pscore > 50: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 2 and pscore > 75: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 3 and pscore > 100: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 4 and pscore > 150: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True for p in players.getAllPlayers(): if str(p.getLogin()) == str(player): query.prepare( "SELECT score, league FROM %s WHERE idUser = ?" % self.parent.season) query.addBindValue(p.getId()) query.exec_() if query.size() > 0: query.first() score = float(query.value(0)) league = int(query.value(1)) query.prepare( "SELECT name, `limit` FROM `ladder_division` WHERE `league` = ? AND `limit` >= ? ORDER BY `limit` ASC LIMIT 1" ) query.addBindValue(league) query.addBindValue(score) query.exec_() if query.size() > 0: query.first() p.setLeague(league) p.division = str(query.value(0)) else: tsplayers = self.getTrueSkillPlayers() for playerTS in tsplayers: name = playerTS.getPlayer() self.sendMessageToPlayers(players, name, self.getInvalidReason())
def specialEnding(self, logger, db, players): try : self.log.debug("special ending.") if len(self.invalidPlayers) == self.numPlayers or self.wrongReport == True: if self.wrongReport: self.log.debug("Recalled player declared defeated.. Player recalled:") for p in self.recalled: self.log.debug(p) self.log.debug("Scores") self.log.debug(self.gameResult) self.log.debug("Recalled player declared defeated..") else: self.log.debug("Invalid : self.invalidPlayers == numPlayer") self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) return False #computing winning team teams = self.finalTeams teamsResults = {} teamsResults[1] = {} teamsResults[2] = {} teamsResults[1]["players"] = {} teamsResults[2]["players"] = {} for teams in self.finalTeams : curScore = 0 for player in teams.getAllPlayers() : uid = player.getId() self.log.debug("searching") self.log.debug(uid) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(uid) query.exec_() playerUid = 1 if query.size() == 1 : query.first() self.log.debug("found uid") playerUid = int(query.value(0)) self.log.debug(playerUid) if playerUid in self.attackers : i = 1 else : i = 2 if uid in str(self.gameResult) : resultPlayer = self.gameResult[uid] if resultPlayer <= -1 : if uid in self.recalled : teamsResults[i]["players"][playerUid] = 0 elif uid in self.autorecalled: teamsResults[i]["players"][playerUid] = -1 else : teamsResults[i]["players"][playerUid] = -2 else : teamsResults[i]["players"][playerUid] = 1 curScore = curScore + resultPlayer else : self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) self.log.debug("score not found for %s" % str(uid)) return 0 teamsResults[i]["score"] = curScore if self.desync < 2: results = json.dumps(teamsResults) self.log.debug(teamsResults) self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results=results)) else: self.log.debug(self.getInvalidReason()) self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) except : self.log.exception("Something awful happened when finishing a gw game !")
def specialEnding(self, logger, db, players): if len(self.invalidPlayers) == 2 : self.setInvalid("Scores not validated. Possible reason : Disconnection between players.") if self.isValid() : if self.isDraw() : query = QSqlQuery(db) queryStr = ("SELECT id FROM table_map WHERE filename LIKE '%"+self.getGameMap()+"%'") query.exec_(queryStr) if query.size() == 1: query.first() mapId = query.value(0) queryStr = ("UPDATE table_map_features set num_draws = (num_draws +1) WHERE map_id LIKE " + str(mapId)) query.exec_(queryStr) # tsresults = self.computeResults() # tsplayers = self.getTrueSkillPlayers() # self.trueSkillUpdate(tsresults, tsplayers, logger, db, players) tsresults = self.computeResults1v1() tsplayers = self.getTrueSkill1v1Players() self.trueSkillUpdate(tsresults, tsplayers, logger, db, players, playerFnc="setladder1v1Rating" ,table="ladder1v1_rating", winner=True, sendScore=False) # and for the ladder ! evenLeague = True maxleague = max(self.leagues.iteritems(), key=operator.itemgetter(1))[1] if len(set(self.leagues.values())) != 1 : evenLeague = False if not self.isDraw() : query = QSqlQuery(db) for player in self.gameResult : if self.isWinner(player) : # if not even league: scoreToAdd = 1 if not evenLeague: if self.leagues[player] == maxleague: scoreToAdd = 0.5 else : scoreToAdd = 1.5 query.prepare("UPDATE %s SET score = (score + ?) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToAdd) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) else: # if not even league: scoreToRemove = 0.5 if not evenLeague : if self.leagues[player] == maxleague: scoreToRemove = 1 else : scoreToRemove = 0 query.prepare("UPDATE %s SET score = GREATEST(0,(score - ?)) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToRemove) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) #check if the user must be promoted query.prepare("SELECT league, score FROM %s WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() if query.size() != 0: update = False query.first() pleague = int(query.value(0)) pscore = float(query.value(1)) if pleague == 1 and pscore > 50: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 2 and pscore > 75: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 3 and pscore > 100: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 4 and pscore > 150: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True for p in players.getAllPlayers() : if str(p.getLogin()) == str(player) : query.prepare("SELECT score, league FROM %s WHERE idUser = ?" % self.parent.season) query.addBindValue(p.getId()) query.exec_() if query.size() > 0: query.first() score = float(query.value(0)) league = int(query.value(1)) query.prepare("SELECT name, `limit` FROM `ladder_division` WHERE `league` = ? AND `limit` >= ? ORDER BY `limit` ASC LIMIT 1") query.addBindValue(league) query.addBindValue(score) query.exec_() if query.size() > 0: query.first() p.setLeague(league) p.division = str(query.value(0)) else : tsplayers = self.getTrueSkillPlayers() for playerTS in tsplayers : name = playerTS.getPlayer() self.sendMessageToPlayers(players, name, self.getInvalidReason())
def save(layout): """"Saves the state of the program and moves the save file to specified place""" # Create a file if there is no previous save # else move db to current folder to save if not os.path.isfile(paths.savePath): # Create txt and write down the first day of usage savefile = open(paths.savePath, mode='w') savefile.write(str(global_vars.DAYFIRST.toordinal())) savefile.close() filename = os.path.basename(paths.savePath)[:-8] # Saving tasks widget block database.setConnection(filename) database.truncate() groups = layout.taskwidget.getGroups() for group in groups: query = QSqlQuery() query.prepare("INSERT INTO status (name) VALUES (:name)") query.bindValue(":name", group.getName()) query.exec_() query = QSqlQuery("SELECT rowid FROM status WHERE name = '" + group.getName() + "' ") query.next() id_ = query.value(0) for task in group: query = QSqlQuery() query.prepare("INSERT INTO tasks (name, status) VALUES (:name, :id)") query.bindValue(":name", task.getTask()) query.bindValue(":id", id_) query.exec_() # Saving maintable for weeknum in layout.tab.notsaved: table = layout.tab.getWidgetFromWeeknum(weeknum) weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for weekday in weekdays: tasks = table.getTasks(weekday) if tasks: fields = '' values = '' for time in tasks: query = QSqlQuery("SELECT rowid FROM tasks WHERE name ='" + tasks[time] + "'") query.next() tasks[time] = query.value(0) fields += '"' + time + '"' + ',' values += str(tasks[time]) + ',' fields = 'weekday,' + fields[:-1] values = '"' + weekday + '_' + str(weeknum) + '"' + ', ' + values[:-1] request = 'INSERT INTO main (' + fields + ') VALUES (' + values + ')' query = QSqlQuery() query.exec_(request) layout.tab.notsaved = [] # Saving evaluation values for week in global_vars.EVAL_VALUES.keys(): val = str(week) + ', ' for value in global_vars.EVAL_VALUES[week]: val += str(value) + ', ' request = 'INSERT INTO evaluation VALUES(' + val[:-2] + ')' query = QSqlQuery() query.exec_(request) # Saving neural network weights parent = layout.parentWidget() exists = True try: parent.network except (AttributeError, NameError): exists = False if exists: hdw = parent.network.hiddenweights otpw = parent.network.outputweights request = 'INSERT INTO weights (input, output, value) ' for i in range(len(hdw)): for j in range(len(hdw[i])): if (i == 0) and (j == 0): request += 'SELECT ' + '"in_' + str(i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) else: request += ' UNION ALL' request += ' SELECT ' + '"in_' + str(i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) for i in range(len(otpw)): for j in range(len(otpw[i])): request += ' UNION ALL' request += ' SELECT ' + '"hidden_' + str(i) + '", "out_' + str(j) + '", ' + str(hdw[i][j]) print(request) query = QSqlQuery() query.exec_(request) print(query.lastError()) print('Saved') # Restoring the original state database.dropConnection()
def save(layout): """"Saves the state of the program and moves the save file to specified place""" # Create a file if there is no previous save # else move db to current folder to save if not os.path.isfile(paths.savePath): # Create txt and write down the first day of usage savefile = open(paths.savePath, mode='w') savefile.write(str(global_vars.DAYFIRST.toordinal())) savefile.close() filename = os.path.basename(paths.savePath)[:-8] # Saving tasks widget block database.setConnection(filename) database.truncate() groups = layout.taskwidget.getGroups() for group in groups: query = QSqlQuery() query.prepare("INSERT INTO status (name) VALUES (:name)") query.bindValue(":name", group.getName()) query.exec_() query = QSqlQuery("SELECT rowid FROM status WHERE name = '" + group.getName() + "' ") query.next() id_ = query.value(0) for task in group: query = QSqlQuery() query.prepare( "INSERT INTO tasks (name, status) VALUES (:name, :id)") query.bindValue(":name", task.getTask()) query.bindValue(":id", id_) query.exec_() # Saving maintable for weeknum in layout.tab.notsaved: table = layout.tab.getWidgetFromWeeknum(weeknum) weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] for weekday in weekdays: tasks = table.getTasks(weekday) if tasks: fields = '' values = '' for time in tasks: query = QSqlQuery("SELECT rowid FROM tasks WHERE name ='" + tasks[time] + "'") query.next() tasks[time] = query.value(0) fields += '"' + time + '"' + ',' values += str(tasks[time]) + ',' fields = 'weekday,' + fields[:-1] values = '"' + weekday + '_' + str( weeknum) + '"' + ', ' + values[:-1] request = 'INSERT INTO main (' + fields + ') VALUES (' + values + ')' query = QSqlQuery() query.exec_(request) layout.tab.notsaved = [] # Saving evaluation values for week in global_vars.EVAL_VALUES.keys(): val = str(week) + ', ' for value in global_vars.EVAL_VALUES[week]: val += str(value) + ', ' request = 'INSERT INTO evaluation VALUES(' + val[:-2] + ')' query = QSqlQuery() query.exec_(request) # Saving neural network weights parent = layout.parentWidget() exists = True try: parent.network except (AttributeError, NameError): exists = False if exists: hdw = parent.network.hiddenweights otpw = parent.network.outputweights request = 'INSERT INTO weights (input, output, value) ' for i in range(len(hdw)): for j in range(len(hdw[i])): if (i == 0) and (j == 0): request += 'SELECT ' + '"in_' + str( i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) else: request += ' UNION ALL' request += ' SELECT ' + '"in_' + str( i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) for i in range(len(otpw)): for j in range(len(otpw[i])): request += ' UNION ALL' request += ' SELECT ' + '"hidden_' + str(i) + '", "out_' + str( j) + '", ' + str(hdw[i][j]) print(request) query = QSqlQuery() query.exec_(request) print(query.lastError()) print('Saved') # Restoring the original state database.dropConnection()
def load(layout): """"Loads the file and restores the saved state""" # Restore the first day of usage global_vars.DAYFIRST = datetime.date.fromordinal( int(open(paths.savePath).read().splitlines()[0])) filename = os.path.basename(paths.savePath)[:-8] database.setConnection(filename) layout.initTasks(database.getStatuses()) layout.tab.clearAll() # ### Loading main table # # weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] opened = False q = 'SELECT * FROM main' query = QSqlQuery(q) while query.next(): record = query.record() indexes = [] if not record.isEmpty(): for i in range(0, 44): if not record.isNull(i + 1): indexes.append(i) day = str(record.field('weekday').value()).split('_') weekday = day[0] weeknum = int(day[1]) values = {} for index in indexes: q = QSqlQuery("SELECT name FROM tasks WHERE rowid ='" + str(query.value(index + 1)) + "'") q.next() values[index] = q.value(0) if values: opened = True layout.tab.setValues(values, weekdays.index(weekday), weeknum) if not opened: layout.tab.openTab(1) # # ################ # Loading evaluation values # q = 'SELECT * from evaluation' query = QSqlQuery(q) while query.next(): record = query.record() if not record.isEmpty(): week = record.field('week').value() values = [] for day in global_vars.WEEKDAYS: values.append(record.field(day).value()) global_vars.EVAL_VALUES[week] = values database.dropConnection()