Уведомления

Группа в Telegram: @pythonsu

#1 Сен. 17, 2015 17:54:38

vlad1213
Зарегистрирован: 2015-09-17
Сообщения: 1
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите пожалуйста разобраться с кодом

Здравствуйте, помогите мне пожалуйста правильно расставить код Python.
Есть уже готовый код, но мне нужна лишь часть этого кода.
Мне нужно что бы работали вот эти строчки:
host.registerHandler(“PlayerConnect”, onPlayerConnect, 1)
host.registerHandler(“RemoteCommand”, onFilteredRemoteCommand, 1)
host.registerHandler('PlayerSpawn', onPlayerSpawn)
host.registerHandler('RemoteCommandSelectKit', onKitSelected)
host.registerHandler('RemoteCommandCustomKit', onCustomKitSelect)
host.registerHandler('RemoteCommandInitKit', onKitInit)

# File: r (Python 2.3)
global g_kits_used, g_kits_allocated, g_kits_allocated_remove, g_kits_allocated_timer, g_kits_squads, g_kits_squads_selects, g_kits_wrong, g_kits_wrong_timer, g_kits_limits, g_kits_limits_factions, g_kits_limits_squads, g_kits_reset_timer, g_kits_variants, g_kits_ninja_timer, g_kits_slots, g_mapid
import host
import bf2
import math
import time
from game.realitycore import *
class KitSlot:
    
    def __init__(self):
        self.Name = ''
        self.Primary = ''
        self.Secondary = ''
        self.Soldier = ''
        self.LimitationsEnabled = True
spawnableKits = [
    'sniper',
    'marksman',
    'aa',
    'at',
    'support',
    'officer',
    'tanker',
    'pilot',
    'riflemanat',
    'assault',
    'engineer',
    'medic',
    'riflemanap',
    'specialist',
    'rifleman',
    'mg',
    'spotter',
    'civilian',
    'insurgent1',
    'insurgent2',
    'insurgent3',
    'insurgent4',
    'sapper']
teamkilledKits = [
    'sniper',
    'marksman',
    'aa',
    'at',
    'support',
    'specialist',
    'tanker',
    'pilot',
    'riflemanat',
    'assault',
    'engineer',
    'riflemanap',
    'officer',
    'mg',
    'spotter']
unlimitedKits = [
    'officer',
    'tanker',
    'pilot',
    'rifleman',
    'insurgent1',
    'insurgent2',
    'insurgent3',
    'insurgent4',
    'sapper',
    'civilian']
lockedKits = []
variantsKits = [
    'nvg',
    'ziptie',
    'md',
    'sp',
    'pickup',
    'night']
unlockedPickupKits = [
    'unarmed']
vehicleKits = [
    'tanker',
    'pilot']
kitNames = {
    'sniper': t('kits_sniper'),
    'marksman': t('kits_marksman'),
    'aa': t('kits_aa'),
    'at': t('kits_at'),
    'support': t('kits_support'),
    'specialist': t('kits_specialist'),
    'officer': t('kits_officer'),
    'tanker': t('kits_crewman'),
    'pilot': t('kits_pilot'),
    'engineer': t('kits_engineer'),
    'medic': t('kits_medic'),
    'riflemanat': t('kits_riflemanat'),
    'assault': t('kits_assault'),
    'civilian': t('kits_civilian'),
    'sapper': t('kits_sapper'),
    'riflemanap': t('kits_riflemanap'),
    'mg': t('kits_mg'),
    'spotter': t('kits_spotter') }
g_kits_used = { }
g_kits_allocated = { }
g_kits_allocated_remove = []
g_kits_allocated_timer = None
g_kits_squads = { }
g_kits_squads_selects = { }
g_kits_wrong = { }
g_kits_wrong_timer = None
g_kits_limits = { }
g_kits_limits_factions = { }
g_kits_limits_squads = { }
g_kits_reset_timer = None
g_kits_variants = { }
g_kits_ninja_timer = None
g_kits_slots = None
g_mapid = ''
def getKitName(kit):
    
    try:
        return kitNames[kit]
    except:
        
        try:
            return kitNames[getKitTypeString(kit, True)]
        try:
            return kitNames[getKitTypeString(kit, False)]
        return kit
    
def getKitTypeString(kit, team = False):
    if kit.find('_') == -1:
        return kit
    
    
    try:
        kit = kit.split('_')
        if team:
            return kit[0] + '_' + kit[1]
        else:
            return kit[1]
    except:
        return kit
def getKitVariants(kit):
    kits = kit.split('_')
    variants = []
    for variant in variantsKits:
        if variant in kits:
            variants.append(variant)
            continue
    
    return variants
def getKitTeamVariants(team):
    return g_kits_variants[team]
def getKitTemplate(kit, team, variants = False, alt = False):
    teamName = getTeamName(team)
    template = teamName + '_' + kit
    if alt and teamName in realityserver.C('KIT_ALTERNATIVES') and kit in realityserver.C('KIT_ALTERNATIVES')[teamName]:
        template += '_alt'
    
    if variants:
        return template + getKitTeamVariants(team)
    else:
        return template
def isNinja(player):
    
    try:
        if getKitTypeString(player.getKit().templateName) == 'ninja':
            return True
    except:
        return False
def isKitTeamkiller(player, kit):
    trace = PRTrace('kits: isKitTeamkiller()')
    
    try:
        penalty = player.tkLimitedKit[kit]
    except:
        return False
    if not penalty:
        return False
    
    if now() >= penalty:
        player.tkLimitedKit[kit] = None
        if isDebugEnabled('penalty'):
            debugMessage('removed ' + player.getName() + ' penalty for tk ' + kit, 'penalty')
        
        return False
    
    if isDebugEnabled('kits'):
        debugMessage(player.getName() + ' is ' + kit + ' kit teamkiller', 'kits')
    
    return True
from game.realityvehicles import getVehiclesOfMap, getVehiclesKits
from game.realityrally import getRallyPoint
from game.realityspawner import createSpawner
from game.realityassets import getAssetsOfType, getAssetTypeFromTemplate
from game.realityscoring import WEAPONS_NO_PUNISH
def init():
    host.registerGameStatusHandler(onGameStatusChanged)
    host.registerHandler('RemoteCommandKitRequest', onRemoteKitRequestCommand)
    host.registerHandler('PlayerTeamKilled', onPlayerTeamKilled)
    host.registerHandler('PickupFirstKit', onPickupInvalidSelectKit)
    host.registerHandler('PickupFirstKit', onPickupVariantKit)
    host.registerHandler('PlayerSpawn', onPlayerSpawn)
    host.registerHandler('PickupKit', onPickupTeamKilledKit)
    host.registerHandler('PickupKit', onPickupKit)
    host.registerHandler('PickupKit', onPickupLockedKit)
    host.registerHandler('DropKit', onDropKit)
    host.registerHandler('DropKit', onDropLockedKit)
    host.registerHandler('ExitVehicle', onExitVehicle)
    host.registerHandler('PlayerKilled', onPlayerKilled)
    host.registerHandler('PlayerDeath', onPlayerDeath)
    host.registerHandler('PlayerConnect', onPlayerConnect, 1)
    host.registerHandler('PlayerChangeTeams', onPlayerChangeTeams)
    host.registerHandler('RemoteCommandCamera', onRemoteCameraCommand)
    host.registerHandler('RemoteCommandNinja', onRemoteNinjaCommand)
    host.registerHandler('RemoteCommandKits', onRemoteKitsCommand)
    host.registerHandler('RemoteCommandOneFaction', onRemoteOneFactionCommand)
    host.registerHandler('RemoteCommandDrop', onRemoteDropCommand)
    host.registerHandler('PlayerChangedSquad', onPlayerChangedSquad)
    host.registerHandler('ChangedCommander', onChangedCommander)
    host.registerHandler('RemoteCommandSelectKit', onKitSelected)
    host.registerHandler('PlayerDisconnect', onPlayerDisconnect)
    host.registerHandler('RemoteCommandCustomKit', onCustomKitSelect)
    host.registerHandler('RemoteCommandInitKit', onKitInit)
    print 'realitykits.py initialized'
def onGameStatusChanged(status):
    global g_mapid, g_kits_slots, g_kits_used, g_kits_wrong, g_kits_allocated, g_kits_allocated_timer, g_kits_reset_timer, g_kits_ninja_timer, g_kits_wrong_timer
    trace = PRTrace('kits: onGameStatusChanged()')
    if status == bf2.GameStatus.Playing and reallyPlaying():
        mapid = '%s|%s|%s' % (getMapName(), getGameMode(), getMapLayer())
        if g_mapid != mapid:
            g_mapid = mapid
            g_kits_slots = {
                1: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None],
                2: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None] }
            for player in bf2.playerManager.getPlayers():
                player.customSelection = {
                    1: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0],
                    2: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0] }
            
        
        setupKitLimits()
        g_kits_used = { }
        g_kits_wrong = { }
        g_kits_allocated = { }
        for team in [
            1,
            2]:
            g_kits_squads[team] = { }
            g_kits_squads_selects[team] = { }
            g_kits_variants[team] = None
            for kit in spawnableKits:
                g_kits_used[getKitTemplate(kit, team)] = 0
                g_kits_allocated[getKitTemplate(kit, team)] = 0
            
            for squad in range(1, 10):
                g_kits_squads[team][squad] = { }
                g_kits_squads_selects[team][squad] = { }
                for kit in spawnableKits:
                    g_kits_squads[team][squad][kit] = []
                    g_kits_squads_selects[team][squad][kit] = []
                
            
        
        g_kits_allocated_timer = bf2.Timer(checkKitAllocations, realityserver.C('STARTDELAY') + 20, 1, '')
        g_kits_allocated_timer.setRecurring(20)
        g_kits_reset_timer = bf2.Timer(resetKits, 1, 1, '')
        g_kits_ninja_timer = bf2.Timer(checkNinjas, realityserver.C('STARTDELAY') + 2, 1, '')
        g_kits_ninja_timer.setRecurring(2)
        g_kits_wrong_timer = bf2.Timer(checkLockedKits, realityserver.C('STARTDELAY') + 15, 1, '')
        g_kits_wrong_timer.setRecurring(15)
    else:
        destroyKitAllocationsTimer()
        destroyKitResetTimer()
        destroyKitNinjasTimer()
        destroyLockedKitsTimer()
        g_kits_used.clear()
        g_kits_allocated.clear()
        del g_kits_allocated_remove[:]
        g_kits_squads.clear()
        g_kits_squads_selects.clear()
        g_kits_variants.clear()
        g_kits_wrong.clear()
        g_kits_limits.clear()
        g_kits_limits_factions.clear()
        g_kits_limits_squads.clear()
def resetKits(data = ''):
    trace = PRTrace('kits: resetKits()')
    destroyKitResetTimer()
    
    try:
        for player in getPlayers():
            onPlayerConnect(player)
            checkSelectedKit(player)
    except:
        pass
def setupKitLimits():
    trace = PRTrace('kits: setupKitLimits()')
    defaults = {
        8: realityserver.C('KIT_LIMIT_8'),
        16: realityserver.C('KIT_LIMIT_16'),
        24: realityserver.C('KIT_LIMIT_24'),
        32: realityserver.C('KIT_LIMIT_32') }
    g_kits_limits.clear()
    g_kits_limits_factions.clear()
    g_kits_limits_squads.clear()
    for team in [
        1,
        2]:
        g_kits_limits[team] = { }
        for num in defaults.keys():
            g_kits_limits[team][num] = { }
            for (kit, limit) in defaults[num].items():
                g_kits_limits[team][num][kit] = limit
            
        
    
    for team in realityserver.C('KIT_LIMITS').keys():
        g_kits_limits_factions[team] = { }
        for (kit, num) in realityserver.C('KIT_LIMITS')[team].items():
            g_kits_limits_factions[team][kit] = num
        
    
    for (kit, num) in realityserver.C('KIT_LIMITS_SQUAD').items():
        g_kits_limits_squads[kit] = num
    
