def init( self ): """Provides default initialisation.""" # Load the configuration self.__config = self.mm.getModuleConfig( configDefaults ) self.__profileIds = dict.fromkeys( self.__config['profileIds'], 1 ) self.__newPlayers = {} self.__reservedPlayers = {} if host.ss_getParam('ranked'): # Max of 20% max_reserved = ( host.ss_getParam( 'maxPlayers' ) * 0.2 ) if self.__config['reservedSlots'] > max_reserved: self.mm.warn( "Max reserved slots is 20%% of maxPlayers on ranked servers, setting to %d" % max_reserved ) self.__config['reservedSlots'] = max_reserved # Register your game handlers and provide any # other dynamic initialisation here if 0 == self.__state: host.registerHandler( 'PlayerSpawn', self.onPlayerSpawn, 1 ) host.registerHandler( 'PlayerConnect', self.onPlayerConnect, 1 ) host.registerHandler( 'PlayerDisconnect', self.onPlayerDisconnect, 1 ) # Register our rcon command handlers self.mm.registerRconCmdHandler( 'reserver', { 'method': self.cmdExec, 'subcmds': self.__cmds, 'level': 1 } ) # Update to the running state self.__state = 1
def init(self): """Provides default initialisation.""" # Load the configuration self.__config = self.mm.getModuleConfig(configDefaults) self.__profileIds = dict.fromkeys(self.__config['profileIds'], 1) self.__newPlayers = {} self.__reservedPlayers = {} if host.ss_getParam('ranked'): # Max of 20% max_reserved = (host.ss_getParam('maxPlayers') * 0.2) if self.__config['reservedSlots'] > max_reserved: self.mm.warn( "Max reserved slots is 20%% of maxPlayers on ranked servers, setting to %d" % max_reserved) self.__config['reservedSlots'] = max_reserved # Register your game handlers and provide any # other dynamic initialisation here if 0 == self.__state: host.registerHandler('PlayerSpawn', self.onPlayerSpawn, 1) host.registerHandler('PlayerConnect', self.onPlayerConnect, 1) host.registerHandler('PlayerDisconnect', self.onPlayerDisconnect, 1) # Register our rcon command handlers self.mm.registerRconCmdHandler('reserver', { 'method': self.cmdExec, 'subcmds': self.__cmds, 'level': 1 }) # Update to the running state self.__state = 1
def onPlayerChangeTeams(p, humanHasSpawned): if not bf2.serverSettings.getAutoBalanceTeam(): return # dont teamswitch alive players, or they will have the wrong teams kit if p.isAlive(): return if host.sgl_getIsAIGame() and not (host.ss_getParam('gameMode') == "gpm_coop"): if humanHasSpawned: return if p.isAIPlayer(): return # handling aiplayer team change autobalance when round not started team = p.getTeam() aiplayer = 0 for tp in bf2.playerManager.getPlayers(): if aiplayer == 0 and tp.getTeam() == team and tp.isAIPlayer(): aiplayer = tp break if aiplayer: if p.getTeam() == 1: aiplayer.setTeam(2) else: aiplayer.setTeam(1) else: # checking to see if player is allowed to change teams team1 = 0 team2 = 0 for tp in bf2.playerManager.getPlayers(): if tp.getTeam() == 1: team1 += 1 else: team2 += 1 if abs(team1 - team2) > 1: if p.getTeam() == 1: p.setTeam(2) else: p.setTeam(1)
def exec_subcmd( mm, subcmds, ctx, cmd ): """Execute a modules sub command.""" module = caller_module() mm.debug( 2, "%s '%s' by %s" % ( module, cmd, ctx.getName() ) ) ( subcmd, args ) = lsplit( cmd.strip(), ' ', 2 ) if subcmds.has_key( subcmd ): subcmd_details = subcmds[subcmd] if 0 == subcmd_details['level'] or ctx.authedAllowed( ctx, subcmd_details ): try: if subcmd_details['restricted'] and host.ss_getParam('ranked'): msg = "Restricted: Sorry command '%s' is not permitted on ranked servers" % subcmd self.mm.debug( 1, msg ) ctx.write( msg ) else: subcmds[subcmd]['method']( ctx, args ) except Exception, e: # generate line number lineNum = '' execInfo = sys.exc_info() tb = execInfo[2] while tb is not None: if lineNum == '': lineNum = str( tb.tb_lineno ) else: lineNum += ', ' + str( tb.tb_lineno ) tb = tb.tb_next mm.error( "%s: Failed to run sub command '%s'" % ( module, ctx.currentCmd ), True ) ctx.write('Exception in sub command \'%s\' %s %s (%s)\n' % ( ctx.currentCmd, str(execInfo[0]), str(e), lineNum)) else: ctx.write( "error: you are not authorised to use the command '%s' it requires level %d you are only level %d" % ( subcmd, ctx.authedLevel, cmd_details['level'] ) ) mm.warn( "Client %s tried to invoke '%s' without sufficient auth level" % ( ctx.getName(), subcmd ) )
def init(self): """Provides default initialisation.""" # Load the configuration self.__config = self.mm.getModuleConfig(configDefaults) # Register your game handlers and provide any # other dynamic initialisation here if not bf2.g_debug: self.mm.info("Global python debugging is disabled") self.mm.info("To enable edit: python/bf2/__init__.py") self.mm.info("and set 'g_debug = 1'") else: self.mm.warn("Global python is enabled.") self.mm.warn( "This may have unexpected side effects and a performance impact!" ) if not host.ss_getParam('ranked'): self.mm.error("This server is NOT ranked!") else: self.mm.info("This server is ranked!") if 0 == self.__state: # Register your host handlers here host.registerHandler('PlayerConnect', self.onPlayerConnect, 1) host.registerHandler('PlayerStatsResponse', self.onStatsResponse, 1) # Update to the running state self.__state = 1
def copyPlayerData(self, player): self.timeOnLine += date() - self.connectAt self.localScore = player.score self.score = player.score.score self.cmdScore = player.score.cmdScore self.teamScore = player.score.rplScore self.skillScore = player.score.skillScore if self.score < 0: self.score = 0 if self.cmdScore < 0: self.cmdScore = 0 if self.teamScore < 0: self.teamScore = 0 if self.skillScore < 0: self.skillScore = 0 self.kills = player.score.kills self.teamkills = player.score.TKs self.deaths = player.score.deaths self.rank = player.score.rank self.army = roundArmies[player.getTeam()] self.team = player.getTeam() if host.ss_getParam('ranked'): if hasattr(player, 'medals'): self.medals = player.medals else: if g_debug: print "Player had no medal stats. pid=", player.index
def onPlayerDeath(p, vehicle): if not bf2.serverSettings.getAutoBalanceTeam(): return if p.isSquadLeader(): return if p.isCommander(): return if (host.ss_getParam('gameMode') == "gpm_coop") and p.isAIPlayer(): return # dont use autobalance when its suicide/changes team if p.getSuicide(): p.setSuicide(0) return aiPlayerBalance = 0 team1 = 0 team2 = 0 for tp in bf2.playerManager.getPlayers(): if tp.getTeam() == 1: team1 += 1 else: team2 += 1 if tp.isAIPlayer(): aiPlayerBalance += 1 else: aiPlayerBalance -= 1 if host.sgl_getIsAIGame(): if not (host.ss_getParam('gameMode') == "gpm_coop"): if not (aiPlayerBalance < 0): if not p.isAIPlayer(): return team2 = team2 * bf2.serverSettings.getTeamRatioPercent() / 100.0 if (p.getTeam() == 1): if (team2+1) < team1: p.setTeam(2) elif (p.getTeam() == 2): if (team1+1) < team2: p.setTeam(1)
def onPlayerDeath(p, vehicle): if not bf2.serverSettings.getAutoBalanceTeam(): return if p.isSquadLeader(): return if p.isCommander(): return if (host.ss_getParam('gameMode') == "gpm_coop") and p.isAIPlayer(): return # dont use autobalance when its suicide/changes team if p.getSuicide(): p.setSuicide(0) return aiPlayerBalance = 0 team1 = 0 team2 = 0 for tp in bf2.playerManager.getPlayers(): if tp.getTeam() == 1: team1 += 1 else: team2 += 1 if tp.isAIPlayer(): aiPlayerBalance += 1 else: aiPlayerBalance -= 1 if host.sgl_getIsAIGame(): if not (host.ss_getParam('gameMode') == "gpm_coop"): if not (aiPlayerBalance < 0): if not p.isAIPlayer(): return team2 = team2 * bf2.serverSettings.getTeamRatioPercent() / 100.0 if (p.getTeam() == 1): if (team2 + 1) < team1: p.setTeam(2) elif (p.getTeam() == 2): if (team1 + 1) < team2: p.setTeam(1)
def __updateServerPassword( self ): """Sets or removes the password on the server depending on the state.""" if not host.ss_getParam('ranked') and self.__config['privatePassword']: # We can password the server as its not ranked ( needed_slots, remaining_slots ) = self.__neededRemainingSlots() if not needed_slots: # dont need any reserved slots remove the password host.rcon_invoke( 'sv.password ""' ) else: host.rcon_invoke( 'sv.password "%s"' % self.__config['privatePassword'] ) return 1
def __updateServerPassword(self): """Sets or removes the password on the server depending on the state.""" if not host.ss_getParam('ranked') and self.__config['privatePassword']: # We can password the server as its not ranked (needed_slots, remaining_slots) = self.__neededRemainingSlots() if not needed_slots: # dont need any reserved slots remove the password host.rcon_invoke('sv.password ""') else: host.rcon_invoke('sv.password "%s"' % self.__config['privatePassword']) return 1
def onPlayerChangeTeams(self, p, humanHasSpawned): """Ensure the player isnt unbalancing the teams.""" if 1 != self.__state: return self.mm.debug(2, "AB: change") if not bf2.serverSettings.getAutoBalanceTeam(): return # dont teamswitch alive players, or they will have the wrong teams kit if p.isAlive(): return if host.sgl_getIsAIGame() and ( self.mm.isBattleField2142() or not (host.ss_getParam('gameMode') == "gpm_coop")): if humanHasSpawned or p.isAIPlayer(): return # handling aiplayer team change autobalance when round not started team = p.getTeam() aiplayer = 0 for tp in bf2.playerManager.getPlayers(): if aiplayer == 0 and tp.getTeam() == team and tp.isAIPlayer(): aiplayer = tp break if aiplayer: if p.getTeam() == 1: aiplayer.setTeam(2) else: aiplayer.setTeam(1) else: # checking to see if player is allowed to change teams team1 = 0 team2 = 0 for tp in bf2.playerManager.getPlayers(): if tp.getTeam() == 1: team1 += 1 else: team2 += 1 if abs(team1 - team2) > 1: if p.getTeam() == 1: p.setTeam(2) else: p.setTeam(1)
def onGameStatusChanged( self, status ): """Make a note of the game status""" self.debug( 1, "STATUS: %d = %s" % ( status, mm_utils.status_name( status ) ) ) if bf2.GameStatus.EndGame == status: self.__playCount = 0 self.__pauseStart = 0 self.__timeLimit = 0 self.gamePlaying = False self.roundStarted = False elif bf2.GameStatus.Playing == status: self.gamePlaying = True now = int( host.timer_getWallTime() ) if bf2.GameStatus.PreGame == self.currentGameStatus: # normal transition i.e. not pause start_delay = int( host.rcon_invoke( 'sv.startDelay' ) ) self.__playCount += 1 self.__timeLimit = host.ss_getParam( 'timeLimit' ) self.__matchTimeLost = 0 self.startTimeUTC = int( time.time() ) + start_delay self.startTimeWall = now + start_delay if 2 == self.__playCount: # We see state change from PreGame -> Playing twice before the round really starts self.roundStarted = True elif bf2.GameStatus.Paused == self.currentGameStatus: self.__matchTimeLost += ( now - self.__pauseStart ) self.__pauseStart = 0 elif bf2.GameStatus.Paused == status: self.__pauseStart = int( host.timer_getWallTime() ) else: self.__pauseStart = 0 self.lastGameStatus = self.currentGameStatus self.currentGameStatus = status
def getUseGlobalUnlocks(self): return host.ss_getParam("globUnlocks")
def getTKPunishEnabled(self): return host.ss_getParam("tkpEnabled")
def getTKPunishByDefault(self): return host.ss_getParam("tkpDefault")
def onPlayerDeath(self, p, vehicle): """Autobalance a player that has died if required and allowed by the balance rules.""" if 1 != self.__state: return if p == None: return if self.mm.isBattleField2142(): # bf2142 specific if not p.isValid() or p.isAutoController(): return else: # bf2 specific if (host.ss_getParam('gameMode') == "gpm_coop") and p.isAIPlayer(): return if not bf2.serverSettings.getAutoBalanceTeam(): return # dont use autobalance when its suicide/changes team if p.getSuicide(): p.setSuicide(0) return if (not self.__config['allowCommander']) and p.isCommander(): # dont autobalance the commander return squadid = p.getSquadId() teamid = p.getTeam() players = bf2.playerManager.getPlayers() if (not self.__config['allowSquadLeader']) and p.isSquadLeader(): # only autobalance the squad leader if they are the only # member of that squad squad_members = 0 for tp in players: if squadid == tp.getSquadId() and tp.index != p.index: # we have other members in this squad dont autobalance #self.mm.debug( 2, "AB: no ( squad leader with members )" ) return if (not self.__config['allowSquadMember']) and (squadid > 0): # only autobalance squad members if there are no none # squad members / commander on this team basic_players = 0 for tp in players: if (0 == tp.getSquadId()) and (teamid == tp.getTeam()) and ( not p.isCommander()): # none squad member / commander of this team basic_players += 1 if 0 != basic_players: # we have basic players in this team we # will balance them instead #self.mm.debug( 2, "AB: no ( basic players avail )" ) return aiPlayerBalance = 0 team1 = 0 team2 = 0 for tp in players: if tp.getTeam() == 1: team1 += 1 else: team2 += 1 if tp.isAIPlayer(): aiPlayerBalance += 1 else: aiPlayerBalance -= 1 if host.sgl_getIsAIGame(): if self.mm.isBattleField2142() or not (host.ss_getParam('gameMode') == "gpm_coop"): if not (aiPlayerBalance < 0): if not p.isAIPlayer(): return team2 = team2 * bf2.serverSettings.getTeamRatioPercent() / 100.0 if (teamid == 1): if (team2 + 1) < team1: #self.mm.debug( 2, "AB: player '%s' -> team %d" % ( p.getName(), 2 ) ) p.setTeam(2) elif (teamid == 2): if (team1 + 1) < team2: #self.mm.debug( 2, "AB: player '%s' -> team %d" % ( p.getName(), 1 ) ) p.setTeam(1)
def getScoreLimit(self): return host.ss_getParam("scoreLimit")
def getMaxPlayers(self): return host.ss_getParam('maxPlayers') def getGameMode(self): return host.ss_getParam('gameMode')
def getMapName(self): return host.ss_getParam('mapName') def getTimeLimit(self): return host.ss_getParam('timeLimit')
def getGameMode(self): return host.ss_getParam('gameMode')
def getTKPunishByDefault(self): return host.ss_getParam('tkpDefault') def getUseGlobalRank(self): return host.ss_getParam('globRank')
def getTeamRatioPercent(self): return host.ss_getParam('teamRatioPct')
def getMaxPlayers(self): return host.ss_getParam('maxPlayers')
def getTicketRatio(self): return host.ss_getParam('ticketRatio')
def getTKNumPunishToKick(self): return host.ss_getParam('tkpNeeded') def getTKPunishByDefault(self): return host.ss_getParam('tkpDefault')
def getAutoBalanceTeam(self): return host.ss_getParam('autoBalance') def getTKPunishEnabled(self): return host.ss_getParam('tkpEnabled')
def getScoreLimit(self): return host.ss_getParam('scoreLimit') def getAutoBalanceTeam(self): return host.ss_getParam('autoBalance')
def getMaxRank(self): return host.ss_getParam('maxRank')
def getTKPunishEnabled(self): return host.ss_getParam('tkpEnabled') def getTKNumPunishToKick(self): return host.ss_getParam('tkpNeeded')
def getGameMode(self): return host.ss_getParam('gameMode') def getMapName(self): return host.ss_getParam('mapName')
def getUseGlobalUnlocks(self): return host.ss_getParam('globUnlocks') def getMaxRank(self): return host.ss_getParam('maxRank')
def getTimeLimit(self): return host.ss_getParam('timeLimit') def getScoreLimit(self): return host.ss_getParam('scoreLimit')
def init(self): """Provides default initialisation.""" # Load the configuration self.__config = self.mm.getModuleConfig(configDefaults) self.__playing = 0 self.__banWords = {} self.__banPatterns = {} self.__kickPatterns = {} self.__kickWords = {} # Register our base handlers if 0 == self.__state: self.mm.debug(2, "Setting Connect and Chat handlers") host.registerHandler('PlayerConnect', self.onPlayerConnect, 1) host.registerHandler('ChatMessage', self.onChatMessage, 1) self.mm.debug(2, "Handlers set") else: self.mm.debug(2, "Handlers NOT set") host.registerGameStatusHandler(self.onGameStatusChanged) # Register our rcon command handlers self.mm.registerRconCmdHandler('kicker', { 'method': self.cmdExec, 'subcmds': self.__cmds, 'level': 1 }) # Apply ranked server restrictions if host.ss_getParam('ranked'): if 0 != self.__config['minPing']: self.__config['minPing'] = 0 self.mm.warn( "Min ping is restricted on ranked servers setting to %d" % self.__config['minPing']) if self.__config['maxPing'] and self.__config['maxPing'] < 160: self.__config['maxPing'] = 160 self.mm.warn( "Max ping is restricted on ranked servers setting to %d" % self.__config['maxPing']) # set up our times self.__checkTimer = bf2.Timer(self.checkPlayers, self.__config['initDelay'], 1) self.__checkTimer.setRecurring(self.__config['sampleRate']) # ban words idx = 0 for word in self.__config['banWords']: self.__banWords[word] = idx idx += 1 # ban patterns idx = 0 for pattern in self.__config['banPatterns']: try: self.__banPatterns[pattern] = [re.compile(pattern), idx] idx += 1 except: self.mm.error("Invalid bad pattern '%s'" % pattern) # kick words idx = 0 for word in self.__config['kickWords']: self.__kickWords[word] = idx idx += 1 # kick patterns idx = 0 for pattern in self.__config['kickPatterns']: try: self.__kickPatterns[pattern] = [re.compile(pattern), idx] idx += 1 except: self.mm.error("Invalid kick pattern '%s'" % pattern) # add already connected players for player in bf2.playerManager.getPlayers(): player.mmKickerInfo = KickerInfo() self.__state = 1
def getMapName(self): return host.ss_getParam("mapName")
def getMaxRank(self): return host.ss_getParam('maxRank') class GameServer:
def getUseGlobalRank(self): return host.ss_getParam('globRank') def getUseGlobalUnlocks(self): return host.ss_getParam('globUnlocks')
def getTicketRatio(self): return host.ss_getParam("ticketRatio")
def getMapName(self): return host.ss_getParam('mapName')
def getMaxPlayers(self): return host.ss_getParam("maxPlayers")
def onGameStatusChanged(status): if status == bf2.GameStatus.Playing: # find highest player still connected highestPid = -1 for pid in sessionPlayerStatsMap: if pid > highestPid: highestPid = pid global playerConnectionOrderIterator playerConnectionOrderIterator = highestPid + 1 print "Reset orderiterator to %d based on highest pid kept" % playerConnectionOrderIterator # Reconnect players #if len(sessionPlayerStatsMap) == 0: #print("Reloading players"); for p in bf2.playerManager.getPlayers(): onPlayerConnect(p) global army roundArmies[1] = getArmy(bf2.gameLogic.getTeamName(1)) roundArmies[2] = getArmy(bf2.gameLogic.getTeamName(2)) # All other hooks host.registerHandler('PlayerKilled', onPlayerKilled) host.registerHandler('PlayerDeath', onPlayerDeath) host.registerHandler('EnterVehicle', onEnterVehicle) host.registerHandler('ExitVehicle', onExitVehicle) host.registerHandler('PickupKit', onPickupKit) host.registerHandler('DropKit', onDropKit) host.registerHandler('PlayerChangedSquad', onPlayerChangedSquad) host.registerHandler('ChangedCommander', onChangedCommander) host.registerHandler('ChangedSquadLeader', onChangedSquadLeader) host.registerHandler('PlayerChangeWeapon', onPlayerChangeWeapon) host.registerHandler('PlayerBanned', onPlayerBanned) host.registerHandler('PlayerKicked', onPlayerKicked) host.registerHandler('PlayerSpawn', onPlayerSpawn) host.registerHandler('DeployGrapplingHook', onDeployGrapplingHook) host.registerHandler('DeployZipLine', onDeployZipLine) host.registerHandler('DeployTactical', onDeployTactical) for s in sessionPlayerStatsMap.itervalues(): s.reset() for p in bf2.playerManager.getPlayers(): p.stats.reinit(p) p.stats.wasHereAtStart = 1 bf2.playerManager.enableScoreEvents() # stats have all been cleared enable next end of round stats setSendEndOfRoundStats(True) elif status == bf2.GameStatus.EndGame: # finalize stats and send snapshot for p in bf2.playerManager.getPlayers(): p.stats.wasHereAtEnd = 1 finalizePlayer(p) # check ensure we only send the end of round stats once if getSendEndOfRoundStats(): # show end-of-round information setSendEndOfRoundStats(False) bf2.stats.endofround.invoke() # if not ranked, clean out stats vectors if not host.ss_getParam('ranked'): playerConnectionOrderIterator = 0 sessionPlayerStatsMap.clear() if ((host.ss_getParam('gameMode') == "gpm_coop") or (host.ss_getParam('gameMode') == "sp1")): for p in bf2.playerManager.getPlayers(): if not p.isAIPlayer(): onPlayerConnect(p)
def getTimeLimit(self): return host.ss_getParam('timeLimit')
def getTeamRatioPercent(self): return host.ss_getParam("teamRatioPct")
def getScoreLimit(self): return host.ss_getParam('scoreLimit')
def getGameMode(self): return host.ss_getParam("gameMode")
def getAutoBalanceTeam(self): return host.ss_getParam('autoBalance')
def getTimeLimit(self): return host.ss_getParam("timeLimit")
def getTKPunishEnabled(self): return host.ss_getParam('tkpEnabled')
def getAutoBalanceTeam(self): return host.ss_getParam("autoBalance")
def getTKNumPunishToKick(self): return host.ss_getParam('tkpNeeded')
def getTKNumPunishToKick(self): return host.ss_getParam("tkpNeeded")
def getTKPunishByDefault(self): return host.ss_getParam('tkpDefault')
def getUseGlobalRank(self): return host.ss_getParam("globRank")
def getUseGlobalRank(self): return host.ss_getParam('globRank')
def getMaxRank(self): return host.ss_getParam("maxRank")
def getUseGlobalUnlocks(self): return host.ss_getParam('globUnlocks')