Exemplo n.º 1
0
 def __init__(
         self, file,
         callbackClass):  # already assured it exists, opened for reading
     self.polygon = Polygon2D()
     for line in file.readlines()[0].split("\\"):
         if ":" in line:
             s = line.strip().split(":")
             if s[0] == "name":
                 self.name = s[1]
                 mm.info("PolygonTrigger name: %s" % s[1])
             if s[0] == "floor":
                 self.floor = int(s[1])
                 mm.info("PolygonTrigger floor: %s" % s[1])
             if s[0] == "height":
                 self.height = int(s[1])
                 mm.info("PolygonTrigger height: %s" % s[1])
             if s[0] == "team":
                 self.team = int(s[1])
                 mm.info("PolygonTrigger team: %s" % s[1])
             if s[0] == "interval":
                 self.interval = int(s[1])
                 mm.info("PolygonTrigger interval: %s" % s[1])
             if s[0] == "callback":
                 self.callback = getattr(callbackClass, s[1])
                 mm.info("PolygonTrigger callback: callbackClass.%s" % s[1])
             if s[0] == "point":
                 xy = s[1].split("/")
                 self.polygon.add(Point(float(xy[0]), float(xy[1])))
                 mm.info("PolygonTrigger point: %s,%s" %
                         (str(self.polygon._coords[-1].x),
                          str(self.polygon._coords[-1].y)))
     file.close()
     self.polygon.precalculate()
     self.timer = bf2.Timer(self.onTick, self.interval, 1, ())
     self.timer.setRecurring(self.interval)
Exemplo n.º 2
0
    def kickPlayer(self,
                   player,
                   kickReason=None,
                   kickDelay=None,
                   kickType=mm_utils.KickBanType.rcon):
        """Kick a player with a reason."""
        if self.__kickTimers.has_key(player.index):
            # Already scheduled for a kick
            self.mm.warn(
                "Kick failed ( Kick already in progress for player %d )" %
                (player.index))
            return False

        if kickType != mm_utils.KickBanType.rcon:
            self.mm.warn("Unsupported kick type '%d' (using %d instead)" %
                         (kickType, mm_utils.KickBanType.rcon))
            kickType = mm_utils.KickBanType.rcon

        try:
            player_name = player.getName()
        except RuntimeError:
            # player has already left?
            player_name = self.validatePlayerName(None)

        # Rcon kick method
        kickDelay = self.validateKickDelay(kickDelay)
        kickReason = self.validateKickReason(kickReason)
        msg = self.__config['kickMessage'] % (player_name, kickReason)
        mm_utils.msg_player(player.index, msg)
        player.mmKickReason = kickReason
        player.mmKickType = kickType
        self.__kickTimers[player.index] = bf2.Timer(self.kickPlayerNow,
                                                    kickDelay, 1, player)

        return True
Exemplo n.º 3
0
    def onKickTimer(self, data):
        self.Debug("onKickTimer")

        player = bf2.playerManager.getPlayerByIndex(self.kickList.pop(0))

        if player.getSquadId() == 0 and not player.isCommander():
            self.Info(player.getName() + " kicking..")
            self.doSendMessage("was kicked for not being in a squad", player,
                               1)
            bf2.Timer(self.doKick, self.kickDelay, 1, player)
Exemplo n.º 4
0
    def __addTimedMsg(self, start, repeat, text):
        """Create a timed message."""
        details = {'start': start, 'repeat': repeat, 'text': text}
        timer = bf2.Timer(self.announce, start, 1, details)
        if repeat:
            timer.setRecurring(repeat)
        details['timer'] = timer

        self.__timedMessages.append(details)
        return details
Exemplo n.º 5
0
def restartRound():
    global timer
    global inCounting

    if (inCounting):
        timer.destroy()
        timer = None

    inCounting = True
    sayAll("Restart round in...")
    timer = bf2.Timer(onRestart, 1, 1)
    timer.setRecurring(1)
    def checkEnable(self):
        """Check to see if team kill punish is enabled."""
        if not bf2.serverSettings.getTKPunishEnabled():
            if self.updateTimer:
                self.updateTimer.destroy()
                self.updateTimer = None
            return False
        else:
            if not self.updateTimer:
                self.updateTimer = bf2.Timer(self.onUpdate, 10, 1)
                self.updateTimer.setRecurring(10)

            return True