def setKitLimit(team, kit, limit, size = None):
    trace = PRTrace('kits: setKitLimit()')
    if not size:
        sizes = [
            8,
            16,
            24,
            32]
    else:
        sizes = [
            size]
    for s in sizes:
        g_kits_limits[team][s][kit] = limit
    
def getKitLimit(team, kit):
    trace = PRTrace('kits: getKitLimit()')
    n = bf2.playerManager.getNumberOfPlayersInTeam(team)
    if n >= 24:
        size = 32
    elif n >= 16:
        size = 24
    elif n >= 8:
        size = 16
    else:
        size = 8
    
    try:
        return g_kits_limits[team][size][kit]
    except:
        return None
def setKitLimitFaction(faction, kit, limit):
    trace = PRTrace('kits: setKitLimitFaction()')
    g_kits_limits_factions[faction][kit] = limit
def getKitLimitFaction(faction, kit):
    trace = PRTrace('kits: getKitLimitFaction()')
    
    try:
        return g_kits_limits_factions[faction][kit]
    except:
        return None
def setKitLimitSquad(kit, limit):
    trace = PRTrace('kits: setKitLimitSquad()')
    g_kits_limits_squads[kit] = limit
def getKitLimitSquad(kit):
    trace = PRTrace('kits: getKitLimitSquad()')
    
    try:
        return g_kits_limits_squads[kit]
    except:
        return None
def destroyKitResetTimer():
    global g_kits_reset_timer
    trace = PRTrace('kits: destroyKitResetTimer()')
    
    try:
        if g_kits_reset_timer:
            g_kits_reset_timer.destroy()
            g_kits_reset_timer = None
    except:
        pass
def destroyKitNinjasTimer():
    global g_kits_ninja_timer
    trace = PRTrace('kits: destroyKitNinjasTimer()')
    
    try:
        if g_kits_ninja_timer:
            g_kits_ninja_timer.destroy()
            g_kits_ninja_timer = None
    except:
        pass
def destroyKitAllocationsTimer():
    global g_kits_allocated_timer
    trace = PRTrace('kits: destroyKitAllocationsTimer()')
    
    try:
        if g_kits_allocated_timer:
            g_kits_allocated_timer.destroy()
            g_kits_allocated_timer = None
    except:
        pass
def destroyLockedKitsTimer():
    global g_kits_wrong_timer
    trace = PRTrace('kits: destroyLockedKitsTimer()')
    
    try:
        if g_kits_wrong_timer:
            g_kits_wrong_timer.destroy()
            g_kits_wrong_timer = None
    except:
        pass
def checkKitAllocations(data = ''):
    trace = PRTrace('kits: checkKitAllocations()')
    times = now()
    floor = { }
    deletion = []
    for item in g_kits_allocated_remove[:]:
        if times < item['end']:
            continue
        
        kit = item['kit']
        team = item['team']
        squad = item['squad']
        index = item['player']
        position = item['position']
        template = getKitTemplate(kit, team)
        if position and g_kits_allocated[template] > g_kits_used[template]:
            if template not in floor:
                floor[template] = False
                if isDebugEnabled('kits'):
                    debugMessage('checking for kits ' + template + ' on the floor', 'kits')
                
                for alt in [
                    False,
                    True]:
                    if alt and getKitTemplate(kit, team, False, alt) == template:
                        continue
                    
                    for floorkit in cleanListOfObjects(bf2.objectManager.getObjectsOfTemplate(getKitTemplate(kit, team, True, alt)), True):
                        
                        try:
                            if getSquareVectorDistance(floorkit.getPosition(), position) <= DISTANCE_SPAWN ** 2:
                                floor[template] = True
                                if isDebugEnabled('kits'):
                                    debugMessage('found kit ' + template + ' on the floor - no deallocation', 'kits')
                                
                                break
                        continue
                        continue
                    
                
            
            if template in floor and floor[template] == True:
                continue
            
        
        
        try:
            if item in g_kits_allocated_remove:
                g_kits_allocated_remove.remove(item)
        except:
            pass
        removeTeamAllocation(team, kit)
        removeSquadAllocation(team, squad, kit, index)
    
def removeKitAllocation(player, kit):
    trace = PRTrace('kits: removeKitAllocation()')
    if not kit and kit not in spawnableKits or player.isAIPlayer():
        return None
    
    player.allocatedKit = None
    if kit in unlimitedKits:
        return None
    
    
    try:
        position = player.getDefaultVehicle().getPosition()
    except:
        position = None
    
    try:
        delay = realityserver.C('KIT_ALLOCATION_DELAY')[kit]
    except:
        delay = 0
    index = player.index
    for team in [
        1,
        2]:
        if delay == 0:
            removeTeamAllocation(team, kit)
        
        for squad in range(1, 10):
            if index not in g_kits_squads[team][squad][kit]:
                continue
            
            if delay == 0:
                removeSquadAllocation(team, squad, kit, index)
                continue
            
            g_kits_allocated_remove.append({
                'team': team,
                'squad': squad,
                'player': index,
                'kit': kit,
                'end': now() + delay,
                'position': position })
            if isDebugEnabled('kits'):
                debugMessage('timed removal of kit allocation %s team %s squad %s index %s delay %s' % (kit, team, squad, index, delay), 'kits')
                continue
        
    
def addKitAllocation(player, kit, times = True):
    trace = PRTrace('kits: addKitAllocation()')
    if not kit and kit not in spawnableKits or player.isAIPlayer():
        return None
    
    team = player.getTeam()
    squad = player.getSquadId()
    removeKitAllocation(player, player.allocatedKit)
    player.allocatedKit = kit
    if times:
        player.lastKitAllocation = now()
    
    if kit in unlimitedKits:
        return None
    
    addTeamAllocation(team, kit)
    addSquadAllocation(team, squad, kit, player.index)
def onChangedCommander(team, oldCmd, newCmd):
    trace = PRTrace('kits: onChangedCommander()')
    if newCmd:
        checkSelectedKit(newCmd)
    
    if oldCmd:
        checkSelectedKit(oldCmd)
    
def onPlayerChangedSquad(player, oldSquad, newSquad):
    trace = PRTrace('kits: onPlayerChangedSquad()')
    if oldSquad:
        removeKitReservations(player)
        checkSelectedKitSquad(player.getTeam(), oldSquad)
    
    checkSelectedKit(player)
def isKitReservable(team, squad, kit):
    trace = PRTrace('kits: isKitReservable()')
    if not team and not squad and kit not in spawnableKits or kit in unlimitedKits:
        return False
    
    return True
def isKitReserved(team, squad, kit):
    trace = PRTrace('kits: isKitReserved()')
    if not isKitReservable(team, squad, kit):
        return False
    
    selected = g_kits_squads_selects[team][squad][kit]
    if len(selected) == 0:
        return False
    
    limit = getKitLimitSquad(kit)
    if not limit:
        return False
    
    if len(selected) < limit:
        return False
    else:
        return True
def isKitReservedByPlayer(team, squad, kit, player):
    trace = PRTrace('kits: isKitReservedByPlayer()')
    if not isKitReservable(team, squad, kit):
        return False
    
    selected = g_kits_squads_selects[team][squad][kit]
    if len(selected) == 0:
        return False
    
    return player.index in selected
def isKitRequestable(player, kit, current = True, allocation = True):
    trace = PRTrace('kits: isKitRequestable()')
    if not kit or kit not in spawnableKits:
        return False
    
    team = player.getTeam()
    squad = player.getSquadId()
    if squad == 0 and not player.isCommander():
        return sendMessageToPlayer(player, 3240301)
    
    if not validTeamKit(team, kit) or getTeamName(team) in realityserver.C('KIT_REQUEST_BLOCK'):
        return sendMessageToPlayer(player, 3240703)
    
    if not isValidKit(player, kit, current, allocation):
        return False
    
    if not isKitReservedByPlayer(team, squad, kit, player) and isKitReserved(team, squad, kit):
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' kit is not valid for ' + player.getName() + ' - currently reserved', 'kits')
        
        return sendMessageToPlayer(player, 2191319)
    
    if kit in vehicleKits:
        if isVehicleKitRequestable(player, kit):
            return True
        
        return sendMessageToPlayer(player, 1190601, 1)
    elif isNormalKitRequestable(player, kit):
        return True
    
    if kit in realityserver.C('KIT_LOCKED_RALLY'):
        return sendMessageToPlayer(player, 1031923, 1)
    else:
        return sendMessageToPlayer(player, 1032415, 1)
    return False
def isKitSelectable(player, kit, current = True, allocation = True):
    trace = PRTrace('kits: isKitSelectable()')
    if not kit and kit not in spawnableKits or player.isAIPlayer():
        return True
    
    team = player.getTeam()
    squad = player.getSquadId()
    if not validTeamKit(team, kit):
        return True
    
    if not isValidKit(player, kit, current, allocation, False):
        return False
    
    if not isKitReservedByPlayer(team, squad, kit, player) and isKitReserved(team, squad, kit):
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' kit is not valid for ' + player.getName() + ' - currently reserved', 'kits')
        
        return False
    
    return True
def checkSelectedKitSquad(team, squad, kit = None, player = None):
    trace = PRTrace('kits: checkSelectedKitSquad()')
    for p in getPlayersOfSquad(team, squad, player):
        if kit and p.selectedKit and p.selectedKit != kit:
            continue
        
        checkSelectedKit(p)
    
def checkSelectedKit(player):
    trace = PRTrace('kits: checkSelectedKit()')
    if player.isAIPlayer():
        return None
    
    if isDebugEnabled('kits'):
        debugMessage('--- check %s selected kit %s' % (player.getName(), player.selectedKit), 'kits')
    
    team = player.getTeam()
    squad = player.getSquadId()
    kit = player.selectedKit
    if isKitSelectable(player, kit):
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' kit is selectable by ' + player.getName(), 'kits')
        
        if player.dead:
            continueSpawnTime(player, 'kit')
            clearScreen(player)
        
        addKitReservation(team, squad, kit, player)
    elif isDebugEnabled('kits'):
        debugMessage(str(kit) + ' kit is not selectable by ' + player.getName(), 'kits')
    
    if player.dead:
        pauseSpawnTime(player, 'kit')
        blackScreen(player)
    
    removeKitReservation(team, squad, kit, player)
def addKitReservation(team, squad, kit, player):
    trace = PRTrace('kits: addKitReservation()')
    if isKitReservable(team, squad, kit) and not isKitReservedByPlayer(team, squad, kit, player):
        g_kits_squads_selects[team][squad][kit].append(player.index)
        if isDebugEnabled('kits'):
            debugMessage('addded reservation %s kit %s team %s squad %s' % (player.getName(), kit, team, squad), 'kits')
        
    
def removeKitReservations(player):
    trace = PRTrace('kits: removeKitReservations()')
    for team in [
        1,
        2]:
        for squad in range(1, 10):
            for kit in spawnableKits:
                removeKitReservation(team, squad, kit, player)
            
        
    
def removeKitReservation(team, squad, kit, player):
    trace = PRTrace('kits: removeKitReservation()')
    if isKitReservable(team, squad, kit) and isKitReservedByPlayer(team, squad, kit, player):
        g_kits_squads_selects[team][squad][kit].remove(player.index)
        if isDebugEnabled('kits'):
            debugMessage('removed reservation %s kit %s team %s squad %s' % (player.getName(), kit, team, squad), 'kits')
        
    
