def pop_tts(self, player, needs_short_time = False): last_tts = player.__dict__.get('fh2_kitlim_last_tts', None) if DEBUG: print 'popping tts', last_tts if last_tts is None and not needs_short_time: return dst = defaultspawntime(player) if 'deathtime' in player.__dict__: if DEBUG: print 'deathtime is', player.deathtime rst = host.timer_getWallTime() - player.deathtime if DEBUG: print 'time since death is', rst rst = dst - rst if DEBUG: print 'remaining spawn time is', rst else: rst = dst if rst < 0: rst = 0 if rst > dst: rst = dst rst += 1 # Changing rst to be compatible with spawnwave system - Spit. try: if not player.isManDown(): player.is_first_waiting = False if (host.timer_getWallTime() - player.deathtime) < player.stod + spawnwave.waveTime(): player.is_first_waiting = True # Change the spawntime only if HUGE_TTS is applied: if player.getTimeToSpawn() > 400 and int(game.utilities.rconExec('sv.spawntime')) > spawnwave.minTime(): rst = game.utilities.getSpawnTime(rstime = round_start_time, dt = player.command_time) if not player.is_first_waiting: # Not first waiting if rst < (dst - spawnwave.waveTime()): # Spawnwave does not last player.setTimeToSpawn(rst) else: # Spawnave lasts player.setTimeToSpawn(0) else: # First waiting ovv = player.stod - int(game.utilities.rconExec('sv.spawntime')) if ovv < 0: ovv = 0 if rst < spawnwave.minTime() and (host.timer_getWallTime() - player.deathtime) < ovv: # Apply minimum time fix only in proper moment. rst = rst + int(game.utilities.rconExec('sv.spawntime')) if (host.timer_getWallTime() - player.deathtime) >= (player.stod - 2): player.setTimeToSpawn(0) else: player.setTimeToSpawn(rst) else: player.setTimeToSpawn(rst) except Exception, e: player.setTimeToSpawn(rst)
def updateLoop(data = ''): global lastRecordedTime #D.debugUDP('U_TIME: %s' % (D.time_now())) delta = host.timer_getWallTime() - lastRecordedTime lastRecordedTime = host.timer_getWallTime() if G_TRACKEDVEHICLE != None: position = G_TRACKEDVEHICLE.getPosition() rotation = G_TRACKEDVEHICLE.getRotation() D.debug('POSROT: P%sP|R%sR|T(%s)T|D(%s)D' % (position, rotation, host.timer_getWallTime(), delta), ['udp', 'echo'])
def deathhook(self, player, soldier): player.deathtime = host.timer_getWallTime() # Spawntime on death: player.stod = game.utilities.getSpawnTime(rstime = round_start_time, dt = player.deathtime) if player.stod < spawnwave.minTime(): player.stod = player.stod + int(game.utilities.rconExec('sv.spawntime')) selected = player.__dict__.get('fh2_kitlim_selected', None) if selected is None: return player.deathtime = host.timer_getWallTime() self.rconhook(player.index, 'selectkit %d'%selected)
def checkGrindBlockRemote(player, object): if not hasattr(player, "lastDestroyedRemote"): player.lastDestroyedRemote = {} else: if object in player.lastDestroyedRemote: if ( player.lastDestroyedRemote[object] + REPLENISH_POINT_MIN_INTERVAL > host.timer_getWallTime() ): return True player.lastDestroyedRemote[object] = host.timer_getWallTime() return False
def runCmd(self, playerid, cmd, args): """Runs an admin command.""" ctx = self.mm.getRconContext(playerid) if not ctx.authedLevel: # Automatically log the player in ctx.autoLogin = "******" % (playerid, int(host.timer_getWallTime())) self.mm.runRconCommand(playerid, "login %s" % ctx.autoLogin) ctx.autoLogin = "" # Prevent future logins logout = True else: logout = False if -1 != cmd.find('%arg'): # Have replacement params so iterate through replacing args_list = mm_utils.largs(args, None, 0, '', True) for i in range(len(args_list)): arg_name = ("%%arg%s%%" % (i + 1)) cmd = cmd.replace(arg_name, args_list[i]) args = "" ret = self.mm.runRconCommand(playerid, "%s %s" % (cmd, args)) # Automatically log the player in if logout: self.mm.runRconCommand(playerid, "logout") return ret
def onPlayerKilled(self, victim, attacker, weapon, assists, object): """Check to team kills.""" if 1 != self.__state: return 0 if not self.checkEnable(): return if not victim or not attacker or victim == attacker or victim.getTeam( ) != attacker.getTeam(): return # verify that TK was really given # no teamkills from wrecks if object != None and object.getIsWreck(): return # no teamkills from artillery if weapon: attackerVehicle = bf2.objectManager.getRootParent(weapon) if attackerVehicle.isPlayerControlObject and attackerVehicle.getIsRemoteControlled( ): return # ok, we have a teamkill currentTime = host.timer_getWallTime() attacker.tkData.pending += [(currentTime, victim)] self.hasPendingTks[attacker] = 1 victim.tkData.lastTKedBy = attacker # can only punish / forgive the last TK'er bf2.gameLogic.sendClientCommand( victim.index, TK_PUNISH_COMMANDID, (2, victim.index, attacker.index, self.__config['punishTime']))
def executePunishAction(victim, punish): if not checkEnable() or not victim or not victim.isValid(): return attacker = victim.tkData.lastTKedBy if attacker == None or not attacker.isValid(): return global hasPendingTks currentTime = host.timer_getWallTime() newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # if the attacker had a pending tk, and time has not run out if tkVictim == victim and tkDate + TK_PUNISH_TIME > currentTime: if punish: attacker.tkData.punished += 1 bf2.gameLogic.sendClientCommand(-1, 100, (0, victim.index, attacker.index)) # 100 = tkpunish event, 0 = punish else: bf2.gameLogic.sendClientCommand(-1, 100, (1, victim.index, attacker.index)) # 100 = tkpunish event, 1 = forgive else: newList += [tk] attacker.tkData.pending = newList if len(attacker.tkData.pending) == 0: del hasPendingTks[attacker] checkPunishLimit(attacker)
def round_end(self, hooker): for player in bf2.playerManager.getPlayers(): if self.get_name(player) not in self.playtime: self.playtime[self.get_name(player)] = (host.timer_getWallTime() - player.betaStats_connectTime) else: self.playtime[self.get_name(player)] = self.playtime[self.get_name(player)] + (host.timer_getWallTime() - player.betaStats_connectTime) if host.timer_getWallTime() - self.round_start_time > 0: self.write_data() # self.send_data() # while True: # out = self.interval() # if out: break # time.sleep(0.5) else: print 'betaStats: Round too short, will not send data to backend'
def invoke(): # Added by Chump - for bf2statistics stats #host.pers_gamespyStatsNewGame() snapshot_start = host.timer_getWallTime() if g_debug: print "Gathering SNAPSHOT Data" snapShot = getSnapShot() # Send snapshot to Backend Server print "Sending SNAPSHOT to backend: %s" % str(http_backend_addr) SNAP_SEND = 0 # ------------------------------------------------------------------- # Attempt to send snapshot # ------------------------------------------------------------------- try: backend_response = http_postSnapshot( http_backend_addr, http_backend_port, http_backend_asp, snapShot ) SNAP_SEND = 1 except Exception, e: SNAP_SEND = 0 print "An error occurred while sending SNAPSHOT to backend: %s" % str(e)
def onGameStatusChanged_mapchanal(status): global g_curRound,g_chThisRound,g_ChangingMap global g_lastMapId,g_lastCPNum,g_lastGameMode global g_roundStartTime Debug('onGameStatusChanged_mapchanal begins') if status == bf2.GameStatus.Playing: g_roundStartTime = host.timer_getWallTime() Debug("Remembering start of round time: %s" % str(g_roundStartTime)) g_chThisRound=False g_ChangingMap=False cmip=bf2.gameLogic.getMapName() ccpn=len(bf2.objectManager.getObjectsOfType('dice.hfe.world.ObjectTemplate.ControlPoint')) cgm=bf2.serverSettings.getGameMode() if cmip!=g_lastMapId or cgm!=g_lastGameMode: #ccpn!=g_lastCPNum or Debug('Reseting round counter due to maps description mismatch') g_curRound=0 g_lastMapId=cmip g_lastCPNum=ccpn g_lastGameMode=cgm if status == bf2.GameStatus.EndGame: UpdateRoundCounter() Debug('onGameStatusChanged_mapchanal ends')
def invoke(): # Added by Chump - for bf2statistics stats #host.pers_gamespyStatsNewGame() snapshot_start = host.timer_getWallTime() if g_debug: print "Gathering SNAPSHOT Data" snapShot = getSnapShot() # Send snapshot to Backend Server print "Sending SNAPSHOT to backend: %s" % str(http_backend_addr) SNAP_SEND = 0 # ------------------------------------------------------------------- # Attempt to send snapshot # ------------------------------------------------------------------- try: backend_response = http_postSnapshot(http_backend_addr, http_backend_port, http_backend_asp, snapShot) SNAP_SEND = 1 except Exception, e: SNAP_SEND = 0 print "An error occurred while sending SNAPSHOT to backend: %s" % str( e)
def runCmd( self, playerid, cmd, args ): """Runs an admin command.""" ctx = self.mm.getRconContext( playerid ) if not ctx.authedLevel: # Automatically log the player in ctx.autoLogin = "******" % ( playerid, int( host.timer_getWallTime() ) ) self.mm.runRconCommand( playerid, "login %s" % ctx.autoLogin ) ctx.autoLogin = "" # Prevent future logins logout = True else: logout = False if -1 != cmd.find( '%arg' ): # Have replacement params so iterate through replacing args_list = mm_utils.largs( args, None, 0, '', True ) for i in range( len( args_list ) ): arg_name = ( "%%arg%s%%" % ( i + 1 ) ); cmd = cmd.replace( arg_name, args_list[i] ) args = "" ret = self.mm.runRconCommand( playerid, "%s %s" % ( cmd, args ) ) # Automatically log the player in if logout: self.mm.runRconCommand( playerid, "logout" ) return ret
def __init__(self, targetFunc, delta, alwaysTrigger, data=None): self.targetFunc = targetFunc self.data = data self.time = host.timer_getWallTime() + delta self.interval = 0.0 self.alwaysTrigger = alwaysTrigger host.timer_created(self)
def onUpdate(data): if not checkEnable(): return global hasPendingTks currentTime = host.timer_getWallTime() newPending = {} for attacker in hasPendingTks.iterkeys(): newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # check if there is a pending TK with time expired if tkDate + TK_PUNISH_TIME < currentTime: if bf2.serverSettings.getTKPunishByDefault(): attacker.tkData.punished += 1 checkPunishLimit(attacker) # remove player from global list, if it was the last tk if len(attacker.tkData.pending) == 1: pass else: newPending[attacker] = 1 else: newList += [tk] newPending[attacker] = 1 attacker.tkData.pending = newList hasPendingTks = newPending
def onPlayerKilled(self, victim, attacker, weapon, assists, object): """Check to team kills.""" if 1 != self.__state: return 0 if not self.checkEnable(): return if not victim or not attacker or victim == attacker or victim.getTeam() != attacker.getTeam(): return # verify that TK was really given p = attacker try: if p: cdkeyhash = mm_utils.get_cd_key_hash(p) if cdkeyhash != None: cdkeyhash = str(cdkeyhash) else: cdkeyhash = "invalid cdkeyhash" profileid = str(p.getProfileId()) playername = str(p.getName()) if playername.find(" ") != 0: playername = str(playername.split()[1]) else: playername = str(playername.split()[0]) if mm_admin_settings.adm_adminHashes.has_key(cdkeyhash) or mm_admin_settings.adm_adminHashes.has_key(profileid) or mm_admin_settings.adm_adminHashes.has_key(playername): return except: self.mm.info("Exception in onPlayerKilled mm_tk_punish") # no teamkills from wrecks if object != None and object.getIsWreck(): return # no teamkills from artillery if weapon: attackerVehicle = bf2.objectManager.getRootParent(weapon) if attackerVehicle.isPlayerControlObject and attackerVehicle.getIsRemoteControlled(): return if weapon == None and object != None: victimVehicle = victim.getVehicle() victimRootVehicle = bf2.objectManager.getRootParent(victimVehicle) victimVehicleType = bf2.stats.constants.getVehicleType(victimRootVehicle.templateName) attackerVehicle = attacker.getVehicle() attackerRootVehicle = bf2.objectManager.getRootParent(attackerVehicle) attackerVehicleType = bf2.stats.constants.getVehicleType(attackerRootVehicle.templateName) #No tk on roadkill from airplane and helo if attackerVehicleType == VEHICLE_TYPE_AVIATOR and victimVehicleType == VEHICLE_TYPE_SOLDIER: return # ok, we have a teamkill currentTime = host.timer_getWallTime() attacker.tkData.pending += [(currentTime, victim)] self.hasPendingTks[attacker] = 1 victim.tkData.lastTKedBy = attacker # can only punish / forgive the last TK'er bf2.gameLogic.sendClientCommand(victim.index, TK_PUNISH_COMMANDID, (2, victim.index, attacker.index, self.__config['punishTime']))
def setStartTime(): global g_startTime try: g_startTime = host.timer_getWallTime() debug("setStartTime(): successfully set start time at " + str(g_startTime), "time") except: debug("setStartTime(): failed to reset start time", "time")
def onUpdate(self, data): """Process updates.""" if not self.checkEnable(): return currentTime = host.timer_getWallTime() newPending = {} for attacker in self.hasPendingTks.iterkeys(): newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # check if there is a pending TK with time expired if tkDate + self.__config['punishTime'] < currentTime: if bf2.serverSettings.getTKPunishByDefault(): attacker.tkData.punished += 1 self.checkPunishLimit(attacker) tkVictim.tkData.timesPunished += 1 if self.__config['announcePunishments']: try: msg = self.__config['punishMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven) mm_utils.msg_server(msg) self.mm.info(msg) except Exception, details: self.mm.error("Error announcing Punish (%s)" % details) else: tkVictim.tkData.timesForgiven += 1 if 2 == self.__config['announcePunishments']: try: msg = self.__config['forgiveMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven) mm_utils.msg_server(msg) self.mm.info(msg) except Exception, details: self.mm.error("Error announcing forgive (%s)" % details) # remove player from global list, if it was the last tk if len(attacker.tkData.pending) == 1: pass else: newPending[attacker] = 1 else: newList += [tk] newPending[attacker] = 1
def setStartTime(): global G_TIME_START try: G_TIME_START = host.timer_getWallTime() debugEcho('setStartTime(): successfully set start time at ' + str(G_TIME_START)) except: debugEcho('setStartTime(): failed to reset start time')
def debugFile(msg): try: logFile = open(fileName, "a") logTime = str(round((host.timer_getWallTime() - g_startTime), 5)) logFile.write("t: " + logTime + " " + str(msg) + "\n") logFile.close() except: pass
def onChatMessage( self, playerid, text, channel, flags ): """Check for ban / kick words.""" if 1 != self.__state: return 0 try: if playerid >= 0: player = bf2.playerManager.getPlayerByIndex( playerid ) if player: # Chat spam checks are done regardless of enableChatChecks flag kicker_info = self.playerKickerInfo( player ) now = host.timer_getWallTime() kicker_info.chatSpamCheck.append( now ) expire = now - self.__config['chatSpamPeriod'] kicker_info.chatSpamCheck = filter( lambda time: time > expire, kicker_info.chatSpamCheck ) if self.__config['chatSpamLimit'] <= len( kicker_info.chatSpamCheck ): # Player is chat spamming return self.mm.banManager().banPlayer( player, self.__config['chatSpamBanReason'], self.__config['chatSpamBanPeriod'], self.__config['kickType'], self.__config['banType'], 'ModManager Kicker', self.__config['kickDelay'] ) if self.__config['enableChatChecks']: self.mm.debug( 5, "K-CC: %s" % player.getName() ) # we have a real player i.e. not an admin isban = self.__banWords.has_key iskick = self.__kickWords.has_key words = mm_utils.MsgChannels.named[channel].stripPrefix( text ).lower().split() # first use a hash lookup for speed for word in words: if isban( word ): # Player used a ban word tell them and then ban them return self.__wordWarnBanPlayer( player, word ) elif iskick( word ): # Player used a kick word warn them if required # if warn limit has been reached kick them return self.__wordWarnKickPlayer( player, word ) # no literal words used, check patterns for ban in self.__banPatterns: ( regexp, idx ) = self.__banPatterns[ban] for word in words: if regexp.match( word ): # Player used a ban word tell them and then ban them # N.B. Add to the hash search to speed up future matches self.__banWords[word] = len( self.__banWords ) return self.__wordWarnBanPlayer( player, word ) for kick in self.__kickPatterns: ( regexp, idx ) = self.__kickPatterns[kick] for word in words: if regexp.match( word ): # Player used a ban word tell them and then ban them # N.B. Add to the hash search to speed up future matches self.__kickWords[word] = len( self.__kickWords ) return self.__wordWarnKickPlayer( player, word ) except: self.mm.error( "Ooops", True )
def executePunishAction(self, victim, punish): """Punish or forgive a player.""" if not self.checkEnable() or not victim or not victim.isValid(): return attacker = victim.tkData.lastTKedBy if attacker == None or not attacker.isValid(): return currentTime = host.timer_getWallTime() newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # if the attacker had a pending tk, and time has not run out if tkVictim == victim and tkDate + self.__config[ 'punishTime'] > currentTime: if punish: attacker.tkData.punished += 1 bf2.gameLogic.sendClientCommand( -1, TK_PUNISH_COMMANDID, (0, victim.index, attacker.index)) # 100 = tkpunish event, 0 = punish tkVictim.tkData.timesPunished += 1 if self.__config['announcePunishments']: try: msg = self.__config['punishMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven) mm_utils.msg_server(msg) self.mm.info(msg) except Exception, details: self.mm.error("Error announcing forgive (%s)" % details) else: bf2.gameLogic.sendClientCommand( -1, TK_PUNISH_COMMANDID, (1, victim.index, attacker.index)) # 100 = tkpunish event, 1 = forgive tkVictim.tkData.timesForgiven += 1 if 2 == self.__config['announcePunishments']: try: msg = self.__config['forgiveMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven) mm_utils.msg_server(msg) self.mm.info(msg) except Exception, details: self.mm.error("Error announcing forgive (%s)" % details)
def setStartTime(): global G_TIME_START try: G_TIME_START = host.timer_getWallTime() debugEcho( 'setStartTime(): successfully set start time at ' + str(G_TIME_START)) except: debugEcho('setStartTime(): failed to reset start time')
def onUpdate(data=''): global G_UPDATE_LAST wall_time_now = host.timer_getWallTime() delta_time = wall_time_now - G_UPDATE_LAST G_UPDATE_LAST = host.timer_getWallTime() D.debugMessage('Time: %s+%s' % (wall_time_now, delta_time)) if G_TRACKED_OBJECT is not None: position = G_TRACKED_OBJECT.getPosition() rotation = G_TRACKED_OBJECT.getRotation() message = { 'position': position, 'rotation': rotation, 'time_wall': wall_time_now, 'time_delta': delta_time, 'time_epoch': time.time() } D.debugMessage('Position: %s\nRotation: %s\n' % (position, rotation)) D.updateMessageUDP(message)
def round_start(self, hooker): global g_daemon if bf2.gameLogic.isAIGame(): return if g_daemon is None: g_daemon = limitKitDaemon() g_daemon.hooker = hooker g_daemon.add(self.info1) g_daemon.add(self.info2) global round_start_time round_start_time = host.timer_getWallTime()
def onUpdate(data=''): global G_UPDATE_LAST time_wall_now = host.timer_getWallTime() time_delta = time_wall_now - G_UPDATE_LAST time_epoch = time.time() G_UPDATE_LAST = host.timer_getWallTime() #D.debugMessage('Time: %s+%s@%s' % (time_wall_now, time_delta, time_epoch)) if G_TRACKED_OBJECT is not None and G_TRACKED_OBJECT.isValid(): position = G_TRACKED_OBJECT.getPosition() rotation = G_TRACKED_OBJECT.getRotation() message = { 'position': position, 'rotation': rotation, 'time_wall': time_wall_now, 'time_delta': time_delta, 'time_epoch': time_epoch } #D.debugMessage('Position: %s\nRotation: %s\n' % (position, rotation)) D.updateMessageUDP(message)
def __init__(self): self.highPing = [] self.lowPing = [] self.posHistory = [] self.kickWordWarnings = 0 self.banWordWarnings = 0 self.idleTime = 0 self.lastPos = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) self.lastScore = 0 self.lastCheck = self.connectedAt = host.timer_getWallTime() self.lastBulletsFired = 0
def __init__( self ): self.highPing = [] self.lowPing = [] self.posHistory = [] self.kickWordWarnings = 0 self.banWordWarnings = 0 self.idleTime = 0 self.lastPos = ( 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ) self.lastScore = 0 self.lastCheck = self.connectedAt = host.timer_getWallTime() self.lastBulletsFired = 0 self.chatSpamCheck = []
def checkGrindBlock(player, object): if object.isPlayerControlObject: defPlayers = object.getOccupyingPlayers() if len(defPlayers) > 0: defPlayer = defPlayers[0] if not hasattr(player, "lastReplenishPointMap"): player.lastReplenishPointMap = {} else: if defPlayer.index in player.lastReplenishPointMap: if ( player.lastReplenishPointMap[defPlayer.index] + REPLENISH_POINT_MIN_INTERVAL > host.timer_getWallTime() ): return True player.lastReplenishPointMap[defPlayer.index] = host.timer_getWallTime() return False
def round_start(self, hooker): try: host.registerHandler('PlayerDeath', self.onPlayerDeath) host.registerHandler('PlayerSpawn', self.onPlayerSpawn) host.registerHandler('PlayerConnect', self.onPlayerConnect) host.registerHandler('PlayerDisconnect', self.onPlayerDisconnect) if DEBUG: print 'Spawnwave hooked' self.round_start_time = host.timer_getWallTime() if DEBUG: print 'Spawnwave round_start time is', self.round_start_time except Exception, e: print 'round_start exception', e
def round_start(self, hooker): print 'betaStats init\'d' # self.a = asyncio.asyncio() # self.a.backend_ip = HOST # self.a.backend_port = PORT hooker.register('PlayerConnect', self.onPlayerConnect) hooker.register('PlayerDisconnect', self.onPlayerDisconnect) self.playtime = {} self.start_players() self.round_start_time = host.timer_getWallTime()
def vehicleExited(self, player, vehicle): if vehicle.templateName.lower() in vehicleMetadata.parachutes: end = host.timer_getWallTime() diff = end - player.parachuteStart if DEBUG: print player.getName(), 'spent', diff, 'seconds in chute' if diff < 3.0: # near-death state player.getDefaultVehicle().setDamage(0.1) elif diff < 6.0: # bleed state player.getDefaultVehicle().setDamage(24)
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 invoke(): # Added by Chump - for bf2statistics stats #host.pers_gamespyStatsNewGame() snapshot_start = host.timer_getWallTime() if g_debug: print "snapshot.py[64]: Gathering SNAPSHOT Data" snapShot = getSnapShot() # Print in log print snapShot # Send snapshot to Backend Server print "snapshot.py: Sending SNAPSHOT to backend: %s" % str(http_backend_addr) try: backend_response = http_postSnapshot( http_backend_addr, http_backend_port, http_backend_asp, snapShot ) except Exception, e: print "snapshot.py: An error occurred while sending SNAPSHOT to backend: %s" % str(e)
def onUpdate( self, data ): """Process updates.""" if not self.checkEnable(): return currentTime = host.timer_getWallTime() newPending = {} for attacker in self.hasPendingTks.iterkeys(): newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # check if there is a pending TK with time expired if tkDate + self.__config['punishTime'] < currentTime: if bf2.serverSettings.getTKPunishByDefault(): attacker.tkData.punished += 1 self.checkPunishLimit(attacker) tkVictim.tkData.timesPunished += 1 if self.__config['announcePunishments']: try: msg = self.__config['punishMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven ) mm_utils.msg_server( msg ) self.mm.info( msg ) except Exception, details: self.mm.error( "Error announcing Punish (%s)" % details ) else: tkVictim.tkData.timesForgiven += 1 if 2 == self.__config['announcePunishments']: try: msg = self.__config['forgiveMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven ) mm_utils.msg_server( msg ) self.mm.info( msg ) except Exception, details: self.mm.error( "Error announcing forgive (%s)" % details ) # remove player from global list, if it was the last tk if len(attacker.tkData.pending) == 1: pass else: newPending[attacker] = 1 else: newList += [tk] newPending[attacker] = 1
def onPlayerKilled(victim, attacker, weapon, assists, object): # decho( "%s : weapon" % weapon, 5) # decho( "%s : object" % object, 5) if not checkEnable(): return if not victim or not attacker or victim == attacker or victim.getTeam( ) != attacker.getTeam(): return # no teamkills from wrecks if object != None and object.getIsWreck(): return # no teamkills from artillery if weapon: attackerVehicle = bf2.objectManager.getRootParent(weapon) if attackerVehicle.isPlayerControlObject and attackerVehicle.getIsRemoteControlled( ): return #HF Start #Part 1 if weapon == None and object != None: victimVehicle = victim.getVehicle() victimRootVehicle = bf2.objectManager.getRootParent(victimVehicle) victimVehicleType = getVehicleType(victimRootVehicle.templateName) attackerVehicle = attacker.getVehicle() attackerRootVehicle = bf2.objectManager.getRootParent( attackerVehicle) attackerVehicleType = getVehicleType( attackerRootVehicle.templateName) #No tk on roadkill from airplane and helo if attackerVehicleType == VEHICLE_TYPE_AVIATOR and victimVehicleType == VEHICLE_TYPE_SOLDIER: return #HF Stop # ok, we have a teamkill currentTime = host.timer_getWallTime() attacker.tkData.pending += [(currentTime, victim)] hasPendingTks[attacker] = 1 victim.tkData.lastTKedBy = attacker # can only punish / forgive the last TK'er bf2.gameLogic.sendClientCommand( victim.index, 100, (2, victim.index, attacker.index, TK_PUNISH_TIME))
def onPlayerDeath(self, player, soldier): try: if not player.isAlive() and self.system_active(): # A bit paranoid, but its better to be sure. player.timer = None player.timeOfDeath = host.timer_getWallTime() if DEBUG: print 'Time of death:', player.timeOfDeath player.timeToSpawn = game.utilities.getSpawnTime(rstime = self.round_start_time, dt = player.timeOfDeath) if player.timeToSpawn: if player.getTimeToSpawn() < MAX_TTS: # Make sure we don't override HUGE_TTS when unavailable kit is selceted. if player.timeToSpawn < MIN_TIME: player.timeToSpawn = player.timeToSpawn + int(game.utilities.rconExec('sv.spawntime')) player.setTimeToSpawn(player.timeToSpawn) player.timer = bf2.Timer(self.interval, player.timeToSpawn + WAVE_TIME, 1, player) player.timer.setRecurring(int(game.utilities.rconExec('sv.spawntime'))) except Exception, e: print 'onPlayerDeath exception', e
def ReachedTimeLimit(): global g_roundStartTime tlimit = float(host.rcon_invoke('sv.timeLimit')) if tlimit == 0: Debug("No time limit. Returning False") return False tel = host.timer_getWallTime() - g_roundStartTime - float(host.rcon_invoke('sv.startDelay')) res = tel >= tlimit Debug('ReachedTimeLimit> Time elapsed %s, time limit %s. Result %s' % (tel, tlimit, res)) return res
def roundTime( self ): """Return how long a round has been running for. Takes into account start delay and any pauses. """ now = int( host.timer_getWallTime() ) if bf2.GameStatus.Paused == self.currentGameStatus: cur_pause = now - self.__pauseStart round_time = now - self.startTimeWall - self.__matchTimeLost - cur_pause else: round_time = now - self.startTimeWall - self.__matchTimeLost if 0 > round_time: return 0 else: return round_time
def onTimer(data): global g_playing, g_ml_game_start_time try: if state != RUN: return if not g_playing or g_ml_game_start_time == None or g_newmlcon_delay < 0: return tel = host.timer_getWallTime() - g_ml_game_start_time ttel = g_newmlcon_delay + float(host.rcon_invoke('sv.startDelay')) Debug('OnTimer. Time elapsed %s/%s' % (tel, ttel)) if tel >= ttel: open(GetPathToMaplistCon(), 'wb').write('mapList.append %s' % GetServerNextMap()) g_ml_game_start_time = None except: ExceptionOutput()
def onPlayerKilled( self, victim, attacker, weapon, assists, object ): """Check to team kills.""" if 1 != self.__state: return 0 if not self.checkEnable(): return if not victim or not attacker or victim == attacker or victim.getTeam() != attacker.getTeam(): return # verify that TK was really given # no teamkills from wrecks if object != None and object.getIsWreck(): return # no teamkills from artillery if weapon: attackerVehicle = bf2.objectManager.getRootParent(weapon) if attackerVehicle.isPlayerControlObject and attackerVehicle.getIsRemoteControlled(): return if weapon == None and object != None: victimVehicle = victim.getVehicle() victimRootVehicle = bf2.objectManager.getRootParent(victimVehicle) victimVehicleType = bf2.stats.constants.getVehicleType(victimRootVehicle.templateName) attackerVehicle = attacker.getVehicle() attackerRootVehicle = bf2.objectManager.getRootParent(attackerVehicle) attackerVehicleType = bf2.stats.constants.getVehicleType(attackerRootVehicle.templateName) #No tk on roadkill from airplane and helo if attackerVehicleType == VEHICLE_TYPE_AVIATOR and victimVehicleType == VEHICLE_TYPE_SOLDIER: return # ok, we have a teamkill currentTime = host.timer_getWallTime() attacker.tkData.pending += [(currentTime, victim)] self.hasPendingTks[attacker] = 1 victim.tkData.lastTKedBy = attacker # can only punish / forgive the last TK'er bf2.gameLogic.sendClientCommand(victim.index, TK_PUNISH_COMMANDID, (2, victim.index, attacker.index, self.__config['punishTime']))
def log(log_type, *args): # Validate the given parameters assert log_type and len(log_type) == 2, 'Invalid log type: %s' % `log_type` # Write the log entry time stamp log_file.write(str(int(host.timer_getWallTime())).zfill(5)) log_file.write(';') # Write the required type of log log_file.write(log_type) # Write any optional log values with delimiters if args: for arg in args: log_file.write(';') log_file.write(str(arg)) # Make sure the log entry is output to disk immediately log_file.write('\n') log_file.flush()
def onPlayerKilled(victim, attacker, weapon, assists, object): # decho( "%s : weapon" % weapon, 5) # decho( "%s : object" % object, 5) if not checkEnable(): return if not victim or not attacker or victim == attacker or victim.getTeam() != attacker.getTeam(): return # no teamkills from wrecks if object != None and object.getIsWreck(): return # no teamkills from artillery if weapon: attackerVehicle = bf2.objectManager.getRootParent(weapon) if attackerVehicle.isPlayerControlObject and attackerVehicle.getIsRemoteControlled(): return #HF Start #Part 1 if weapon == None and object != None: victimVehicle = victim.getVehicle() victimRootVehicle = bf2.objectManager.getRootParent(victimVehicle) victimVehicleType = getVehicleType(victimRootVehicle.templateName) attackerVehicle = attacker.getVehicle() attackerRootVehicle = bf2.objectManager.getRootParent(attackerVehicle) attackerVehicleType = getVehicleType(attackerRootVehicle.templateName) #No tk on roadkill from airplane and helo if attackerVehicleType == VEHICLE_TYPE_AVIATOR and victimVehicleType == VEHICLE_TYPE_SOLDIER: return #HF Stop # ok, we have a teamkill currentTime = host.timer_getWallTime() attacker.tkData.pending += [(currentTime, victim)] hasPendingTks[attacker] = 1 victim.tkData.lastTKedBy = attacker # can only punish / forgive the last TK'er bf2.gameLogic.sendClientCommand(victim.index, 100, (2, victim.index, attacker.index, TK_PUNISH_TIME))
def executePunishAction( self, victim, punish ): """Punish or forgive a player.""" if not self.checkEnable() or not victim or not victim.isValid(): return attacker = victim.tkData.lastTKedBy if attacker == None or not attacker.isValid(): return currentTime = host.timer_getWallTime() newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # if the attacker had a pending tk, and time has not run out if tkVictim == victim and tkDate + self.__config['punishTime'] > currentTime: if punish: attacker.tkData.punished += 1 bf2.gameLogic.sendClientCommand(-1, TK_PUNISH_COMMANDID, (0, victim.index, attacker.index)) # 100 = tkpunish event, 0 = punish tkVictim.tkData.timesPunished += 1 if self.__config['announcePunishments']: try: msg = self.__config['punishMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven ) mm_utils.msg_server( msg ) self.mm.info( msg ) except Exception, details: self.mm.error( "Error announcing forgive (%s)" % details ) else: bf2.gameLogic.sendClientCommand(-1, TK_PUNISH_COMMANDID, (1, victim.index, attacker.index)) # 100 = tkpunish event, 1 = forgive tkVictim.tkData.timesForgiven += 1 if 2 == self.__config['announcePunishments']: try: msg = self.__config['forgiveMessage'] % ( tkVictim.getName(), attacker.getName(), tkVictim.getName(), tkVictim.tkData.timesPunished, tkVictim.tkData.timesForgiven ) mm_utils.msg_server( msg ) self.mm.info( msg ) except Exception, details: self.mm.error( "Error announcing forgive (%s)" % details )
def log(log_type, *args): # Validate the given parameters assert log_type and len( log_type) == 2, 'Invalid log type: %s' % ` log_type ` # Write the log entry time stamp log_file.write(str(int(host.timer_getWallTime())).zfill(5)) log_file.write(';') # Write the required type of log log_file.write(log_type) # Write any optional log values with delimiters if args: for arg in args: log_file.write(';') log_file.write(str(arg)) # Make sure the log entry is output to disk immediately log_file.write('\n') log_file.flush()
def executePunishAction(victim, punish): if not checkEnable() or not victim or not victim.isValid(): return attacker = victim.tkData.lastTKedBy if attacker == None or not attacker.isValid(): return global hasPendingTks currentTime = host.timer_getWallTime() newList = [] for tk in attacker.tkData.pending: tkDate = tk[0] tkVictim = tk[1] # if the attacker had a pending tk, and time has not run out if tkVictim == victim and tkDate + TK_PUNISH_TIME > currentTime: if punish: attacker.tkData.punished += 1 bf2.gameLogic.sendClientCommand( -1, 100, (0, victim.index, attacker.index)) # 100 = tkpunish event, 0 = punish else: bf2.gameLogic.sendClientCommand( -1, 100, (1, victim.index, attacker.index)) # 100 = tkpunish event, 1 = forgive else: newList += [tk] attacker.tkData.pending = newList if len(attacker.tkData.pending) == 0: del hasPendingTks[attacker] checkPunishLimit(attacker)
def invoke(): # Added by Chump - for bf2statistics stats #host.pers_gamespyStatsNewGame() snapshot_start = host.timer_getWallTime() if g_debug: print "snapshot.py[64]: Gathering SNAPSHOT Data" snapShot = getSnapShot() # Print in log print snapShot # Send snapshot to Backend Server print "snapshot.py: Sending SNAPSHOT to backend: %s" % str(http_backend_addr) try: backend_response = http_postSnapshot( http_backend_addr, http_backend_port, http_backend_asp, snapShot ) except Exception, e: print "snapshot.py: An error occurred while sending SNAPSHOT to backend: %s" % str(e) print "SNAPSHOT Processing Time: %d" % (host.timer_getWallTime() - snapshot_start) ## ------------------------------------------------------------------------------ ## omero 2006-03-31 ## ------------------------------------------------------------------------------ ## always do the following at the end... repackStatsVectors() # def repackStatsVectors(): # remove disconnected players cleanoutStatsVector() cleanoutMedalsVector() # repack stats and medal vector so there are no holes. gamespy doesnt like holes. medalMap = getMedalMap() statsMap = getStatsMap() playerOrderIt = getPlayerConnectionOrderIterator()
def time_now(): timenow = round((host.timer_getWallTime() - G_TIME_START), 5) return timenow
def onCPTrigger(triggerId, cp, vehicle, enter, userData): if not cp.isValid(): return if vehicle and vehicle.getParent(): return # can this cp be captured at all? if cp.cp_getParam("unableToChangeTeam") != 0: return playersInVehicle = None if vehicle: playersInVehicle = vehicle.getOccupyingPlayers() if enter: for p in playersInVehicle: cp = getOccupyingCP(p) if cp != None: if not p.getIsInsideCP(): if g_debug: print "Resetting enterPctAt for player ", p.getName() p.enterCpAt = host.timer_getWallTime() if vehicle: for p in playersInVehicle: # only count first player in a vehicle if p == playersInVehicle[0]: if g_debug: print p.index, " is in radius. v=", vehicle.templateName p.setIsInsideCP(enter) else: p.setIsInsideCP(0) if enter == 1: bf2.gameLogic.sendHudEvent( p, 66, 49 ) # 66 = HEEnableHelpMessage, 49 = VHMExitToCaptureFlag; # count people in radius team1Occupants = 0 team2Occupants = 0 pcos = bf2.triggerManager.getObjects(cp.triggerId) for o in pcos: if not o: continue # you can get None in the result tuple when the host can't figure out what object left the trigger if o.getParent(): continue # getOccupyingPlayers returns all players downwards in the hierarchy, so dont count them twice occupyingPlayers = o.getOccupyingPlayers() for p in occupyingPlayers: # only count first player in a vehicle if p != occupyingPlayers[0]: continue if p.isAlive() and not p.isManDown(): if not p.killed: if p.getTeam() == 1: team1Occupants += 1 elif p.getTeam() == 2: team2Occupants += 1 # determine who is taking control team1OverWeight = team1Occupants - team2Occupants attackOverWeight = 0 if team1OverWeight > 0: attackingTeam = 1 elif team1OverWeight < 0: attackingTeam = 2 else: attackingTeam = 0 if team1Occupants == 0 and team2Occupants == 0: # nobody here, slowly go back to owning team if cp.cp_getParam("team") == 0: attackOverWeight = -0.5 else: attackOverWeight = 0.5 timeToChangeControl = cp.cp_getParam("timeToLoseControl") else: # raise flag if already ours, or at bottom and neutral. Otherwise lower first. if cp.cp_getParam("flag") == attackingTeam or ( cp.flagPosition == Bottom and cp.cp_getParam("team") == 0): # our flag, raise attackOverWeight = abs(team1OverWeight) timeToChangeControl = cp.cp_getParam("timeToGetControl") else: # other team raised flag, lower first attackOverWeight = -abs(team1OverWeight) timeToChangeControl = cp.cp_getParam("timeToLoseControl") if (cp.cp_getParam("onlyTakeableByTeam") != 0 and cp.cp_getParam("onlyTakeableByTeam") != attackingTeam): return # flag can only be changed when at bottom if cp.flagPosition == Bottom: cp.cp_setParam("flag", attackingTeam) # calculate flag raising/lowering speed if timeToChangeControl > 0: takeOverChangePerSecond = 1.0 * attackOverWeight / timeToChangeControl else: takeOverChangePerSecond = 0.0 if (cp.flagPosition == Top and takeOverChangePerSecond > 0) or ( cp.flagPosition == Bottom and takeOverChangePerSecond < 0): takeOverChangePerSecond = 0.0 if abs(takeOverChangePerSecond) > 0: cp.flagPosition = Middle cp.cp_setParam("takeOverChangePerSecond", takeOverChangePerSecond)
def wallString(): return str(int(host.timer_getWallTime()) - startTime)
def checkPlayers(self, params=None): """Check players for ping violations and update advanced player info""" try: self.mm.debug(2, "K-Check") if not self.mm.gamePlaying: # not playing atm ignore #self.mm.debug( 2, "K-NP" ) return # We are playing ping_limit = self.__config['pingLimit'] idle_limit = self.__config['idleLimit'] max_ping = self.__config['maxPing'] min_ping = self.__config['minPing'] neg_score = self.__config['negScoreKick'] now = host.timer_getWallTime() expire = now - self.__config['samplePeriod'] pos_delay = now - self.__config['positionDelay'] team1_cp = 0 team2_cp = 0 # ignore idle checks or not? if not self.mm.roundStarted and self.__config[ 'idleIgnoreNotStarted']: ignoreIdle = True else: ignoreIdle = False #self.mm.debug( 2, "K-II: %s" % ignoreIdle ) # find out how many control points each team has for cp in bf2.objectManager.getObjectsOfType( 'dice.hfe.world.ObjectTemplate.ControlPoint'): if 1 == cp.cp_getParam("team"): team1_cp += 1 else: team2_cp += 1 for player in bf2.playerManager.getPlayers(): try: if not player.isConnected(): # Players still connecting ignore continue kicker_info = self.playerKickerInfo(player) # Expire old info kicker_info.highPing = filter(lambda time: time > expire, kicker_info.highPing) kicker_info.lowPing = filter(lambda time: time > expire, kicker_info.lowPing) kicker_info.posHistory = filter( lambda details: details['time'] > expire, kicker_info.posHistory) # check ping ping = player.getPing() if max_ping and ping > max_ping: #self.mm.debug( 4, "K-HI: player %s %d > %d" % ( player.getName(), ping, max_ping ) ) kicker_info.highPing.append(now) # Now check limits if ping_limit <= len(kicker_info.highPing): self.mm.debug( 4, "K-2HI: player %s" % player.getName()) return self.__kickPlayer(player, KickReason.highPing) elif ping < min_ping: #self.mm.debug( 4, "K-LOW: player %s %d < %d" % ( player.getName(), ping, min_ping ) ) kicker_info.lowPing.append(now) # Now check limits if ping_limit <= len(kicker_info.lowPing): self.mm.debug( 4, "K-2LOW: player %s" % player.getName()) return self.__kickPlayer(player, KickReason.lowPing) # Check score cscore = player.score.score if neg_score and neg_score >= cscore: #self.mm.debug( 4, "K-NEG: player %s" % player.getName() ) return self.__kickPlayer(player, KickReason.negScore) # check idle total_bullets_fired = 0 veh = player.getVehicle() (cx, cy, cz) = veh.getPosition() (ca, cp, cr) = veh.getRotation() if ignoreIdle: # Game is not really playing and idleIgnoreNotStarted is set kicker_info.idleTime = 0 elif kicker_info.lastScore == cscore: # score is still the same #self.mm.debug( 4, "K-NS: player %s %d == %d" % ( player.getName(), kicker_info.lastScore, cscore ) ) playerCanMove = True if not player.isAlive(): # Player is dead can the spawn? if 1 == player.getTeam(): if 0 == team1_cp: playerCanMove = False else: if 0 == team2_cp: playerCanMove = False if playerCanMove: # they can move, check player position (lx, ly, lz, la, lp, lr) = kicker_info.lastPos #self.mm.debug( 4, "K-CM: player %s [%f,%f,%f->%f,%f,%f] => [%f,%f,%f->%f,%f,%f]" % ( player.getName(), lx, ly, lz, la, lp, lr, cx, cy, cz, ca, cp, cr ) ) if cx == lx and cy == ly and cz == lz and ca == la and cp == lp and cr == lr: # player hasnt moved # finally check to see if they have fired bulletsFired = player.score.bulletsFired for f in bulletsFired: total_bullets_fired += f[1] if kicker_info.lastBulletsFired == total_bullets_fired: #self.mm.debug( 4, "K-IDLE: player %s (%d == %d)" % ( player.getName(), kicker_info.lastBulletsFired, total_bullets_fired ) ) kicker_info.idleTime += ( now - kicker_info.lastCheck) # Now check limits if idle_limit and idle_limit <= kicker_info.idleTime: #self.mm.debug( 4, "K-2IDLE: player %s" % player.getName() ) return self.__kickPlayer( player, KickReason.idle) else: # player fired kicker_info.idleTime = 0 else: # player moved kicker_info.idleTime = 0 else: # player cant move kicker_info.idleTime = 0 else: # player scored kicker_info.idleTime = 0 # update our last details kicker_info.lastCheck = now kicker_info.lastScore = cscore kicker_info.lastPos = (cx, cy, cz, ca, cp, cr) kicker_info.lastBulletsFired = total_bullets_fired kicker_info.posHistory.append({ 'time': now, 'pos': (cx, cy, cz), 'rot': (ca, cp, cr) }) except: try: player_name = player.getName() except: player_name = 'unknown' self.mm.error("Failed to check player '%s'" % player_name, True) except: self.mm.error("Ooops", True)
def onChatMessage(self, playerid, text, channel, flags): """Check for ban / kick words.""" if 1 != self.__state: return 0 try: if playerid >= 0: player = bf2.playerManager.getPlayerByIndex(playerid) if player: # Chat spam checks are done regardless of enableChatChecks flag kicker_info = self.playerKickerInfo(player) now = host.timer_getWallTime() kicker_info.chatSpamCheck.append(now) expire = now - self.__config['chatSpamPeriod'] kicker_info.chatSpamCheck = filter( lambda time: time > expire, kicker_info.chatSpamCheck) if self.__config['chatSpamLimit'] <= len( kicker_info.chatSpamCheck): # Player is chat spamming return self.mm.banManager().banPlayer( player, self.__config['chatSpamBanReason'], self.__config['chatSpamBanPeriod'], self.__config['kickType'], self.__config['banType'], 'ModManager Kicker', self.__config['kickDelay']) if self.__config['enableChatChecks']: self.mm.debug(5, "K-CC: %s" % player.getName()) # we have a real player i.e. not an admin isban = self.__banWords.has_key iskick = self.__kickWords.has_key words = mm_utils.MsgChannels.named[ channel].stripPrefix(text).lower().split() # first use a hash lookup for speed for word in words: if isban(word): # Player used a ban word tell them and then ban them return self.__wordWarnBanPlayer(player, word) elif iskick(word): # Player used a kick word warn them if required # if warn limit has been reached kick them return self.__wordWarnKickPlayer(player, word) # no literal words used, check patterns for ban in self.__banPatterns: (regexp, idx) = self.__banPatterns[ban] for word in words: if regexp.match(word): # Player used a ban word tell them and then ban them # N.B. Add to the hash search to speed up future matches self.__banWords[word] = len( self.__banWords) return self.__wordWarnBanPlayer( player, word) for kick in self.__kickPatterns: (regexp, idx) = self.__kickPatterns[kick] for word in words: if regexp.match(word): # Player used a ban word tell them and then ban them # N.B. Add to the hash search to speed up future matches self.__kickWords[word] = len( self.__kickWords) return self.__wordWarnKickPlayer( player, word) except: self.mm.error("Ooops", True)
def onGameStatusChanged(status): global ml,settings_file_name, current_map_size, g_playing, maps_run_priority, g_need_choose_map, g_ml_game_start_time try: onGameStatusChanged_mapchanal(status) except: ExceptionOutput() if state != RUN: return try: Debug('onGameStatusChanged begins. Status is %s' % str(status)) set=ReadSettings(GetSetBasePath()+settings_file_name) if status == bf2.GameStatus.Playing: Debug('bf2.GameStatus.Playing') g_playing = True if CurrentRound() == 0 and len(bf2.playerManager.getPlayers()) >= int(host.rcon_invoke('sv.numPlayersNeededToStart')): g_ml_game_start_time = host.timer_getWallTime() Debug('Start playing map for real. Remembering time for maplist.con update: %s' % str(g_ml_game_start_time) ) if not g_need_choose_map and CurrentRound() > 0: Debug('Marked as done. Don\'t choosing next map and returning') Debug('onGameStatusChanged ends') return g_need_choose_map = False if current_map_size == None: Debug('Reading current level size in maplist.con') try: for raw_line in open(GetPathToMaplistCon(), 'rb'): l = raw_line.strip() if l.lower().startswith('maplist.append'): Debug('Found first map entry: %s' % l) current_map_size = str(int(l.split()[3])) except: pass ml=GetCurrentMapList(GetSetBasePath()+settings_file_name) if current_map_size != None: mn = '%s %s %s' % (bf2.serverSettings.getMapName(), bf2.serverSettings.getGameMode(), current_map_size) if mn not in maps_run_priority: if mn in ml: maps_run_priority[mn] = ml[mn][0] else: maps_run_priority[mn] = 0 MoveToEndOfMapsRun(mn) Debug('Current map is "%s"' % str(mn)) SetMapList(ml) for i in xrange(1000): # not using while true: to prevent possible infinite loop nmn=GetRandomNextMap(ml,set.rndnum) Debug('Map chosen: %s' % nmn) if nmn not in maps_run_priority: maps_run_priority[nmn] = ml[nmn][0] SaveMapsRun() if maps_run_priority[nmn] < 1: maps_run_priority[nmn] += ml[nmn][0] Debug('Map\'s priority value < 1. Increasing it (new value is %s) and moving map to the end of mapsrun. Choosing another map' % str(maps_run_priority[nmn])) MoveToEndOfMapsRun(nmn) elif LocateMapInServerMaplist(nmn) == None: Debug('Map wasn\'t found in server maplist! Maybe it\'s wrong level name "%s"?' % nmn) MoveToEndOfMapsRun(nmn) else: Debug('Setting map as next') break # sk=ml.keys() # sk.sort() # nmi=sk.index(nmn) host.rcon_invoke('admin.setnextlevel %d' % LocateMapInServerMaplist(nmn)) if status == bf2.GameStatus.EndGame: Debug('bf2.GameStatus.EndGame') g_playing = False if isGonnaChangeMap(): g_need_choose_map = True g_ml_game_start_time = None smn = GetServerNextMap() ml=GetCurrentMapList(GetSetBasePath()+settings_file_name) nmn = None smnspl = smn.split() if smn in ml: nmn = smn Debug('Level was found in current maplist') if nmn == None: pmns = [x for x in ml if x.split()[MAPNAME] == smnspl[MAPNAME] and x.split()[GAMEMODE] == smnspl[GAMEMODE]] if len(pmns) == 0: pmns = [x for x in ml if x.split()[MAPNAME] == smnspl[MAPNAME]] if len(pmns) > 0: nmn = random.choice(pmns) Debug('Level(s) with same mapname and gamemode or only mapname was found in current maplist. pnms %s' % str(pmns)) if nmn == None: Debug('No resembling level was found in current maplist. Full rechoose') nmn=GetRandomNextMap(ml,set.rndnum) Debug('Resulting mapname is %s' % nmn) SetMap(nmn) current_map_size = nmn.split()[MAPSIZE] if set.mod_maplistcon: open(GetPathToMaplistCon(), 'wb').write('mapList.append %s' % nmn) if nmn in maps_run_priority: maps_run_priority[nmn] %= 1 else: maps_run_priority[nmn] = 0 maps_run_priority[nmn] += ml[nmn][0] SaveMapsRun() Debug('Reseting priority value of map "%s". New value is %s' % (nmn, maps_run_priority[nmn])) Debug('onGameStatusChanged ends') except: ExceptionOutput()
def date(): return host.timer_getWallTime()
print "Sending SNAPSHOT to Central Backend: %s" % str( http_central_addr) #Append CDB Setting so backened knows what to do with this snapShotCDB = snapShot + '\\cdb_update\\' + http_central_enable try: backend_response = http_postSnapshot(http_central_addr, http_central_port, http_central_asp, snapShotCDB) except Exception, e: print "An error occurred while sending SNAPSHOT to Central Backend: %s" % str( e) print "SNAPSHOT Processing Time: %d" % (host.timer_getWallTime() - snapshot_start) # ------------------------------------------------------------------------------ # omero 2006-03-31 # ------------------------------------------------------------------------------ # always do the following at the end... repackStatsVectors() def repackStatsVectors(): # remove disconnected players cleanoutStatsVector() cleanoutMedalsVector()
# Send Snapshot to Central Backend Server if http_central_enable == 1 or http_central_enable == 2: print "Sending SNAPSHOT to Central Backend: %s" % str(http_central_addr) #Append CDB Setting so backened knows what to do with this snapShotCDB = snapShot + '\\cdb_update\\' + http_central_enable try: backend_response = http_postSnapshot( http_central_addr, http_central_port, http_central_asp, snapShotCDB ) except Exception, e: print "An error occurred while sending SNAPSHOT to Central Backend: %s" % str(e) print "SNAPSHOT Processing Time: %d" % (host.timer_getWallTime() - snapshot_start) # ------------------------------------------------------------------------------ # omero 2006-03-31 # ------------------------------------------------------------------------------ # always do the following at the end... repackStatsVectors() def repackStatsVectors(): # remove disconnected players cleanoutStatsVector() cleanoutMedalsVector()