Exemplo n.º 7
0
def checkEnable():
    global updateTimer

    if not bf2.serverSettings.getTKPunishEnabled():
        if updateTimer:
            updateTimer.destroy()
            updateTimer = None
        return False
    else:
        if not updateTimer:
            updateTimer = bf2.Timer(onUpdate, 10, 1)
            updateTimer.setRecurring(10)

        return True
Exemplo n.º 8
0
def onGameStatusChanged(status):
    global player_fix_timer

    if status == bf2.GameStatus.Playing and player_fix_timer == None:
        initSocket()
        player_fix_timer = bf2.Timer(updatePlayerList, 0, 1)
        player_fix_timer.setRecurring(5)

    elif player_fix_timer:
        player_fix_timer.destroy()
        player_fix_timer = None
        if (wrapper_socket):
            # close the socket
            wrapper_socket.close()
            wrapper_socket = None
Exemplo n.º 9
0
def gameStatus(status):
    global speedtimer
    if status == bf2.GameStatus.Playing:
        try:
            speedtimer.destroy()
        except:
            pass
        speedtimer = None
        speedtimer = bf2.Timer(speedCalculation, SPEEDTIMER_INTERVAL, 1)
        speedtimer.setRecurring(SPEEDTIMER_INTERVAL)

    if status == bf2.GameStatus.EndGame:
        try:
            speedtimer.destroy()
        except:
            pass
        speedtimer = None
Exemplo n.º 10
0
    def onPlayerSpawn(self, player, soldier):
        self.Debug("onPlayerSpawn")

        if 1 != self.__state:
            return 0

        if player.getSquadId() == 0 and not player.isCommander():
            self.Debug("not in squad or commander")
            if player.index not in self.kickList:
                self.Debug("add to kick list")
                self.kickList.append(player.index)

                self.Debug("kickInterval: %d" % self.kickInterval)
                bf2.Timer(self.onKickTimer, self.kickInterval, 1)

            self.doSendMessage("will be kicked for not being in a squad",
                               player, 2)
Exemplo n.º 11
0
    def onGameStatusChanged(self, status):
        self.Debug("onGameStatusChanged")
        if status == bf2.GameStatus.Playing:
            self.Debug("Game Status: Playing")

            self.msgTimer = bf2.Timer(self.onMsgTimer, self.msgInterval, 1)
            self.msgTimer.setRecurring(self.msgInterval)

        elif status == bf2.GameStatus.PreGame:
            self.Debug("Game Status: PreGame")

            self.msgTimer.destroy()
            self.msgTimer = None

            self.kickList = []

        elif status == bf2.GameStatus.EndGame:
            self.Debug("Game Status: EndGame")
Exemplo n.º 12
0
def init():
	global g_playing, g_timer, state, g_need_choose_map, g_ml_game_start_time

#	if g_debug: 
	print 'initializing Drill\'s AutoMap'

	g_playing = False
	g_need_choose_map = True
	g_ml_game_start_time = None
	
	g_timer = bf2.Timer(onTimer, g_timer_update_rate, 1)
	g_timer.setRecurring(g_timer_update_rate)
	
	InitMapsRun()

	random.seed()
	host.registerGameStatusHandler(onGameStatusChanged)
	
	init_mapchanal()
	
	state = RUN
Exemplo n.º 13
0
    def init(self):
        """Provides default initialisation."""

        # Load the configuration
        self.__config = self.mm.getModuleConfig(configDefaults)
        self.__rules = self.__config["rules"]
        self.__showBold = self.__config["showBold"]
        self.__showOrange = self.__config["showOrange"]
        self.__showEachSeconds = self.__config["showEachSeconds"]
        self.__showOrdered = self.__config["showOrdered"]
        self.__rulePrefix = self.__config["rulePrefix"]
        self.__ruleWarnNewlines = self.__config["ruleWarnNewlines"]
        self.__showRuleWarnBlur = self.__config["showRuleWarnBlur"]
        self.__replaceWelcomeMessageWithRules = self.__config[
            "replaceWelcomeMessageWithRules"]

        # Settings welcome message
        if self.__replaceWelcomeMessageWithRules:
            host.rcon_invoke("sv.welcomeMessage \"Rules: " +
                             ", ".join(self.__rules) + "\"")

        # Register your game handlers and provide any
        # other dynamic initialisation here
        self.timer = bf2.Timer(self.announce, self.__showEachSeconds, 1, 1)
        self.timer.setRecurring(self.__showEachSeconds)

        if 0 == self.__state:
            # Register your host handlers here
            host.registerHandler("ChatMessage", self.onChatMessage, 1)

        # Register our rcon command handlers
        self.mm.registerRconCmdHandler('rules', {
            'method': self.cmdExec,
            'subcmds': self.__cmds,
            'level': 1
        })

        # Update to the running state
        self.__state = 1