def onPlayerSpawn(player, soldier):
    trace = PRTrace('kits: onPlayerSpawn()')
    if player.isAIPlayer():
        return None
    
    modifySpawn(player)
    player.lastUnarmedDropKit = (now() - realityserver.C('KIT_REQUEST_INTERVAL')) + 15
    times = True
    if player.selectedKit in unlimitedKits:
        times = False
    
    addKitAllocation(player, player.selectedKit, times)
def onPickupVariantKit(player, kit):
    trace = PRTrace('kits: onPickupVariantKit()')
    team = player.getTeam()
    if g_kits_variants[team] == None:
        g_kits_variants[team] = ''
        for variant in getKitVariants(kit.templateName):
            g_kits_variants[team] += '_' + variant
        
    
def onPickupInvalidSelectKit(player, kit):
    trace = PRTrace('kits: onPickupInvalidSelectKit()')
    if realityserver.isCoopServer():
        return None
    
    team = player.getTeam()
    squad = player.getSquadId()
    kit = getKitTypeString(kit.templateName)
    if not (player.selectedKit):
        player.selectedKit = kit
    
    if not (player.selectedKit) or player.selectedKit == kit:
        return None
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is not valid kit for ' + player.getName() + ' - selected kit is not ' + str(player.selectedKit), 'kits')
    
    setInvalidKit(player)
def onPickupKit(player, kit):
    trace = PRTrace('kits: onPickupKit()')
    if player.isAIPlayer():
        return None
    
    tmp = kit.templateName
    kit = getKitTypeString(tmp, True)
    if kit not in g_kits_used:
        return None
    
    g_kits_used[kit] += 1
    if isDebugEnabled('kits'):
        debugMessage('%s pickup by %s team %s (%s) - %s' % (kit, player.getName(), player.getTeam(), g_kits_used[kit], tmp), 'kits')
    
def onDropKit(player, kit):
    trace = PRTrace('kits: onDropKit()')
    if player.isAIPlayer():
        return None
    
    tmp = kit.templateName
    kit = getKitTypeString(tmp, True)
    if kit not in g_kits_used:
        return None
    
    g_kits_used[kit] -= 1
    if isDebugEnabled('kits'):
        debugMessage('%s drop by %s team %s (%s) - %s' % (kit, player.getName(), player.getTeam(), g_kits_used[kit], tmp), 'kits')
    
def onPlayerChangeTeams(player, human):
    trace = PRTrace('kits: onPlayerChangeTeams()')
    player.oldTeam = getOtherTeam(player.getTeam())
    removeKitReservations(player)
    removeKitAllocation(player, player.allocatedKit)
    onPlayerConnect(player)
    continueSpawnTime(player, 'kit')
    player.selectedKit = getKitSlot(player.getTeam())
    checkSelectedKit(player)
def onPlayerConnect(player):
    trace = PRTrace('kits: onPlayerConnect()')
    cached = getPlayerByIndex(player.index)
    if not cached:
        return None
    
    cached.customSelection = {
        1: [
            0,
            0,
            0,
            0,
            0,
            0,
            0],
        2: [
            0,
            0,
            0,
            0,
            0,
            0,
            0] }
    cached.allocatedKit = None
    cached.lastKitAllocation = None
    cached.lastUnarmedDropKit = None
    cached.tkLimitedKit = { }
    cached.selectedKit = None
def onPlayerDisconnect(player):
    trace = PRTrace('kits: onPlayerDisconnect()')
    team = player.getTeam()
    squad = player.getSquadId()
    kit = player.selectedKit
    index = player.index
    
    try:
        removeTeamAllocation(team, kit)
    except:
        pass
    
    try:
        removeSquadAllocation(team, squad, kit, index)
    except:
        pass
    
    try:
        removeKitReservations(player)
    except:
        pass
    player.customSelection = { }
    player.allocatedKit = None
    player.lastKitAllocation = None
    player.lastUnarmedDropKit = None
    player.tkLimitedKit = { }
    player.selectedKit = None
def onPlayerTeamKilled(victim, attacker, weapon, assists, object):
    trace = PRTrace('kits: onPlayerTeamKilled()')
    if realityserver.C('KIT_TK_PENALTY') == 0:
        return None
    
    team = attacker.getTeam()
    teamName = getTeamName(team)
    
    try:
        victimKit = getKitTypeString(victim.getKit().templateName)
        attackerKit = getKitTypeString(attacker.getKit().templateName)
    except:
        return None
    if victimKit not in teamkilledKits:
        return None
    
    
    try:
        if weapon:
            weaponName = weapon.templateName.lower()
        else:
            weaponName = attacker.getVehicle().templateName.lower()
    except:
        weaponName = ''
    if weaponName in WEAPONS_NO_PUNISH:
        return None
    
    g_vehicles_kits = getVehiclesKits()
    g_vehicles_map = getVehiclesOfMap()
    for type in [
        AIR,
        LAND,
        SEA,
        SUP,
        SPEC,
        ENG]:
        
        try:
            if victimKit not in g_vehicles_kits[type][teamName]:
                continue
        except:
            continue
        if weaponName in g_vehicles_map[team][type] and victimKit == attackerKit:
            return None
            continue
    
    
    try:
        if len(attacker.tkLimitedKit):
            pass
        1
    except:
        attacker.tkLimitedKit = { }
    if isDebugEnabled('penalty'):
        debugMessage(attacker.getName() + ' penalized for tk ' + victimKit, 'penalty')
    
    attacker.tkLimitedKit[victimKit] = now() + realityserver.C('KIT_TK_PENALTY')
def onPickupTeamKilledKit(player, kit):
    trace = PRTrace('kits: onPickupTeamKilledKit()')
    if realityserver.C('KIT_PICKUP_ANY') != 1:
        return None
    
    
    try:
        if isKitTeamkiller(player, getKitTypeString(kit.templateName)) > 0:
            if isDebugEnabled('penalty'):
                debugMessage('die teamkiller bastard', 'penalty')
            
            killPlayer(player)
    except:
        pass
def onPickupLockedKit(player, kit):
    trace = PRTrace('kits: onPickupLockedKit()')
    if realityserver.C('KIT_FACTION_LOCKED') != 1 or player.isAIPlayer():
        return None
    
    
    try:
        k = getKitTypeString(kit.templateName, True)
        team = k.split('_')[0]
        temp = k.split('_')[1]
    except:
        return None
    if team != getTeamName(getOtherTeam(player.getTeam())):
        return None
    
    if temp in unlockedPickupKits:
        return None
    
    g_kits_wrong[player.index] = now()
    sendMessageToPlayer(player, 1191819, 3)
def onDropLockedKit(player, kit):
    trace = PRTrace('kits: onDropLockedKit()')
    if realityserver.C('KIT_FACTION_LOCKED') != 1 or player.isAIPlayer():
        return None
    
    
    try:
        if player.index in g_kits_wrong:
            del g_kits_wrong[player.index]
            if not (player.killed):
                clearScreen(player)
            
    except:
        pass
def checkLockedKits(data = ''):
    trace = PRTrace('kits: checkLockedKits()')
    for (index, times) in g_kits_wrong.items():
        player = getPlayerByIndex(index)
        if not player or player.killed:
            
            try:
                if index in g_kits_wrong:
                    del g_kits_wrong[index]
            continue
            continue
            continue
        
        sendMessageToPlayer(player, 1191819, 3)
        if not times:
            killPlayer(player)
            continue
        if now() - times > 10:
            g_kits_wrong[index] = None
            blackScreen(player)
            continue
    
def validDistanceFromControlPoints(player, kit, cps, distance = DISTANCE_AREA):
    trace = PRTrace('kits: validDistanceFromControlPoints()')
    if isDebugEnabled('kits'):
        debugMessage('check valid distance from cps ' + kit, 'kits')
    
    team = player.getTeam()
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return False
    dist = distance ** 2
    for cp in cps:
        if isDebugEnabled('kits'):
            debugMessage('check if close to cp ' + cp.templateName, 'kits')
        
        if cp.cp_getParam('team') == team and cp.flagPosition != 2 and getSquareHorizDistance(cp.getPosition(), playerPos) < dist:
            if isDebugEnabled('kits'):
                debugMessage('next to cp ' + cp.templateName, 'kits')
            
            return True
            continue
    
def validTeamKit(team, kit):
    trace = PRTrace('kits: validTeamKit()')
    teamName = getTeamName(team)
    if teamName not in realityserver.C('KIT_LIMITS') or kit not in realityserver.C('KIT_LIMITS')[teamName]:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid team kit for ' + teamName, 'kits')
        
        return False
    elif isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid team kit for ' + teamName, 'kits')
    
    return True
def validSquadChange(player, kit):
    trace = PRTrace('kits: validSquadChange()')
    if realityserver.C('KIT_SQUAD_DELAY') == 0:
        return True
    
    if hasattr(player, 'oldTeam') and player.oldTeam != player.getTeam():
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - different team for last squad change', 'kits')
        return True
    
    if hasattr(player, 'changedSquad') and player.changedSquad and kit not in unlimitedKits:
        delta = now() - player.changedSquad
        if delta < realityserver.C('KIT_SQUAD_DELAY'):
            if isDebugEnabled('kits'):
                debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - squad change', 'kits')
            
            return False
        
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - old last squad change', 'kits')
    
    return True
def validSquadNumbers(player, kit, messages = True):
    trace = PRTrace('kits: validSquadNumbers()')
    if kit in [
        'officer'] and player.isCommander():
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - he is the commander', 'kits')
        
        return True
    
    if kit in [
        'officer'] and not player.isCommander() and not player.isSquadLeader():
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - he is not a squad leader or commander', 'kits')
        
        if messages:
            return sendMessageToPlayer(player, 2190318)
        
        return False
    
    neededSquadMembers = getKitLimitFaction(getTeamName(player.getTeam()), kit)
    if neededSquadMembers == None:
        if messages:
            return sendMessageToPlayer(player, 3240703)
        
        return False
    
    if neededSquadMembers == 0:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - it is not limited by squad number', 'kits')
        
        return True
    
    numSquadMembers = numPlayersInSquad(player)
    if isDebugEnabled('kits'):
        debugMessage('check squad numbers - %s members %s needed' % (numSquadMembers, neededSquadMembers), 'kits')
    
    if numSquadMembers == 0:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - no squad', 'kits')
        
        if messages:
            return sendMessageToPlayer(player, 3240301)
        
        return False
    elif numSquadMembers < neededSquadMembers:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - not enough squad members', 'kits')
        
        if messages:
            return sendSquadRequirementMessageToPlayer(player, neededSquadMembers)
        
        return False
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - good squad number', 'kits')
    
    return True
def validSquadAllocation(player, kit, messages = True):
    trace = PRTrace('kits: validSquadAllocation()')
    if kit not in realityserver.C('KIT_LIMITS_SQUAD'):
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - no squad allocation needed', 'kits')
        
        return True
    
    limit = getKitLimitSquad(kit)
    if not limit:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - no squad allocation needed', 'kits')
        
        return True
    
    issued = 0
    used = 0
    team = player.getTeam()
    squad = player.getSquadId()
    
    try:
        issued = len(g_kits_squads[team][squad][kit])
    except:
        pass
    if issued <= limit:
        for member in getPlayersInSquad(player):
            if member.killed or player.isAIPlayer():
                continue
            
            
            try:
                if kit == getKitTypeString(member.getKit().templateName):
                    used += 1
            continue
            continue
        
    
    if isDebugEnabled('kits'):
        debugMessage('check squad limits - %s issued %s used %s limit' % (issued, used, limit), 'kits')
    
    if issued >= limit or used >= limit:
        if isDebugEnabled('kits'):
            if used >= limit:
                debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - squad usage', 'kits')
            
            if issued >= limit:
                debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - squad allocation ' + str(getPlayersNames(getPlayersByIndex(g_kits_squads[team][squad][kit], True))), 'kits')
            
        
        if messages:
            return sendMessageToPlayer(player, 2191319)
        
        return False
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - good squad allocation', 'kits')
    
    return True
def validTeamAllocation(player, kit, messages = True):
    trace = PRTrace('kits: validTeamAllocation()')
    team = player.getTeam()
    limit = getKitLimit(team, kit)
    if limit == None:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - unlimited kit', 'kits')
        
        return True
    
    if limit < 1:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - unavailable for team right now', 'kits')
        
        if messages:
            return sendMessageToPlayer(player, 2020719)
        
        return False
    
    
    try:
        used = g_kits_used[getKitTemplate(kit, team)]
    except:
        used = 0
    
    try:
        allocated = g_kits_allocated[getKitTemplate(kit, team)]
    except:
        allocated = 0
    if used > allocated:
        num = used
    else:
        num = allocated
    if isDebugEnabled('kits'):
        debugMessage('check team allocation - %s used %s allocated %s limit' % (used, allocated, limit), 'kits')
    
    if num >= limit:
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - team allocation', 'kits')
        
        if messages:
            return sendMessageToPlayer(player, 2191608)
        
        return False
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' - good team allocation', 'kits')
    
    return True
def validSquadRallyRequest(player, kit):
    trace = PRTrace('kits: validSquadRallyRequest()')
    if player.getSquadId() == 0:
        return None
    
    if kit in realityserver.C('KIT_LOCKED_RALLY'):
        return None
    
    if isDebugEnabled('kits'):
        debugMessage('check if close to squad rallypoint', 'kits')
    
    rallypoint = getRallyPoint(player.getTeam(), player.getSquadId())
    if rallypoint:
        
        try:
            if getSquareVectorDistance(rallypoint.getPosition(), player.getDefaultVehicle().getPosition()) < DISTANCE_PICKUP ** 2:
                if isDebugEnabled('kits'):
                    debugMessage('next to squad rally point', 'kits')
                
                return True
        return False
    
def validCommandPostRequest(player, kit):
    trace = PRTrace('kits: validCommandPostRequest()')
    if isDebugEnabled('kits'):
        debugMessage('check if close to command post', 'kits')
    
    cmdPost = getCommandPost(player.getTeam())
    if cmdPost:
        
        try:
            if getSquareVectorDistance(cmdPost.getPosition(), player.getDefaultVehicle().getPosition()) < DISTANCE_SPAWN ** 2:
                if isDebugEnabled('kits'):
                    debugMessage('next to command post', 'kits')
                
                return True
        return False
    
def validSupplyObject(player, objects, vehicle = False, team = True):
    trace = PRTrace('kits: validSupplyObject()')
    if len(objects) == 0:
        return None
    
    playerTeam = player.getTeam()
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return False
    for (template, distance) in objects.items():
        if isDebugEnabled('kits'):
            debugMessage('check if close to supply object ' + template, 'kits')
        
        if template in realityserver.C('KIT_SUPPLY_OBJECTS_COMMANDER')[getTeamName(playerTeam)]:
            objs = getAssetsOfType(getAssetTypeFromTemplate(template, playerTeam), playerTeam)
        else:
            objs = bf2.objectManager.getObjectsOfTemplate(template)
        dist = distance ** 2
        for o in cleanListOfObjects(objs):
            
            try:
                if team and o.getTeam() != playerTeam:
                    continue
            except:
                pass
            spawn = False
            if vehicle and template not in realityserver.C('KIT_SUPPLY_OBJECTS_VEHICLES_SIDEDOORS'):
                if getSquareVectorVehicleDistance(o.getRotation(), o.getPosition(), playerPos) < dist:
                    spawn = True
                
            elif getSquareVectorDistance(o.getPosition(), playerPos) < dist:
                spawn = True
            
            if not spawn:
                continue
            
            if isDebugEnabled('kits'):
                debugMessage('next to ' + template, 'kits')
            
            return True
        
    
def isNormalKitRequestable(player, kit):
    trace = PRTrace('kits: isNormalKitRequestable()')
    team = player.getTeam()
    teamName = getTeamName(team)
    
    try:
        if validCommandPostRequest(player, kit):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_SUPPLY_OBJECTS_COMMANDER')[teamName], False):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_SUPPLY_OBJECTS')[teamName], False):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_SUPPLY_OBJECTS_OPEN')[teamName], False, False):
            return True
    except:
        pass
    
    try:
        if kit not in realityserver.C('KIT_LOCKED_VEHICLES'):
            if validSupplyObject(player, realityserver.C('KIT_SUPPLY_OBJECTS_VEHICLES')[teamName], True):
                return True
            
    except:
        pass
def isVehicleKitRequestable(player, kit):
    trace = PRTrace('kits: isVehicleKitRequestable()')
    team = player.getTeam()
    teamName = getTeamName(team)
    
    try:
        if validCommandPostRequest(player, kit):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_VEHICLE_SUPPLY_OBJECTS_COMMANDER')[teamName], False):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_VEHICLE_SUPPLY_OBJECTS')[teamName], False):
            return True
    except:
        pass
    
    try:
        if validSupplyObject(player, realityserver.C('KIT_VEHICLE_SUPPLY_OBJECTS_OPEN')[teamName], False, False):
            return True
    except:
        pass
    
    try:
        g_vehicles_map = getVehiclesOfMap()
        if kit == 'tanker':
            templates = g_vehicles_map[team][LAND]
        elif kit == 'pilot':
            templates = g_vehicles_map[team][AIR]
        else:
            templates = []
    except:
        return False
    supplyObjects = { }
    for template in templates:
        supplyObjects[template] = DISTANCE_PICKUP * 3
    
    if validSupplyObject(player, supplyObjects, True):
        return True
    
def getKitSlot(team, slot = 2):
    trace = PRTrace('kits: getKitSlot()')
    
    try:
        if g_kits_slots[team][slot].LimitationsEnabled:
            return g_kits_slots[team][slot].Name
        else:
            return None
    except:
        
        try:
            if g_kits_slots[team][2].LimitationsEnabled:
                return g_kits_slots[team][2].Name
            else:
                return None
        return None
def onKitSelected(player, cmd, args):
    trace = PRTrace('kits: onKitSelected()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    
    try:
        slot = int(args[0].strip())
    except:
        return None
    team = player.getTeam()
    squad = player.getSquadId()
    inherit = False
    kit = getKitSlot(team, slot)
    if isKitReservedByPlayer(team, squad, player.selectedKit, player):
        removeKitReservations(player)
        inherit = copy(player.selectedKit)
    
    if isDebugEnabled('kits'):
        debugMessage('------ %s selected kit %s team %s squad %s' % (player.getName(), kit, team, squad), 'kits')
    
    player.selectedKit = kit
    checkSelectedKit(player)
    if inherit:
        checkSelectedKitSquad(team, squad, inherit, player)
    
def isValidKit(player, kit, current = True, allocation = True, messages = True):
    trace = PRTrace('kits: isValidKit()')
    if isDebugEnabled('kits'):
        debugMessage('check valid kit ' + kit + ' for ' + player.getName(), 'kits')
    
    if not player:
        return False
    
    team = player.getTeam()
    teamName = getTeamName(team)
    if not validSquadChange(player, kit):
        if messages:
            return sendMessageToPlayer(player, 3212201)
        
        return False
    
    if isKitTeamkiller(player, kit):
        if messages:
            return sendMessageToPlayer(player, 3242303)
        
        return False
    
    if not (player.dead) and current:
        
        try:
            playerKit = getKitTypeString(player.getKit().templateName)
            if playerKit == kit:
                if isDebugEnabled('kits'):
                    debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - requesting current kit', 'kits')
                
                if messages:
                    return sendMessageToPlayer(player, 2190303)
                
                return False
            
            if playerKit in lockedKits:
                if isDebugEnabled('kits'):
                    debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - requesting with locked kit', 'kits')
                
                if messages:
                    return sendMessageToPlayer(player, 2190318)
                
                return False
    
    if not validSquadNumbers(player, kit, messages):
        return None
    
    if allocation:
        if not validTeamAllocation(player, kit, messages):
            return None
        
        if not validSquadAllocation(player, kit, messages):
            return None
        
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' kit valid for ' + player.getName(), 'kits')
    
    return True
def onRemoteKitRequestCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteKitRequestCommand()')
    
    try:
        kit = args[0].strip()
    except:
        return None
    alt = False
    
    try:
        if args[1].strip() == 'alt':
            alt = True
    except:
        pass
    if isInsideVehicle(player) or isClimbing(player):
        return None
    
    team = player.getTeam()
    squad = player.getSquadId()
    if isDebugEnabled('kits'):
        debugMessage('------ %s requested kit %s alt %s team %s squad %s' % (player.getName(), kit, alt, team, squad), 'kits')
    
    if player.lastKitAllocation and now() - player.lastKitAllocation <= realityserver.C('KIT_REQUEST_INTERVAL'):
        if isDebugEnabled('kits'):
            debugMessage(str(kit) + ' is not valid for ' + player.getName() + ' - too soon to request again ' + str(now() - player.lastKitAllocation) + ' < ' + str(realityserver.C('KIT_REQUEST_INTERVAL')), 'kits')
        
        return sendMessageToPlayer(player, 3241213)
    
    if not isKitRequestable(player, kit):
        return None
    
    if isDebugEnabled('kits'):
        debugMessage(str(kit) + ' is valid for ' + player.getName() + ' request', 'kits')
    
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return None
    spawnerKit(playerPos, getKitTemplate(kit, team, True, alt), team)
    addKitAllocation(player, kit)
    sendMessageToPlayer(player, 2190309)
def removeTeamAllocation(team, kit):
    trace = PRTrace('kits: removeTeamAllocation()')
    kit = getKitTemplate(kit, team)
    if kit not in g_kits_allocated:
        return None
    
    g_kits_allocated[kit] -= 1
    if g_kits_allocated[kit] < 0:
        g_kits_allocated[kit] = 0
    
    if isDebugEnabled('kits'):
        debugMessage('removed kit team allocation %s team %s (%s)' % (kit, team, g_kits_allocated[kit]), 'kits')
    
def addTeamAllocation(team, kit):
    trace = PRTrace('kits: addTeamAllocation()')
    kit = getKitTemplate(kit, team)
    if kit not in g_kits_allocated:
        return None
    
    g_kits_allocated[kit] += 1
    if g_kits_allocated[kit] < 0:
        g_kits_allocated[kit] = 0
    
    if isDebugEnabled('kits'):
        debugMessage('added kit team allocation %s team %s (%s)' % (kit, team, g_kits_allocated[kit]), 'kits')
    
def removeSquadAllocation(team, squad, kit, index):
    trace = PRTrace('kits: removeSquadAllocation()')
    if not squad and kit not in realityserver.C('KIT_LIMITS_SQUAD') or not getKitLimitSquad(kit):
        return None
    
    if index not in g_kits_squads[team][squad][kit]:
        return None
    
    g_kits_squads[team][squad][kit].remove(index)
    if isDebugEnabled('kits'):
        debugMessage('removed kit squad allocation %s team %s squad %s index %s %s' % (kit, team, squad, index, getPlayersNames(getPlayersByIndex(g_kits_squads[team][squad][kit], True))), 'kits')
    
    checkSelectedKitSquad(team, squad, kit)
def addSquadAllocation(team, squad, kit, index):
    trace = PRTrace('kits: addSquadAllocation()')
    if not squad and kit not in realityserver.C('KIT_LIMITS_SQUAD') or not getKitLimitSquad(kit):
        return None
    
    if index in g_kits_squads[team][squad][kit]:
        return None
    
    g_kits_squads[team][squad][kit].append(index)
    if isDebugEnabled('kits'):
        debugMessage('added kit squad allocation %s team %s squad %s index %s %s' % (kit, team, squad, index, getPlayersNames(getPlayersByIndex(g_kits_squads[team][squad][kit], True))), 'kits')
    