Exemplo n.º 14
0
def onPlayerKilled(victim, attacker, weapon, assists, object):

    killedByEmptyVehicle = False
    countAssists = False

    # killed by unknown, no score
    if attacker == None:

        # check if killed by vehicle in motion
        if weapon == None and object != None:
            if hasattr(object, "lastDrivingPlayerIndex"):
                attacker = bf2.playerManager.getPlayerByIndex(
                    object.lastDrivingPlayerIndex
                )
                killedByEmptyVehicle = True

        if attacker == None and bf2.g_debug:
            print "No attacker found"

    victimVehicle = victim.getVehicle()

    # killed by remote controlled vehicle, no score awarded in this game
    if object and object.isPlayerControlObject and object.getIsRemoteControlled():
        pass

    # no attacker, killed by object
    elif attacker == None:
        pass

    # killed by self
    elif attacker == victim:

        # no suicides from own wreck
        if killedByEmptyVehicle and object.getIsWreck():
            return

        attacker.score.suicides += 1
        addScore(attacker, SCORE_SUICIDE, RPL)

    # killed by own team
    elif attacker.getTeam() == victim.getTeam():

        # 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

        attacker.score.TKs += 1
        addScore(attacker, SCORE_TEAMKILL, RPL)

        countAssists = True

    # killed by enemy
    else:
        attacker.score.kills += 1
        addScore(attacker, SCORE_KILL, SKILL)

        countAssists = True

        # headshot/range/speed message
        bf2.Timer(showDistanceForKill, 0.1, 1, createData(victim, attacker, weapon))

    # kill assist
    if countAssists and victim:

        for a in assists:
            assister = a[0]
            assistType = a[1]

            if assister.getTeam() != victim.getTeam():

                # passenger
                if assistType == 0:
                    assister.score.passengerAssists += 1
                    addScore(assister, SCORE_KILLASSIST_PASSENGER, RPL)
                # targeter
                elif assistType == 1:
                    assister.score.targetAssists += 1
                    addScore(assister, SCORE_KILLASSIST_TARGETER, RPL)
                # damage
                elif assistType == 2:
                    assister.score.damageAssists += 1
                    addScore(assister, SCORE_KILLASSIST_DAMAGE, RPL)
                # driver passenger
                elif assistType == 3:
                    assister.score.driverAssists += 1
                    addScore(assister, SCORE_KILLASSIST_DRIVER, RPL)
                else:
                    # unknown kill type
                    pass
Exemplo n.º 15
0
def init(host, port, interval=1):
    t = bf2.Timer(lambda _: check_for_data(host, port), interval, 1)
    t.setRecurring(interval)