def onExitVehicle(player, vehicle):
    trace = PRTrace('kits: onExitVehicle()')
    player.lastUnarmedDropKit = (now() - realityserver.C('KIT_REQUEST_INTERVAL')) + 15
def onPlayerKilled(victim, attacker, weapon, assists, obj):
    trace = PRTrace('kits: onPlayerKilled()')
    removeKitAllocation(victim, victim.allocatedKit)
def onPlayerDeath(player, vehicle):
    trace = PRTrace('kits: onPlayerDeath()')
    removeKitAllocation(player, player.allocatedKit)
    checkSelectedKit(player)
def spawnerKit(position, template, team, spawnAbove = False):
    trace = PRTrace('kits: spawnerKit()')
    yoffset = -1.0
    if spawnAbove:
        yoffset = 2.5
    
    properties = {
        'team': team,
        'timeToLive': '300',
        'distance': '0',
        'damageWhenLost': '',
        'template': template,
        'position': (position[0], position[1] + yoffset, position[2]),
        'rotation': (0, 0, 0) }
    createSpawner(template + '_spawner_%s' % str(int(position[0]) + int(position[1]) + int(position[2])), properties)
def spawnPlayerKit(player, type):
    trace = PRTrace('kits: spawnPlayerKit()')
    
    try:
        position = player.getDefaultVehicle().getPosition()
    except:
        return None
    template = getKitTemplate(type, player.getTeam())
    spawnerKit(position, template, player.getTeam())
def spawnVehicleKit(vehicle, kit, team):
    trace = PRTrace('kits: spawnVehicleKit()')
    position = vehicle.getPosition()
    spawnerKit(position, kit, team)
def checkNinjas(data = ''):
    trace = PRTrace('kits: checkNinjas()')
    for player in getAlivePlayers():
        
        try:
            if isNinja(player):
                player.getDefaultVehicle().setDamage(100)
        continue
        continue
    
def onRemoteDropCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteDropCommand()')
    if player.killed:
        return None
    
    if player.lastUnarmedDropKit and now() - player.lastUnarmedDropKit <= realityserver.C('KIT_REQUEST_INTERVAL'):
        return sendMessageToPlayer(player, 1031121, 1)
    
    team = player.getTeam()
    player.lastUnarmedDropKit = now()
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return None
    spawnerKit(playerPos, getTeamName(team) + '_unarmed', team, True)
    sendMessageToPlayer(player, 1220118, 2)
def onRemoteCameraCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteCameraCommand()')
    if player.killed:
        return None
    
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return None
    spawnerKit(playerPos, 'pickup_camera', player.getTeam())
    debugMessage('camera kit deployed', 'kits')
def onRemoteOneFactionCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteOneFactionCommand()')
    if realityserver.C('KIT_FACTION_LOCKED') == 1:
        realityserver.C('KIT_FACTION_LOCKED', 0)
        debugMessage('kit faction requirements system disabled...')
    else:
        realityserver.C('KIT_FACTION_LOCKED', 1)
        debugMessage('kit faction requirements system enabled...')
def onRemoteKitsCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteKitsCommand()')
    if player.killed:
        return None
    
    
    try:
        team = int(args[0])
        if team not in [
            1,
            2]:
            team = player.getTeam()
    except:
        team = player.getTeam()
    teamName = getTeamName(team)
    if teamName not in realityserver.C('KIT_LIMITS'):
        return None
    
    kits = []
    for type in realityserver.C('KIT_LIMITS')[teamName].keys():
        kits.append(getKitTemplate(type, team))
        kits.append(getKitTemplate(type, team, True))
        kits.append(getKitTemplate(type, team, False, True))
        kits.append(getKitTemplate(type, team, True, True))
    
    if teamName == 'meinsurgent':
        for type in [
            'civilian',
            'insurgent1',
            'insurgent2',
            'insurgent3',
            'insurgent4',
            'sapper']:
            kits.append(getKitTemplate(type, team))
        
    else:
        for type in [
            'rifleman']:
            kits.append(getKitTemplate(type, team))
            kits.append(getKitTemplate(type, team, True))
            kits.append(getKitTemplate(type, team, False, True))
            kits.append(getKitTemplate(type, team, True, True))
        
    kits.sort()
    final = []
    for kit in kits:
        if kit not in final:
            final.append(kit)
            continue
    
    count = 2
    for kit in final:
        if isDebugEnabled('kits'):
            debugMessage('spawning kit %s' % kit, 'kits')
        
        spawnerKit(getPositionFromPlayer(player, count), kit, team)
        count += 2
    
def onRemoteNinjaCommand(player, cmd, args):
    trace = PRTrace('kits: onRemoteNinjaCommand()')
    if player.killed:
        return None
    
    tmp = 'pickup_ninja'
    
    try:
        if int(args[0].strip()) == 1:
            tmp += '_alt'
    except:
        pass
    
    try:
        playerPos = player.getDefaultVehicle().getPosition()
    except:
        return None
    spawnerKit(playerPos, tmp, player.getTeam())
    debugMessage('ninja kit deployed', 'kits')
def onKitInit(player, cmd, args):
    trace = PRTrace('kits: onKitInit()')
    team = int(args[0])
    kitIndex = int(args[1])
    if g_kits_slots[team][kitIndex] is not None:
        return None
    
    kitSlot = KitSlot()
    kitSlot.Primary = args[2]
    kitSlot.Secondary = args[3]
    kitSlot.Soldier = args[4]
    if getGameMode() == 'vehicles':
        kitSlot.LimitationsEnabled = False
    else:
        kitSlot.LimitationsEnabled = True
    if kitSlot.Primary.find('_') != -1:
        kitSlot.Name = kitSlot.Primary.split('_')[1]
    
    g_kits_slots[team][kitIndex] = kitSlot
def onCustomKitSelect(player, cmd, args):
    trace = PRTrace('kits: onCustomKitSelect()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    team = player.getTeam()
    player.customSelection[team][int(args[0])] = int(args[1])
def modifySpawn(player):
    trace = PRTrace('kits: modifySpawn()')
    team = player.getTeam()
    for kitIndex in range(7):
        kit = g_kits_slots[team][kitIndex].Primary
        if player.customSelection[team][kitIndex] == 1:
            kit = g_kits_slots[team][kitIndex].Secondary
        
        soldier = g_kits_slots[team][kitIndex].Soldier
        if kit == 'empty':
            continue
        
        host.rcon_invoke('gameLogic.setKit %s %s %s %s' % (team, kitIndex, kit, soldier))
    



# File: r (Python 2.3)
import host
import bf2
from game.realityconfig_common import PRSPECTATORS
from game.realityprofiler import PRTrace
from game.realitydebug import PRDEBUG_DEVS, isDebugEnabled, debugMessage
gameStatus = 0
events = {
    'ControlPointChangedOwner': (2, [], '(controlPointObject, attackingTeamID)'),
    'PlayerTeamDamagePoint': (2, [], '(playerObject, victimSoldierObject)'),
    'PlayerUnlocksResponse': (3, [], '(succeeded, player, unlocks)'),
    'PlayerStatsResponse': (3, [], '(succeeded, player, response)'),
    'PlayerGiveAmmoPoint': (2, [], '(givingPlayerObject, receivingPhysicalObject)'),
    'DeployGrapplingHook': (1, [], '(player)'),
    'TicketLimitReached': (2, [], '(team, limitID)'),
    'ConsoleSendCommand': (2, [], '(command, args)'),
    'ChangedSquadLeader': (3, [], '(squadID, oldLeaderPlayerObject, newLeaderPlayerObject)'),
    'PlayerChangedSquad': (3, [], '(playerObject, oldSquadID, newSquadID)'),
    'PlayerChangeWeapon': (3, [], '(playerObject, oldWeaponObject, newWeaponObject)'),
    'PlayerRepairPoint': (2, [], '(givingPlayerObject, receivingVehicleObject)'),
    'PlayerChangeTeams': (2, [], '(playerObject, humanHasSpawned)'),
    'ChangedCommander': (3, [], '(teamID, oldCommanderPlayerObject, newCommanderPlayerObject)'),
    'PlayerDisconnect': (1, [], '(playerObject)'),
    'TimeLimitReached': (1, [], '(value)'),
    'VehicleDestroyed': (2, [], '(vehicleObject, attackerObject)'),
    'PlayerHealPoint': (2, [], '(givingPlayerObject, receivingSoldierObject)'),
    'DeployTactical': (1, [], '(player)'),
    'PlayerRevived': (2, [], '(revivedPlayerObject, medicPlayerObject)'),
    'PlayerConnect': (1, [], '(player)'),
    'DeployZipLine': (1, [], '(player)'),
    'RemoteCommand': (2, [], '(playerId, cmd)'),
    'ClientCommand': (3, [], '(command, issuerPlayerObject, args)'),
    'EnterVehicle': (3, [], '(player, vehicle, freeSoldier = False)'),
    'PlayerKilled': (5, [], '(victimPlayerObject, attackerPlayerObject, weaponObject, assists, victimSoldierObject)'),
    'PlayerBanned': (3, [], '(playerObject, times, type)'),
    'PlayerKicked': (1, [], '(playerObject)'),
    'ExitVehicle': (2, [], '(player, vehicle)'),
    'PlayerSpawn': (2, [], '(player, soldier)'),
    'PlayerDeath': (2, [], '(playerObject, soldierObject)'),
    'PlayerScore': (2, [], '(playerObject, difference)'),
    'ChatMessage': (4, [], '(playerId, text, channel, flags)'),
    'PickupKit': (2, [], '(playerObject, kitObject)'),
    'DropKit': (2, [], '(playerObject, kitObject)'),
    'Reset': (1, [], '(data)'),
    'ValidatePlayerNameResponse': (5, [], '(realNick, oldNick, realPID, oldPID, player)'),
    'AttackRequest': (1, [], '(player)'),
    'ExtractRequest': (2, [], '(player, mode)'),
    'MineRequest': (1, [], '(player)'),
    'SupplyRequest': (1, [], '(player)'),
    'AmmoRequest': (1, [], '(player)'),
    'MedicRequest': (1, [], '(player)'),
    'RepairRequest': (1, [], '(player)'),
    'FireRequest': (1, [], '(player)'),
    'MutinyRequest': (1, [], '(player)'),
    'SupportRequest': (2, [], '(player, mode)'),
    'StatusRequest': (2, [], '(player, mode)'),
    'PositionMarked': (4, [], '(mark, team, position, args)'),
    'PickupFirstKit': (2, [], '(player, kit)'),
    'DropFirstKit': (2, [], '(player, kit)'),
    'PickupRevivedKit': (2, [], '(player, kit)'),
    'DropRevivedKit': (2, [], '(player, kit)'),
    'PlayerSuicided': (2, [], '(victimPlayerObject, weaponObject)'),
    'PlayerKilledFiltered': (5, [], '(victimPlayerObject, attackerPlayerObject, weaponObject, assists, victimSoldierObject)'),
    'PlayerTeamKilled': (5, [], '(victimPlayerObject, attackerPlayerObject, weaponObject, assists, victimSoldierObject)'),
    'PlayerEnemyKilled': (5, [], '(victimPlayerObject, attackerPlayerObject, weaponObject, assists, victimSoldierObject)'),
    'VehicleSpawned': (1, [], '(vehicleObject)'),
    'VehicleDestroyedFiltered': (2, [], '(vehicleObject, attackerObject)'),
    'TeamVehicleDestroyed': (2, [], '(vehicleObject, attackerObject)'),
    'EnemyVehicleDestroyed': (2, [], '(vehicleObject, attackerObject)'),
    'ChatMessageFiltered': (4, [], '(player, text, channel, flags)'),
    'TicketsChanged': (3, [], '(team, tickets, remaining)'),
    'RoundStart': (0, [], '()'),
    'RoundEnd': (1, [], '(winner)'),
    'ControlPointNeutralized': (3, [], '(cp, team, players)'),
    'ControlPointCaptured': (3, [], '(cp, team, players)'),
    'PositionDefended': (2, [], '(team, player)'),
    'AssetDeployed': (2, [], '(assetType, player)'),
    'AssetDefended': (2, [], '(assetType, player)'),
    'EnterControlPoint': (2, [], '(player, cp)'),
    'ExitControlPoint': (2, [], '(player, cp)'),
    'PositionsUpdated': (1, [], '(positions)'),
    'PlayerForgave': (1, [], '(player)'),
    'PlayerPunished': (1, [], '(player)'),
    'OutpostEnabled': (1, [], '(outpost)'),
    'OutpostDisabled': (1, [], '(outpost)'),
    'RemoteCommandIntel': (3, [], '(player, cmd, args)'),
    'RemoteCommandPhase': (3, [], '(player, cmd, args)'),
    'RemoteCommandKitRequest': (3, [], '(player, cmd, args)'),
    'RemoteCommandAssetRequest': (3, [], '(player, cmd, args)'),
    'RemoteCommandRallyRequest': (3, [], '(player, cmd, args)'),
    'RemoteCommandGiveUp': (3, [], '(player, cmd, args)'),
    'RemoteCommandDone': (3, [], '(player, cmd, args)'),
    'RemoteCommandHealth': (3, [], '(player, cmd, args)'),
    'RemoteCommandSize': (3, [], '(player, cmd, args)'),
    'RemoteCommandTemplate': (3, [], '(player, cmd, args)'),
    'RemoteCommandDebug': (3, [], '(player, cmd, args)'),
    'RemoteCommandDestroyables': (3, [], '(player, cmd, args)'),
    'RemoteCommandControlPoint': (3, [], '(player, cmd, args)'),
    'RemoteCommandDistance': (3, [], '(player, cmd, args)'),
    'RemoteCommandRequestMark': (3, [], '(player, cmd, args)'),
    'RemoteCommandSpottedMark': (3, [], '(player, cmd, args)'),
    'RemoteCommandTeleport': (3, [], '(player, cmd, args)'),
    'RemoteCommandClosest': (3, [], '(player, cmd, args)'),
    'RemoteCommandKillStreak': (3, [], '(player, cmd, args)'),
    'RemoteCommandCamera': (3, [], '(player, cmd, args)'),
    'RemoteCommandNinja': (3, [], '(player, cmd, args)'),
    'RemoteCommandKits': (3, [], '(player, cmd, args)'),
    'RemoteCommandOneFaction': (3, [], '(player, cmd, args)'),
    'RemoteCommandDrop': (3, [], '(player, cmd, args)'),
    'RemoteCommandSelectKit': (3, [], '(player, cmd, args)'),
    'RemoteCommandCustomKit': (3, [], '(player, cmd, args)'),
    'RemoteCommandInitKit': (3, [], '(player, cmd, args)'),
    'RemoteCommandLocalization': (3, [], '(player, cmd, args)'),
    'RemoteCommandProfiler': (3, [], '(player, cmd, args)'),
    'RemoteCommandPoints': (3, [], '(player, cmd, args)'),
    'RemoteCommandModded': (3, [], '(player, cmd, args)'),
    'RemoteCommandBlacklist': (3, [], '(player, cmd, args)'),
    'RemoteCommandServer': (3, [], '(player, cmd, args)'),
    'RemoteCommandMap': (3, [], '(player, cmd, args)'),
    'RemoteCommandSpawner': (3, [], '(player, cmd, args)'),
    'RemoteCommandSpawners': (3, [], '(player, cmd, args)'),
    'RemoteCommandVehicles': (3, [], '(player, cmd, args)'),
    'RemoteCommandSpectator': (3, [], '(player, cmd, args)'),
    'RemoteCommandGameplayMark': (3, [], '(player, cmd, args)'),
    'RemoteCommandMod': (3, [], '(player, cmd, args)'),
    'RemoteCommandGameplayRequest': (3, [], '(player, cmd, args)') }
arguments = [
    None,
    None,
    None,
    None,
    None]
def init(debugger = False):
    host.registerGameStatusHandler(onGameStatusChanged)
    host.registerHandler('ControlPointChangedOwner', onControlPointChangedOwner, 1)
    host.registerHandler('PlayerTeamDamagePoint', onPlayerTeamDamagePoint, 1)
    host.registerHandler('PlayerUnlocksResponse', onPlayerUnlocksResponse, 1)
    host.registerHandler('PlayerStatsResponse', onPlayerStatsResponse, 1)
    host.registerHandler('PlayerGiveAmmoPoint', onPlayerGiveAmmoPoint, 1)
    host.registerHandler('DeployGrapplingHook', onDeployGrapplingHook, 1)
    host.registerHandler('TicketLimitReached', onTicketLimitReached, 1)
    host.registerHandler('ConsoleSendCommand', onConsoleSendCommand, 1)
    host.registerHandler('ChangedSquadLeader', onChangedSquadLeader, 1)
    host.registerHandler('PlayerChangedSquad', onPlayerChangedSquad, 1)
    host.registerHandler('PlayerChangeWeapon', onPlayerChangeWeapon, 1)
    host.registerHandler('PlayerRepairPoint', onPlayerRepairPoint, 1)
    host.registerHandler('PlayerChangeTeams', onPlayerChangeTeams, 1)
    host.registerHandler('ChangedCommander', onChangedCommander, 1)
    host.registerHandler('PlayerDisconnect', onPlayerDisconnect, 1)
    host.registerHandler('TimeLimitReached', onTimeLimitReached, 1)
    host.registerHandler('VehicleDestroyed', onVehicleDestroyed, 1)
    host.registerHandler('PlayerHealPoint', onPlayerHealPoint, 1)
    host.registerHandler('DeployTactical', onDeployTactical, 1)
    host.registerHandler('PlayerRevived', onPlayerRevived, 1)
    host.registerHandler('PlayerConnect', onPlayerConnect, 1)
    host.registerHandler('DeployZipLine', onDeployZipLine, 1)
    host.registerHandler('RemoteCommand', onRemoteCommand, 1)
    host.registerHandler('ClientCommand', onClientCommand, 1)
    host.registerHandler('EnterVehicle', onEnterVehicle, 1)
    host.registerHandler('PlayerKilled', onPlayerKilled, 1)
    host.registerHandler('PlayerBanned', onPlayerBanned, 1)
    host.registerHandler('PlayerKicked', onPlayerKicked, 1)
    host.registerHandler('ExitVehicle', onExitVehicle, 1)
    host.registerHandler('PlayerSpawn', onPlayerSpawn, 1)
    host.registerHandler('PlayerDeath', onPlayerDeath, 1)
    host.registerHandler('PlayerScore', onPlayerScore, 1)
    host.registerHandler('ChatMessage', onChatMessage, 1)
    host.registerHandler('PickupKit', onPickupKit, 1)
    host.registerHandler('DropKit', onDropKit, 1)
    host.registerHandler('Reset', onReset, 1)
    if not debugger:
        host.registerHandler('ValidatePlayerNameResponse', onValidatePlayerNameResponse, 1)
    
    host.registerHandler('PickupKit', onCustomPickupKit, 1)
    host.registerHandler('PickupKit', onRevivedPickupKit, 1)
    host.registerHandler('DropKit', onCustomDropKit, 1)
    host.registerHandler('DropKit', onRevivedDropKit, 1)
    host.registerHandler('RemoteCommand', onFilteredRemoteCommand, 1)
    host.registerHandler('ClientCommand', onPunishmentCommand, 1)
    host.registerHandler('ChatMessage', onFilteredChatMessage, 1)
    host.registerHandler('VehicleDestroyed', onVehicleSpawned, 1)
    host.registerHandler = newRegisterHandler
    host.unregisterHandler = unregisterHandler
def newRegisterHandler(event, function, optional = 0):
    if not events.has_key(event):
        if isDebugEnabled():
            debugMessage('events: ERROR! ' + event + ' event does not exist')
        
        return None
    elif function.func_code.co_argcount != events[event][0] and function.__class__ == init.__class__:
        if isDebugEnabled():
            debugMessage('events: ERROR! ' + function.func_name + ' in ' + getFileName(function.func_code.co_filename) + ' wrong # of args')
        
        return None
    else:
        for handler in events[event][1]:
            if handler[0] == function:
                if isDebugEnabled('events'):
                    debugMessage('already registered ' + function.func_name + ' in ' + getFileName(function.func_code.co_filename), 'events')
                
                return None
                continue
        
    handler = (function, optional)
    events[event][1].append(handler)
    if isDebugEnabled('events'):
        debugMessage('registered ' + function.func_name + ' in ' + getFileName(function.func_code.co_filename), 'events')
    
def unregisterHandler(function):
    for event in events.items():
        for handler in event[1][1]:
            if handler[0] == function:
                
                try:
                    event[1][1].remove(handler)
                    if isDebugEnabled('events'):
                        debugMessage('unregistered ' + function.func_name + ' in ' + getFileName(function.func_code.co_filename), 'events')
                    
                    return None
                if isDebugEnabled():
                    debugMessage('events: ERROR! Unregister ' + function.func_name)
                
                continue
            isDebugEnabled()
        
    
    if isDebugEnabled():
        debugMessage('events: ERROR! Unregister ' + function.func_name + ' does not exist')
    
def getFileName(path):
    s = '\\'
    if path.count(s) == 0:
        s = '/'
    
    arr = path.split(s)
    return str(arr.pop())
def sendToHandlers(event, extraLocals):
    
    try:
        if 'trace' in extraLocals:
            del extraLocals['trace']
    except:
        pass
    for function in event[1]:
        if function[1] == 0 and gameStatus != 1:
            return None
        
        handler = function[0]
        localsNamespace = dict(extraLocals)
        localsNamespace.update(locals())
        if not isDebugEnabled('events'):
            
            try:
                eval('handler' + event[2], globals(), localsNamespace)
            except Exception:
                err = None
                trace = PRTrace('events: ERROR! ' + handler.func_name + ' in ' + getFileName(handler.func_code.co_filename))
                trace = PRTrace('events: ERROR! ' + str(err))
                if isDebugEnabled():
                    debugMessage('events: ERROR! ' + handler.func_name + ' in ' + getFileName(handler.func_code.co_filename))
                    debugMessage('events: ERROR! ' + str(err))
                
            except:
                isDebugEnabled()
            
        eval('handler' + event[2], globals(), localsNamespace)
    
def onGameStatusChanged(status):
    global gameStatus
    if status == 1:
        gameStatus = status
    else:
        gameStatus = 0
def getEvents(name):
    
    try:
        return events[name]
    except:
        pass
import realityserver
def requestSpamBlocker(player):
    if not player or not player.isValid():
        return None
    
    times = int(host.timer_getWallTime())
    reset = False
    if not (player.lastRequest):
        reset = True
    elif player.canRequest == 1 and times - player.lastRequest > realityserver.C('SPAM_INTERVAL'):
        reset = True
    elif player.canRequest == 0 and times - player.lastRequest > realityserver.C('SPAM_PENALTY'):
        reset = True
    
    if reset:
        player.lastRequest = times
        player.requestCounter = 0
        player.canRequest = 1
    
    if player.requestCounter >= realityserver.C('SPAM_LIMIT'):
        return None
    
    player.requestCounter += 1
    if player.requestCounter == realityserver.C('SPAM_LIMIT'):
        player.canRequest = 0
        player.lastRequest = times
        if isDebugEnabled('events'):
            debugMessage('spam blocked ' + player.getName(), 'events')
        
        return True
    
def onPlayerConnect(player):
    event = getEvents('PlayerConnect')
    sendToHandlers(event, locals())
def onPlayerSpawn(player, soldier):
    event = getEvents('PlayerSpawn')
    sendToHandlers(event, locals())
def onRemoteCommand(playerId, cmd):
    event = getEvents('RemoteCommand')
    sendToHandlers(event, locals())
def onPlayerChangeTeams(playerObject, humanHasSpawned):
    event = getEvents('PlayerChangeTeams')
    sendToHandlers(event, locals())
def onPlayerChangeWeapon(playerObject, oldWeaponObject, newWeaponObject):
    event = getEvents('PlayerChangeWeapon')
    sendToHandlers(event, locals())
def onPlayerChangedSquad(playerObject, oldSquadID, newSquadID):
    event = getEvents('PlayerChangedSquad')
    sendToHandlers(event, locals())
def onPlayerScore(playerObject, difference):
    event = getEvents('PlayerScore')
    sendToHandlers(event, locals())
def onPlayerHealPoint(givingPlayerObject, receivingSoldierObject):
    event = getEvents('PlayerHealPoint')
    sendToHandlers(event, locals())
def onPlayerRepairPoint(givingPlayerObject, receivingVehicleObject):
    event = getEvents('PlayerRepairPoint')
    sendToHandlers(event, locals())
def onPlayerGiveAmmoPoint(givingPlayerObject, receivingPhysicalObject):
    event = getEvents('PlayerGiveAmmoPoint')
    sendToHandlers(event, locals())
def onPlayerTeamDamagePoint(playerObject, victimSoldierObject):
    event = getEvents('PlayerTeamDamagePoint')
    sendToHandlers(event, locals())
def onPlayerKilled(victimPlayerObject, attackerPlayerObject, weaponObject, assists, victimSoldierObject):
    event = getEvents('PlayerKilled')
    sendToHandlers(event, locals())
def onPlayerRevived(revivedPlayerObject, medicPlayerObject):
    event = getEvents('PlayerRevived')
    sendToHandlers(event, locals())
def onPlayerDeath(playerObject, soldierObject):
    event = getEvents('PlayerDeath')
    sendToHandlers(event, locals())
def onEnterVehicle(player, vehicle, freeSoldier = False):
    event = getEvents('EnterVehicle')
    sendToHandlers(event, locals())
def onExitVehicle(player, vehicle):
    event = getEvents('ExitVehicle')
    sendToHandlers(event, locals())
def onPlayerBanned(playerObject, times, type):
    event = getEvents('PlayerBanned')
    sendToHandlers(event, locals())
def onPlayerKicked(playerObject):
    event = getEvents('PlayerKicked')
    sendToHandlers(event, locals())
def onPlayerDisconnect(playerObject):
    event = getEvents('PlayerDisconnect')
    sendToHandlers(event, locals())
def onVehicleDestroyed(vehicleObject, attackerObject):
    event = getEvents('VehicleDestroyed')
    sendToHandlers(event, locals())
def onPickupKit(playerObject, kitObject):
    event = getEvents('PickupKit')
    sendToHandlers(event, locals())
def onDropKit(playerObject, kitObject):
    event = getEvents('DropKit')
    sendToHandlers(event, locals())
def onReset(data):
    event = getEvents('Reset')
    sendToHandlers(event, locals())
def onValidatePlayerNameResponse(realNick, oldNick, realPID, oldPID, player):
    event = getEvents('ValidatePlayerNameResponse')
    sendToHandlers(event, locals())
def onChangedCommander(teamID, oldCommanderPlayerObject, newCommanderPlayerObject):
    event = getEvents('ChangedCommander')
    sendToHandlers(event, locals())
def onChangedSquadLeader(squadID, oldLeaderPlayerObject, newLeaderPlayerObject):
    event = getEvents('ChangedSquadLeader')
    sendToHandlers(event, locals())
def onControlPointChangedOwner(controlPointObject, attackingTeamID):
    event = getEvents('ControlPointChangedOwner')
    sendToHandlers(event, locals())
def onTimeLimitReached(value):
    event = getEvents('TimeLimitReached')
    sendToHandlers(event, locals())
def onTicketLimitReached(team, limitID):
    event = getEvents('TicketLimitReached')
    sendToHandlers(event, locals())
def onConsoleSendCommand(command, args):
    event = getEvents('ConsoleSendCommand')
    sendToHandlers(event, locals())
def onClientCommand(command, issuerPlayerObject, args):
    event = getEvents('ClientCommand')
    sendToHandlers(event, locals())
def onPlayerUnlocksResponse(succeeded, player, unlocks):
    event = getEvents('PlayerUnlocksResponse')
    sendToHandlers(event, locals())
def onChatMessage(playerId, text, channel, flags):
    event = getEvents('ChatMessage')
    sendToHandlers(event, locals())
def onPlayerStatsResponse(succeeded, player, response):
    event = getEvents('PlayerStatsResponse')
    sendToHandlers(event, locals())
def onDeployGrapplingHook(player):
    event = getEvents('DeployGrapplingHook')
    sendToHandlers(event, locals())
def onDeployZipLine(player):
    event = getEvents('DeployZipLine')
    sendToHandlers(event, locals())
def onDeployTactical(player):
    event = getEvents('DeployTactical')
    sendToHandlers(event, locals())
def onFilteredChatMessage(playerId, text, channel, flags):
    if playerId == -1:
        playerId = 255
    
    
    try:
        player = bf2.playerManager.getPlayerByIndex(playerId)
        if not player or not player.isValid():
            return None
    except:
        return None
    text = text.replace('HUD_TEXT_CHAT_COMMANDER', '')
    text = text.replace('HUD_TEXT_CHAT_TEAM', '')
    text = text.replace('HUD_TEXT_CHAT_SQUAD', '')
    text = text.replace('HUD_CHAT_DEADPREFIX', '')
    text = text.replace('* ', '')
    text = text.strip()
    args = text.lower().split(' ')
    
    try:
        if args[0] != 'rcon':
            event = getEvents('ChatMessageFiltered')
            sendToHandlers(event, locals())
        else:
            text = text.replace('rcon ', '')
            onFilteredRemoteCommand(playerId, text)
    except:
        pass
def onFilteredRemoteCommand(playerId, text):
    if playerId == -1:
        playerId = 255
    
    text = text.lower()
    args = text.split(' ')
    cmd = args[0]
    args.pop(0)
    
    try:
        player = bf2.playerManager.getPlayerByIndex(playerId)
        if not player or not player.isValid():
            return None
    except:
        return None
    spam = False
    debug = False
    dev = False
    if cmd == 'intel':
        e = 'RemoteCommandIntel'
        debug = True
    elif cmd == 'phase':
        e = 'RemoteCommandPhase'
        debug = True
    elif cmd == 'spawn':
        e = 'RemoteCommandKitRequest'
        spam = True
    elif cmd == 'cmdr':
        e = 'RemoteCommandAssetRequest'
        spam = True
    elif cmd == 'rally':
        e = 'RemoteCommandRallyRequest'
        spam = True
    elif cmd == 'giveup':
        e = 'RemoteCommandGiveUp'
    elif cmd == 'done':
        e = 'RemoteCommandDone'
    elif cmd == 'health':
        e = 'RemoteCommandHealth'
        debug = True
    elif cmd == 'size':
        e = 'RemoteCommandSize'
        debug = True
    elif cmd == 'tmp':
        e = 'RemoteCommandTemplate'
        debug = True
    elif cmd == 'debug':
        e = 'RemoteCommandDebug'
        dev = True
    elif cmd == 'destroyables':
        e = 'RemoteCommandDestroyables'
        debug = True
    elif cmd == 'cp':
        e = 'RemoteCommandControlPoint'
        debug = True
    elif cmd == 'distance':
        e = 'RemoteCommandDistance'
    elif cmd == 'request':
        e = 'RemoteCommandRequestMark'
        spam = True
    elif cmd == 'mark':
        e = 'RemoteCommandSpottedMark'
        spam = True
    elif cmd == 'teleport':
        e = 'RemoteCommandTeleport'
    elif cmd == 'closest':
        e = 'RemoteCommandClosest'
    elif cmd == 'killstreak':
        e = 'RemoteCommandKillStreak'
        debug = True
    elif cmd == 'camera':
        e = 'RemoteCommandCamera'
        dev = True
    elif cmd == 'ninja':
        e = 'RemoteCommandNinja'
        dev = True
    elif cmd == 'kits':
        e = 'RemoteCommandKits'
        debug = True
    elif cmd == 'onefaction':
        e = 'RemoteCommandOneFaction'
        debug = True
    elif cmd == 'drop':
        e = 'RemoteCommandDrop'
        spam = True
    elif cmd == 'select':
        e = 'RemoteCommandSelectKit'
    elif cmd == 'custom':
        e = 'RemoteCommandCustomKit'
    elif cmd == 'initkit':
        e = 'RemoteCommandInitKit'
    elif cmd == 'localization':
        e = 'RemoteCommandLocalization'
        debug = True
    elif cmd == 'profiler':
        e = 'RemoteCommandProfiler'
        debug = True
    elif cmd == 'points':
        e = 'RemoteCommandPoints'
        debug = True
    elif cmd == 'modded':
        e = 'RemoteCommandModded'
        debug = True
    elif cmd == 'blacklist':
        e = 'RemoteCommandBlacklist'
        debug = True
    elif cmd == 'sv':
        e = 'RemoteCommandServer'
        debug = True
    elif cmd == 'map':
        e = 'RemoteCommandMap'
        dev = True
    elif cmd == 'spawner':
        e = 'RemoteCommandSpawner'
        debug = True
    elif cmd == 'spawners':
        e = 'RemoteCommandSpawners'
        debug = True
    elif cmd in [
        'vehicles',
        'exit',
        'critical',
        'damage',
        'oneman',
        'start']:
        e = 'RemoteCommandVehicles'
        debug = True
    elif cmd in [
        'prbot',
        'prbot2',
        'prbot3',
        'prbot4',
        'prbot_alt']:
        e = 'RemoteCommandSpectator'
        dev = True
    elif cmd in [
        'delete',
        'uav',
        'lz',
        'target',
        'mortar',
        'cas',
        'demolish',
        'minefield',
        'spotted']:
        e = 'RemoteCommandGameplayMark'
    elif cmd in [
        'attack',
        'extract',
        'support',
        'supply',
        'repair',
        'ammo',
        'medic',
        'fire',
        'mutiny',
        'status',
        'mine']:
        e = 'RemoteCommandGameplayRequest'
        spam = True
    elif cmd in [
        'kick',
        'kill',
        'slap',
        'hurt',
        'tard',
        'move',
        'ready']:
        e = 'RemoteCommandMod'
        dev = True
    else:
        return None
    if isDebugEnabled('events'):
        debugMessage(text + ' --> ' + e, 'events')
    
    if spam:
        if requestSpamBlocker(player):
            if player and not (player.dead) and not player.isAIPlayer():
                host.sgl_sendMedalEvent(player.index, 1031406, 1)
            
        
        if player.canRequest == 0:
            if isDebugEnabled('events'):
                debugMessage(player.getName() + ' is spam blocked', 'events')
            
            return None
        
    
    if dev or debug:
        debugger = False
        if realityserver.isModdableServer() and realityserver.C('PRDEBUG_ALL') == 1:
            debugger = True
        elif realityserver.isInternetServer():
            if hasattr(player, 'hash') and player.hash in PRDEBUG_DEVS.values():
                debugger = True
            
        elif realityserver.getPlayerName(player) in PRDEBUG_DEVS:
            debugger = True
        
        if cmd in [
            'prbot'] and realityserver.getPlayerName(player) in PRSPECTATORS and realityserver.isModdableServer():
            debugger = True
        
        if not debugger:
            return None
        
        if debug and not isDebugEnabled():
            return None
        
    
    event = getEvents(e)
    sendToHandlers(event, locals())
def onPunishmentCommand(command, player, args):
    if int(command) == 100:
        event = getEvents('PlayerPunished')
        sendToHandlers(event, locals())
        return None
    
    if int(command) == 101:
        event = getEvents('PlayerForgave')
        sendToHandlers(event, locals())
        return None
    
def onRevivedPickupKit(player, kit):
    if player.revived == False:
        return None
    
    event = getEvents('PickupRevivedKit')
    sendToHandlers(event, locals())
def onRevivedDropKit(player, kit):
    if player.revived == False:
        return None
    
    event = getEvents('DropRevivedKit')
    sendToHandlers(event, locals())
def onCustomPickupKit(player, kit):
    if not hasattr(player, 'pickupKit'):
        player.pickupKit = 0
    
    player.pickupKit += 1
    if player.pickupKit > 1:
        return None
    
    event = getEvents('PickupFirstKit')
    sendToHandlers(event, locals())
def onCustomDropKit(player, kit):
    if player.pickupKit > 1:
        return None
    
    event = getEvents('DropFirstKit')
    sendToHandlers(event, locals())
def onVehicleSpawned(vehicle, attacker):
    if vehicle.templateName != 'SpawnerEvent':
        return None
    
    realSpawn = vehicle.getParent()
    event = getEvents('VehicleSpawned')
    sendToHandlers(event, {
        'vehicleObject': realSpawn })





Вот я пытался расставить код:
# Customization script 0.2
# By Hjid
global g_kits_slots
import host
import bf2
import random
import copy
import events
from game.events import onFilteredRemoteCommand
#from gamestatus import GameStatus
# Team names
g_kits_slots = None
g_team_names = []
# init
def init():
    host.registerGameStatusHandler(onGameStatusChanged)
    host.registerHandler("PlayerConnect", onPlayerConnect, 1)
    host.registerHandler("RemoteCommand", onFilteredRemoteCommand, 1)
    host.registerHandler('PlayerSpawn', onPlayerSpawn)
    host.registerHandler('RemoteCommandSelectKit', onKitSelected)
    host.registerHandler('RemoteCommandCustomKit', onCustomKitSelect)
    host.registerHandler('RemoteCommandInitKit', onKitInit)
def onGameStatusChanged(status):
    global g_mapid, g_kits_slots, g_kits_used, g_kits_wrong, g_kits_allocated, g_kits_allocated_timer, g_kits_reset_timer, g_kits_ninja_timer, g_kits_wrong_timer
    trace = PRTrace('kits: onGameStatusChanged()')
    if status == bf2.GameStatus.Playing and reallyPlaying():
        mapid = '%s|%s|%s' % (getMapName(), getGameMode(), getMapLayer())
        if g_mapid != mapid:
            g_mapid = mapid
            g_kits_slots = {
                1: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None],
                2: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None] }
            for player in bf2.playerManager.getPlayers():
                player.customSelection = {
                    1: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0],
                    2: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0] }