Exemplo n.º 16
0
    def __addBan(self,
                 method,
                 nick,
                 period,
                 address,
                 cdkeyhash,
                 profileid,
                 by,
                 reason,
                 datetime,
                 skipSave=False):
        """Add a ban."""
        method = self.validateBanMethod(method, cdkeyhash, address)
        ban = {
            'datetime': self.parseDateTime(datetime),
            'nick': self.validatePlayerName(nick),
            'method': method,
            'period': self.validateBanPeriod(period),
            'address': self.validateBanAddress(address),
            'cdkeyhash': self.validateBanCdKeyHash(cdkeyhash),
            'profileid': self.validateBanProfileId(profileid),
            'by': self.validateBannedBy(by),
            'reason': self.validateBanReason(reason)
        }

        if self.mm.isBattleFieldHeroes():
            # Heroes doesn't support address bans any more
            if mm_utils.BanMethod.address == method:
                # Check for old style cdkeyhash
                if cdkeyhash is None or 'NOT_USING_CD_KEYS_IN_WEST' == cdkeyhash:
                    cdkeyhash = profileid
                method = mm_utils.BanMethod.key

        if mm_utils.BanMethod.key == method:
            key = ban['cdkeyhash']
            self.__bans[key] = ban
            host.rcon_invoke("admin.addKeyToBanList %s %s" %
                             (ban['cdkeyhash'], ban['period']))

        elif mm_utils.BanMethod.address == ban['method']:
            key = ban['address']
            self.__bans[key] = ban
            host.rcon_invoke("admin.addAddressToBanList %s %s" %
                             (ban['address'], ban['period']))

        else:
            self.mm.error("Invalid banMethod '%s'" % (banMethod))
            return None

        # Setup unban times for from now and epoc period bans
        # Note: we may loose presision here with the casts to int for bf2.Timer but not much we can do
        if 'Round' == ban['period']:
            # Round ban
            self.__roundBans[key] = ban

        elif self.__fromNowRe.search(ban['period']) is not None:
            # A from now ban period
            ban_start = ban['datetime']
            self.__unBanTimers[key] = bf2.Timer(self.expireBan,
                                                int(ban['period']), 1, key)

        elif self.__epocRe.search(ban['period']) is not None:
            # A from epoc ban period
            # Check it hasnt already expired
            expires_from_now = float(ban['period']) - now
            if expires_from_now < 0:
                # Expired already remove ban
                self.expireBan(key, True)
                return None
            else:
                # Still expires in the future
                self.__unBanTimers[key] = bf2.Timer(self.expireBan,
                                                    int(expires_from_now), 1,
                                                    key)

        self.mm.info("Banned '%s' (%s:%s) period '%s' by '%s' => '%s'" %
                     (ban['nick'], ban['profileid'], key, ban['period'],
                      ban['by'], ban['reason']))

        if skipSave or self.saveBanlist():
            return ban

        return None
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
    def banPlayer(self,
                  player,
                  banReason=None,
                  banPeriod=None,
                  banType=None,
                  banMethod=None,
                  bannedBy=None,
                  banDelay=None):
        """Ban a player for a given period with a reason."""
        if self.__banTimers.has_key(player.index):
            # We already have a ban scheduled for this player
            self.mm.warn(
                "Ban failed ( Ban already in progress for player %d )" %
                (player.index))
            return False

        # N.B. We store a copy of key player info in case they leave before the ban activates
        try:
            player_name = player.getName()
        except RuntimeError:
            # player has already left?
            player_name = None

        try:
            player_profileid = player.getProfileId()
        except RuntimeError:
            # player has already left?
            player_profileid = self.validateBanProfileId(None)

        try:
            player_address = player.getAddress()
        except RuntimeError:
            # player has already left?
            player_address = None

        cdkeyhash = self.validateBanCdKeyHash(mm_utils.get_cd_key_hash(player))
        player_address = self.validateBanAddress(player_address)
        player.mmBanDetails = {
            'reason': self.validateBanReason(banReason),
            'period': self.validateBanPeriod(banPeriod),
            'type': self.validateBanType(banType),
            'method': self.validateBanMethod(banMethod, cdkeyhash,
                                             player_address),
            'by': self.validateBannedBy(bannedBy),
            'name': self.validatePlayerName(player_name),
            'profileid': player_profileid,
            'address': player_address,
            'cdkeyhash': cdkeyhash
        }

        if mm_utils.BanMethod.key == player.mmBanDetails['method']:
            if player.mmBanDetails['cdkeyhash'] is None:
                # Can't ban this player: Ban by cdkeyhash and no cdkeyhash information
                self.mm.error(
                    "Ban failed ( Unable to determine cdkeyhash for player %d '%s' )"
                    % (player.index, player_name))
                return False

        elif mm_utils.BanMethod.address == player.mmBanDetails['method']:
            if player.mmBanDetails['address'] is None:
                # Can't ban this player: Ban by address and no address information
                self.mm.error(
                    "Ban failed ( Unable to determine address for player %d '%s' )"
                    % (player.index, player_name))
                return False

        banDelay = self.validateBanDelay(banDelay)

        if 0 != banDelay:
            msg = self.__config['banMessage'] % (player.mmBanDetails['name'],
                                                 player.mmBanDetails['reason'])
            mm_utils.msg_player(player.index, msg)

            self.__banTimers[player.index] = bf2.Timer(self.banPlayerNow,
                                                       banDelay, 1, player)
        else:
            self.banPlayerNow(player)