def onChangedCommander(team, oldCmd, newCmd):
    trace = PRTrace('kits: onChangedCommander()')
    if newCmd:
        checkSelectedKit(newCmd)
    
    if oldCmd:
        checkSelectedKit(oldCmd)
		
			
def onPlayerConnect(player):
    trace = PRTrace('kits: onPlayerConnect()')
    cached = getPlayerByIndex(player.index)
	
def onPlayerSpawn(player, soldier):
    trace = PRTrace('kits: onPlayerSpawn()')
    if player.isAIPlayer():
        return None
    
    modifySpawn(player)
    times = True
    if player.selectedKit in unlimitedKits:
        times = False
    
    addKitAllocation(player, player.selectedKit, times)
def onKitSelected(player, cmd, args):
    trace = PRTrace('kits: onKitSelected()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    
    try:
        slot = int(args[0].strip())
    except:
        return None
    team = player.getTeam()
    squad = player.getSquadId()
    inherit = False
    kit = getKitSlot(team, slot)
    if isKitReservedByPlayer(team, squad, player.selectedKit, player):
        removeKitReservations(player)
        inherit = copy(player.selectedKit)
    
    player.selectedKit = kit
    checkSelectedKit(player)
    if inherit:
        checkSelectedKitSquad(team, squad, inherit, player)
def onKitInit(player, cmd, args):
    trace = PRTrace('kits: onKitInit()')
    team = int(args[0])
    kitIndex = int(args[1])
    if g_kits_slots[team][kitIndex] is not None:
        return None
    
    kitSlot = KitSlot()
    kitSlot.Primary = args[2]
    kitSlot.Secondary = args[3]
    kitSlot.Soldier = args[4]
    if getGameMode() == 'vehicles':
        kitSlot.LimitationsEnabled = False
    else:
        kitSlot.LimitationsEnabled = True
    if kitSlot.Primary.find('_') != -1:
        kitSlot.Name = kitSlot.Primary.split('_')[1]
    
    g_kits_slots[team][kitIndex] = kitSlot
def onCustomKitSelect(player, cmd, args):
    trace = PRTrace('kits: onCustomKitSelect()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    team = player.getTeam()
    player.customSelection[team][int(args[0])] = int(args[1])
def modifySpawn(player):
    trace = PRTrace('kits: modifySpawn()')
    team = player.getTeam()
    for kitIndex in range(7):
        kit = g_kits_slots[team][kitIndex].Primary
        if player.customSelection[team][kitIndex] == 1:
            kit = g_kits_slots[team][kitIndex].Secondary
        
        soldier = g_kits_slots[team][kitIndex].Soldier
        if kit == 'empty':
            continue
        
        host.rcon_invoke('gameLogic.setKit %s %s %s %s' % (team, kitIndex, kit, soldier))

events.py
# Customization script 0.2
# By Hjid
global g_kits_slots
import host
import bf2
import random
import copy
import events
from game.events import onFilteredRemoteCommand
#from gamestatus import GameStatus
# Team names
g_kits_slots = None
g_team_names = []
# init
def init():
    host.registerGameStatusHandler(onGameStatusChanged)
    host.registerHandler("PlayerConnect", onPlayerConnect, 1)
    host.registerHandler("RemoteCommand", onFilteredRemoteCommand, 1)
    host.registerHandler('PlayerSpawn', onPlayerSpawn)
    host.registerHandler('RemoteCommandSelectKit', onKitSelected)
    host.registerHandler('RemoteCommandCustomKit', onCustomKitSelect)
    host.registerHandler('RemoteCommandInitKit', onKitInit)
def onGameStatusChanged(status):
    global g_mapid, g_kits_slots, g_kits_used, g_kits_wrong, g_kits_allocated, g_kits_allocated_timer, g_kits_reset_timer, g_kits_ninja_timer, g_kits_wrong_timer
    trace = PRTrace('kits: onGameStatusChanged()')
    if status == bf2.GameStatus.Playing and reallyPlaying():
        mapid = '%s|%s|%s' % (getMapName(), getGameMode(), getMapLayer())
        if g_mapid != mapid:
            g_mapid = mapid
            g_kits_slots = {
                1: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None],
                2: [
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None] }
            for player in bf2.playerManager.getPlayers():
                player.customSelection = {
                    1: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0],
                    2: [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0] }
def onChangedCommander(team, oldCmd, newCmd):
    trace = PRTrace('kits: onChangedCommander()')
    if newCmd:
        checkSelectedKit(newCmd)
    
    if oldCmd:
        checkSelectedKit(oldCmd)
		
			
def onPlayerConnect(player):
    trace = PRTrace('kits: onPlayerConnect()')
    cached = getPlayerByIndex(player.index)
	
def onPlayerSpawn(player, soldier):
    trace = PRTrace('kits: onPlayerSpawn()')
    if player.isAIPlayer():
        return None
    
    modifySpawn(player)
    times = True
    if player.selectedKit in unlimitedKits:
        times = False
    
    addKitAllocation(player, player.selectedKit, times)
def onKitSelected(player, cmd, args):
    trace = PRTrace('kits: onKitSelected()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    
    try:
        slot = int(args[0].strip())
    except:
        return None
    team = player.getTeam()
    squad = player.getSquadId()
    inherit = False
    kit = getKitSlot(team, slot)
    if isKitReservedByPlayer(team, squad, player.selectedKit, player):
        removeKitReservations(player)
        inherit = copy(player.selectedKit)
    
    player.selectedKit = kit
    checkSelectedKit(player)
    if inherit:
        checkSelectedKitSquad(team, squad, inherit, player)
def onKitInit(player, cmd, args):
    trace = PRTrace('kits: onKitInit()')
    team = int(args[0])
    kitIndex = int(args[1])
    if g_kits_slots[team][kitIndex] is not None:
        return None
    
    kitSlot = KitSlot()
    kitSlot.Primary = args[2]
    kitSlot.Secondary = args[3]
    kitSlot.Soldier = args[4]
    if getGameMode() == 'vehicles':
        kitSlot.LimitationsEnabled = False
    else:
        kitSlot.LimitationsEnabled = True
    if kitSlot.Primary.find('_') != -1:
        kitSlot.Name = kitSlot.Primary.split('_')[1]
    
    g_kits_slots[team][kitIndex] = kitSlot
def onCustomKitSelect(player, cmd, args):
    trace = PRTrace('kits: onCustomKitSelect()')
    if not player.isValid() or player.isAIPlayer():
        return None
    
    team = player.getTeam()
    player.customSelection[team][int(args[0])] = int(args[1])
def modifySpawn(player):
    trace = PRTrace('kits: modifySpawn()')
    team = player.getTeam()
    for kitIndex in range(7):
        kit = g_kits_slots[team][kitIndex].Primary
        if player.customSelection[team][kitIndex] == 1:
            kit = g_kits_slots[team][kitIndex].Secondary
        
        soldier = g_kits_slots[team][kitIndex].Soldier
        if kit == 'empty':
            continue
        
        host.rcon_invoke('gameLogic.setKit %s %s %s %s' % (team, kitIndex, kit, soldier))

Но при запуске скрипта выдает ошибку RuntimeError: illegal event name

Это скрипт предназначен для игры Battlefield 2

Отредактировано vlad1213 (Сен. 17, 2015 18:04:51)

Офлайн

#2 Апрель 23, 2024 10:46:57

WilliamThompson
Зарегистрирован: 2024-04-23
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите пожалуйста разобраться с кодом

Pokemon Infinite Fusion

vlad1213
Здравствуйте, помогите мне пожалуйста правильно расставить код Python.Есть уже готовый код, но мне нужна лишь часть этого кода.Мне нужно что бы работали вот эти строчки: host.registerHandler(“PlayerConnect”, onPlayerConnect, 1) host.registerHandler(“RemoteCommand”, onFilteredRemoteCommand, 1) host.registerHandler('PlayerSpawn', onPlayerSpawn) host.registerHandler('RemoteCommandSelectKit', onKitSelected) host.registerHandler('RemoteCommandCustomKit', onCustomKitSelect) host.registerHandler('RemoteCommandInitKit', onKitInit)
Здравствуйте, вы смогли это исправить?
#fdf5f5

Отредактировано WilliamThompson (Апрель 23, 2024 10:48:51)

Офлайн

#3 Апрель 24, 2024 06:55:31

kiwithrifty
Зарегистрирован: 2024-04-24
Сообщения: 1
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите пожалуйста разобраться с кодом

WilliamThompson
Pokemon Infinite Fusion doodle baseball
Я думаю, что в этом коде нет ошибок, которые нужно исправлять. Вы столкнулись с какой-либо путаницей?

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version