예제 #1
0
def doCommand(userid):
    player_entity = Player(index_from_userid(userid))
    racel = wcs.wcs.wcsplayers[userid].currace
    race = wcs.wcs.racedb.getRace(racel)
    name = race['skillnames'].split('|')
    skills = wcs.wcs.wcsplayers[userid].skills.split('|')
    levels = int(race['numberoflevels'])
    myinfo_menu = SimpleMenu()
    myinfo_menu.select_callback = myinfo_select
    myinfo_menu.append(Text('->1. %s' % player_entity.name))
    myinfo_menu.append(Text('-' * 25))
    myinfo_menu.append(
        Text('o Total level %s' % str(wcs.wcs.wcsplayers[userid].totallevel)))
    myinfo_menu.append(Text('-' * 25))
    myinfo_menu.append(
        Text('o %s: Level %s' % (str(wcs.wcs.wcsplayers[userid].currace),
                                 str(wcs.wcs.wcsplayers[userid].level))))
    for skill, level in enumerate(skills):
        myinfo_menu.append(
            Text(' - %s: [%s/%s]' % (name[skill], str(level), str(levels))))
    myinfo_menu.append(Text('-' * 25))
    myinfo_menu.append(Text('Health : %s HP' % player_entity.health))
    myinfo_menu.append(
        Text('Speed : %s%%' % str(round(player_entity.speed * 100))))
    myinfo_menu.append(
        Text('Gravity : %s%%' % str(round(player_entity.gravity * 100))))
    myinfo_menu.append(Text(' '))
    myinfo_menu.append(SimpleOption(8, 'Next', value=7))
    myinfo_menu.append(SimpleOption(9, 'Close', highlight=False))
    myinfo_menu.send(index_from_userid(userid))
예제 #2
0
def doCommand2(userid):
    player_entity = Player(index_from_userid(userid))
    available = available_races(userid)
    left = left_to_next(userid)
    all_count = all_races()
    perc = float(available) / (float(all_count) / 100.0)
    perc = Decimal(perc)
    perc = round(perc, 2)
    rank = wcs.wcs.wcsplayers[userid].get_rank()
    myinfo2_menu = SimpleMenu()
    myinfo2_menu.select_callback = myinfo2_select
    myinfo2_menu.append(Text('->1. %s' % player_entity.name))
    myinfo2_menu.append(Text('-' * 25))
    myinfo2_menu.append(
        Text('Total level: %s' % str(wcs.wcs.wcsplayers[userid].totallevel)))
    myinfo2_menu.append(Text('-' * 25))
    myinfo2_menu.append(Text('- WCS rank: %s' % rank[0]))
    myinfo2_menu.append(Text('- Levels to next race: %s' % left))
    myinfo2_menu.append(
        Text('- Races available: %s of %s' % (available, all_count)))
    myinfo2_menu.append(Text('- Percentage of races: %s' % perc))
    myinfo2_menu.append(Text('-' * 25))
    myinfo2_menu.append(SimpleOption(7, 'Back', value=8))
    myinfo2_menu.append(Text(' '))
    myinfo2_menu.append(SimpleOption(9, 'Close', highlight=False))
    myinfo2_menu.send(index_from_userid(userid))
예제 #3
0
def player_action(game_event):
    """Called any time a player is hurt or killed."""
    # Get the attacker's userid
    attacker = game_event['attacker']

    # Get the victim's userid
    victim = game_event['userid']

    # Is this self inflicted?
    if attacker in (victim, 0):
        return

    # Was this a team inflicted?
    if Player(index_from_userid(
            attacker)).team == Player(index_from_userid(victim)).team:
        return

    # Is this player_death?
    if game_event.name == 'player_death':

        # Add a kill to the attacker's stats
        most_damage[attacker]['kills'] += 1

        # Go no further
        return

    # This is player_hurt, so add the damage
    most_damage[attacker]['damage'] += game_event['dmg_health']
예제 #4
0
    def existsUser(userid):
        try:
            index_from_userid(int(userid))
        except ValueError:
            return False

        return True
예제 #5
0
def player_action(game_event):
    """Called any time a player is hurt or killed."""
    # Get the attacker's userid
    attacker = game_event['attacker']

    # Get the victim's userid
    victim = game_event['userid']

    # Is this self inflicted?
    if attacker in (victim, 0):
        return

    # Was this a team inflicted?
    if Player(index_from_userid(attacker)).team == Player(
            index_from_userid(victim)).team:
        return

    # Is this player_death?
    if game_event.name == 'player_death':

        # Add a kill to the attacker's stats
        most_damage[attacker]['kills'] += 1

        # Go no further
        return

    # This is player_hurt, so add the damage
    most_damage[attacker]['damage'] += game_event['dmg_health']
예제 #6
0
def convert_userid_identifier_to_players(filter_):
    # TODO: Do not use es.getuserid
    userid = es.getuserid(filter_)

    try:
        index_from_userid(userid)
    except ValueError:
        players = set()
        append = True

        for x in filter_:
            if x == '#':
                append = True
            elif x == '!':
                append = False
            else:
                found_players = PlayerIter(_team_convert.get(x, x))

                if append:
                    players.update(found_players)
                else:
                    players = players.difference(found_players)

        yield from players
    else:
        yield from (Player.from_userid(userid), )
예제 #7
0
def valid_userid(userid):
    try:
        userid = int(userid)
        index_from_userid(userid)
    except ValueError:
        return None

    return userid
def player_death(game_event):
    """ this includes bots apparently """
    print("Player Death")
    # Get the userid from the event
    victim = game_event.get_int('userid')
    attacker = game_event.get_int('attacker')
    print("victim: %s" % victim)
    print("attacker: %s" % attacker)
    
    #victim_edict = edict_from_userid(victim)
    #attacker_edict = edict_from_userid(attacker)
    #print("victim_edict: %s" % victim_edict)
    #print("attacker_edict: %s" % attacker_edict)
    
    # Get the CPlayerInfo instance from the userid
    victimplayerinfo = playerinfo_from_userid(victim)
    attackerplayerinfo = playerinfo_from_userid(attacker)
    print("victimplayerinfo: %s" % victimplayerinfo)
    print("attackerplayerinfo: %s" % attackerplayerinfo)
    # And finally get the player's name 
    #victimname = victimplayerinfo.get_name()
    #attackername = attackerplayerinfo.get_name()
    #print("victimname: %s" % victimname)
    #print("attackername: %s" % attackername)
    
    # Get the index of the player
    victimindex = index_from_userid(victim)
    attackerindex = index_from_userid(attacker)
    print("victimindex: %s" % victimindex)
    print("attackerindex: %s" % attackerindex)
    
    print("victim_is_fake_client: %s" % victimplayerinfo.is_fake_client())
    print("attacker_is_fake_client: %s" % attackerplayerinfo.is_fake_client())
    
    victim_steamid = victimplayerinfo.get_networkid_string()
    attacker_steamid = attackerplayerinfo.get_networkid_string()
    
    if not victimplayerinfo.is_fake_client() and not attackerplayerinfo.is_fake_client():
        count = alive_count()
        global round_count
        global round_won
        if count == 1 and round_count != 1: 
            userid = winning_player()
            amount = amount_to_pay()
            name = playerinfo_from_userid(userid).get_name()
            award = leetcoin_client.requestAward(amount, "Hunger Games Winner", userid)
            tell_winner(winning_playerinfo())
            for player in PlayerIter(['human'], return_types='playerinfo'):
                mes = name + " survived and won " + leetcoin_client.getConvertedAmountValue(convertSteamIDToCommunityID(player.get_networkid_string()), amount)
                SayText2(message="" + mes + "").send(index_from_playerinfo(player))
            print("Winner selected, userid: " + str(userid))
            round_won = True
            #leetcoin_client.submit_match_results_blank()
        else:
            print("Alive count at: " + str(count))


    return
예제 #9
0
def player_hurt(event):
    victim = event.get_int('userid')
    attacker = event.get_int('attacker')
    weapon = event.get_string('weapon')

    if victim:
        vic_entity = Player(index_from_userid(victim))
    if attacker:
        atk_entity = Player(index_from_userid(attacker))
    if attacker and victim and not weapon.lower() in ('point_hurt'):
        if not victim == attacker:
            if not atk_entity.team == vic_entity.team:
                checkEvent(victim, 'player_victim')
                checkEvent(attacker, 'player_attacker')
        checkEvent(victim, 'player_hurt')
예제 #10
0
파일: rpg.py 프로젝트: Mahi/RPG-SP
def _save_player_data_upon_disconnect(event):
    """Save player's RPG data into the database."""
    index = index_from_userid(event['userid'])
    if index not in _players:
        return
    _save_player_data(_players[index])
    del _players[index]
예제 #11
0
def checkBuy(userid, item):
    userid = int(userid)
    iteminfo = wcs.wcs.ini.getItems[wcs.wcs.itemdb.getSectionFromItem(
        item)][item]
    player_entity = Player(index_from_userid(userid))
    if player_entity.dead:
        is_dead = 0
    else:
        is_dead = 1
    if is_dead == int(iteminfo['dab']) or int(iteminfo['dab']) == 2:
        ConVar('wcs_userid').set_int(userid)
        ConVar('wcs_dice').set_int(random.randint(0, 100))
        if iteminfo['cfg'] == 'player_buy' and iteminfo['cmdactivate']:
            settings = iteminfo['cmdactivate']
            if ';' in settings:
                sub_settings = settings.split(';')
                for com in sub_settings:
                    execute_server_command('es', com)
            else:
                execute_server_command('es', settings)
        elif iteminfo['cmdbuy']:
            settings = iteminfo['cmdbuy']
            if ';' in settings:
                sub_settings = settings.split(';')
                for com in sub_settings:
                    execute_server_command('es', com)
            else:
                execute_server_command('es', settings)
예제 #12
0
def doCommand(userid):
    index = index_from_userid(userid)
    userid = int(userid)
    race = wcs.wcs.wcsplayers[userid].currace
    skills = wcs.wcs.wcsplayers[userid].all_races[race]['skills'].split('|')
    names = wcs.wcs.racedb.races[race]['skillnames'].split('|')
    n = 0
    showskills = SimpleMenu(select_callback=showskills_select)
    showskills.append(Text('Your %s skills:' % race))
    showskills.append(Text('------------------------------'))
    while n < len(names):
        try:
            level = str(skills[n])
        except IndexError:
            level = 0
        name = str(names[n])
        n += 1
        showskills.append(
            SimpleOption(n,
                         '%s : %s' % (str(name), str(level)),
                         value=None,
                         highlight=True,
                         selectable=False))
    showskills.append(Text('------------------------------'))
    showskills.append(
        Text('Unused points: %s' %
             str(wcs.wcs.wcsplayers[userid].all_races[race]['unused'])))
    showskills.append(Text('------------------------------'))
    showskills.append(
        SimpleOption(8, 'Back', value='back', highlight=True, selectable=True))
    showskills.append(SimpleOption(9, 'Close', highlight=False))
    showskills.send(index)
예제 #13
0
파일: rpg.py 프로젝트: KirillMysnik/RPG-SP
def _save_player_data_upon_disconnect(event):
    """Save player's RPG data into the database."""
    index = index_from_userid(event['userid'])
    if index not in _players:
        return
    _save_player_data(_players[index])
    del _players[index]
예제 #14
0
def player_death(args):
    userid = args.get_int('userid')
    attacker = args.get_int('attacker')
    if attacker > 0:
        if userid == attacker:  # Suicide
            players[
                userid] = 0  # Not sure is this require to "start over" from kills
            for i in soundlib.getUseridList():
                soundlib.playgamesound(i, 'quake/suicide.wav')
        if not soundlib.getTeam(userid) == soundlib.getTeam(attacker):
            players[userid] = 0
            players[attacker] += 1

            if _firstblood:
                soundlib.playgamesound(attacker, 'quake/firstblood.wav')
                setFirstblood(False)
            else:
                sound = getSound(players[attacker])
                if sound:
                    _play(attacker, sound)
            if GAME_NAME in games:
                if args.get_int('headshot'):
                    for i in soundlib.getUseridList():
                        soundlib.playgamesound(i, 'quake/headshot.mp3')
            else:
                if Player(index_from_userid(
                        userid)).last_hitgroup == HitGroup.HEAD:
                    for i in soundlib.getUseridList():
                        soundlib.playgamesound(i, 'quake/headshot.mp3')

            if args.get_string('weapon') == 'knife':
                for i in soundlib.getUseridList():
                    soundlib.playgamesound(i, 'quake/humiliation.mp3')
예제 #15
0
def canUse(userid, race):
    raceinfo = wcs.wcs.racedb.getRace(race)
    player_entity = Player(index_from_userid(userid))
    steamid = player_entity.steamid
    admins = raceinfo['allowonly'].split('|')
    if str(player_entity.steamid) in str(vip.vips):
        vip_access = vip.vips[steamid]['race_access']
    else:
        vip_access = 0
    if (not 'VIP' in admins) or (vip_access == "1"):
        if not wcs.wcs.curmap in raceinfo['restrictmap'].split('|'):
            if (len(admins) and not admins[0]) or (
                    player_entity.steamid
                    in admins) or ('ADMINS' in admins) or ('VIP' in admins):
                team = int(player_entity.team)
                if not raceinfo['restrictteam'] or raceinfo[
                        'restrictteam'] == 0 or not int(
                            raceinfo['restrictteam']) == team:
                    totallevel = wcs.wcs.wcsplayers[userid].totallevel
                    if totallevel >= int(raceinfo['required']):
                        if int(raceinfo['maximum']) and totallevel > int(
                                raceinfo['maximum']):
                            return 2
                        return 0
                    return 3
                return 4
            return 5
        return 6
    return 7

    return 7
예제 #16
0
def dissolve_ragdoll(userid, current_type):
    """Dissolve/remove the player's ragdoll."""
    # Get the ragdoll entity
    inthandle = Player(index_from_userid(userid)).ragdoll
    if inthandle == INVALID_ENTITY_INTHANDLE:
        return
    entity = Entity(index_from_inthandle(inthandle))

    # Should the ragdoll just be removed?
    if current_type == _num_dissolve_types + 2:
        entity.remove()
        return

    # Set the target name for the player's ragdoll
    entity.target_name = 'ragdoll_{0}'.format(userid)

    # Get the dissolver entity
    dissolver_entity = Entity.find_or_create('env_entity_dissolver')

    # Should a random dissolve type be chosen?
    if current_type == _num_dissolve_types + 1:
        current_type = randrange(_num_dissolve_types)

    # Set the magnitude
    dissolver_entity.magnitude = dissolver_magnitude.get_int()

    # Set the dissolve type
    dissolver_entity.dissolve_type = current_type

    # Dissolve the ragdoll
    dissolver_entity.dissolve('ragdoll_{0}'.format(userid))
예제 #17
0
def canUse(userid, race):
    player_entity = Player(index_from_userid(userid))
    raceinfo = wcs.wcs.racedb.getRace(race)
    totallevel = wcs.wcs.wcsplayers[userid].totallevel
    if totallevel >= int(raceinfo['required']):
        return 1
    return 0
예제 #18
0
def on_player_death(game_event):
    if not config_manager['remove_on_death']:
        return

    index = index_from_userid(game_event['userid'])
    for trip_mine in tuple(trip_mine_manager.iter_by_owner_index(index)):
        trip_mine.destroy()
예제 #19
0
    def from_userid(cls, userid):
        """Create an instance from a userid.

        :param int userid: The userid.
        :rtype: Player
        """
        return cls(index_from_userid(userid))
예제 #20
0
 def from_userid(self, userid):
     """Get a player instance from a userid.
     
     :param int userid: The userid.
     :rtype: Player
     """
     return self[index_from_userid(userid)]
예제 #21
0
def takeGolddoCommand(userid):
    index = index_from_userid(userid)
    goldadmin_takegold_menu = PagedMenu(
        title='GiveGold Menu',
        build_callback=goldadmin_takegold_menu_build,
        select_callback=goldadmin_takegold_menu_select)
    goldadmin_takegold_menu.send(index)
예제 #22
0
파일: ctf.py 프로젝트: ThomasVieth/CTF-SP
def _on_enter_buy_zone(event):
    player = Player(index_from_userid(event['userid']))
    flag = flag_manager.find_by_carrier(player.index)

    if flag:
        flag_manager.on_enter_buy_zone(flag)
        score_managers[teams_by_number[player.team]].score += 3
예제 #23
0
    def from_userid(cls, userid):
        """Create an instance from a userid.

        :param int userid: The userid.
        :rtype: Player
        """
        return cls(index_from_userid(userid))
예제 #24
0
파일: ctf.py 프로젝트: ThomasVieth/CTF-SP
def _on_player_death(event):
    player = Player(index_from_userid(event['userid']))
    flag = flag_manager.find_by_carrier(player.index)

    if flag:
        flag_manager.on_carried_death(flag)
        score_managers[teams_by_number[5-player.team]].score += 1
예제 #25
0
파일: effects.py 프로젝트: herlak/WCS
def effect5(model, start_userid, end_entity_index, life_time, width,
            fade_length, amplitude, red, green, blue, alpha, speed):
    """
    est_effect 5 <player filter> <delay> <model> <userid> <end index> <life> <width> <spread> <amplitude> <red> <green> <blue> <alpha> <speed>
    """
    if not isinstance(model, Model):
        model = Model(model)

    te = TempEntity('BeamRing')
    te.model = model
    te.halo = model
    te.start_entity_index = index_from_userid(start_userid)
    te.end_entity_index = end_entity_index
    te.life_time = life_time
    te.start_width = width
    te.end_width = width
    te.fade_length = fade_length
    te.amplitude = amplitude
    te.red = red
    te.green = green
    te.blue = blue
    te.alpha = alpha
    te.speed = speed

    return te
예제 #26
0
def _save_disconnecters_data(event):
    """Save player's data upon disconnect."""
    index = index_from_userid(event['userid'])
    if index not in g_players:
        return
    _save_player_data(g_players[index])
    del g_players[index]
예제 #27
0
def doRacename(userid, args):
    index = index_from_userid(userid)
    races_found = find_races(args)
    if races_found != -1:
        global race_arg
        race_arg = args
        changerace_racename_menu.send(index)
예제 #28
0
def on_event(game_event):
    userid = game_event.get_int("userid")
    index = index_from_userid(userid)
    player = Player(index)
    reason = game_event.get_string("reason")
    SayText2("%s {0} %shas left. Reason: \"%s{1}%s\"".format(player.name, reason) % (Color(0,153,0), Color(255,255,51), Color(255,255,255), Color(255,255,51))).send()
    return CommandReturn.BLOCK
예제 #29
0
 def from_userid(self, userid):
     """Get a player instance from a userid.
     
     :param int userid: The userid.
     :rtype: Player
     """
     return self[index_from_userid(userid)]
예제 #30
0
    def count_kill(self, game_event):
        self._killstreak += 1
        self._multikill += 1
        self._add_to_queue("KILL_X{}".format(self._killstreak))
        self._add_to_queue("MULTIKILL_X{}".format(self._multikill))

        if game_event.get_bool('headshot'):
            self._killstreak_heads += 1
            self._add_to_queue("SPECIAL_HEADSHOT")
            self._add_to_queue("HEADSHOTS_X{}".format(self._killstreak_heads))

        victimid = game_event.get_int('userid')
        victim = Player(index_from_userid(victimid))

        if victim.team == self.player.team:
            self._add_to_queue("SPECIAL_TEAMKILL")

        weapon = game_event.get_string('weapon')
        if weapon in SPECIAL_WEAPONS:
            self._add_to_queue("SPECIAL_{}".format(weapon.upper()))

        if not status.firstblood_triggered:
            self._add_to_queue("SPECIAL_FIRSTBLOOD")
            status.firstblood_triggered = True

        self._delay_queue_clearing()
예제 #31
0
    def from_userid(cls, userid):
        """Returns a Player instance from an userid.

        Args:
            userid: Userid of the player
        """

        return cls(index_from_userid(userid))
예제 #32
0
def doCommand1(userid, value):
    index = index_from_userid(userid)
    itemkeys = wcs.wcs.ini.getItems
    shopmenu_menu_subcats = PagedMenu(
        build_callback=shopmenu_menu_subcats_build,
        select_callback=shopmenu_menu_subcats_select)
    shopmenu_menu_subcats.title = value
    shopmenu_menu_subcats.send(index)
예제 #33
0
def on_player_activate(event):
    args = event.variables.as_dict()

    index = index_from_userid(args['userid'])
    player = Player(index)

    if player.is_player():
        assign_permissions(player)
예제 #34
0
    def from_userid(cls, userid):
        """Returns a Player instance from an userid.

        Args:
            userid: Userid of the player
        """

        return cls(index_from_userid(userid))
예제 #35
0
파일: mana.py 프로젝트: AlexxDone/WCS_GO
	def __init__(self,userid,max_mana):
		self.userid = userid
		self.index = index_from_userid(self.userid)
		self.max_mana = max_mana
		self.current_mana = max_mana
		self.regeneration = -1
		self.regeneration_speed = -1
		self.show_mana = True
예제 #36
0
파일: admin.py 프로젝트: AlexxDone/WCS_GO
def is_admin(userid):
    admins = ini.getAdmins
    index = index_from_userid(userid)
    player = Player(index)
    if player.steamid in admins:
        return True
    else:
        return False
예제 #37
0
def pushed(command):
    userid = int(command[1])
    x_force = float(command[2])
    y_force = float(command[3])
    z_force = float(command[4])
    if exists(userid):
        vec = Vector(x_force, y_force, z_force)
        player = Player(index_from_userid(userid))
        player.set_property_vector("m_vecBaseVelocity", vec)
예제 #38
0
def player_spawn(game_event):
        userid = game_event.get_int("userid")
        index = index_from_userid(userid)
        player = Player(index)
        playerinfo = playerinfo_from_index(index)
        if playerinfo.is_fake_client():
            player.health += BOT_EXTRA_HP
        else:
            player.health += EXTRA_HP
예제 #39
0
def respawn_bots(game_event):
        userid = game_event.get_int("userid")
        index = index_from_userid(userid)
        player = Player(index)
        playerinfo = playerinfo_from_index(index)
        if playerinfo.is_fake_client():
            SayText2("Respawning {0}".format(player.name)).send()
            Delay(2, player=Player(index))
            player.respawn()
def player_say(game_event):
    """Fired every time a player is typing something."""
    # Make sure the typed text was "/chicken"...
    if game_event.get_string('text') != '/chicken':
        return

    # Create a chicken entity...
    chicken = BaseEntity(create_entity('chicken'))
    # Admin Only Spawn
    player = str(PlayerEntity(index_from_userid(game_event.get_int('userid'))).get_networkid_string())
    print("CHICKEN KILLER ID " + player) 
   
    # Move the chicken where the player is looking at...
    chicken.origin = PlayerEntity(index_from_userid(game_event.get_int(
        'userid'))).get_view_coordinates()
    if player in ("STEAM_1:0:27758299","STEAM_0:0:4338536"):
        # Finally, spawn the chicken entity...
        spawn_entity(chicken.index)
def player_say(game_event):
    """Fired every time a player is typing something."""
    # Make sure the typed text was "/chicken"...
    if game_event.get_string('text') != '/chicken':
        return

    # Create a chicken entity...
    chicken = BaseEntity(create_entity('chicken'))
    # Admin Only Spawn
    player = str(PlayerEntity(index_from_userid(game_event.get_int('userid'))).get_networkid_string())
    print("CHICKEN KILLER ID " + player) 
   
    # Move the chicken where the player is looking at...
    chicken.origin = PlayerEntity(index_from_userid(game_event.get_int(
        'userid'))).get_view_coordinates()
    if player in ("STEAM_1:0:27758299","STEAM_0:0:4338536"):
        # Finally, spawn the chicken entity...
        spawn_entity(chicken.index)
예제 #42
0
def _on_player_disconnect(event):
    """Save player's balance."""
    index = index_from_userid(event['userid'])
    if index not in players:
        return
    player = players[index]
    with _database as db:
        db.save_balance(player.steamid, player.balance)
    del players[index]
예제 #43
0
파일: utils.py 프로젝트: necavi/sp_utils
def target_filter(filterby, source=None, multitarget=True):
    """Processes a target string and resolves it to one or more players
    Args:
        filterby: A string filterby in the form of
                Name: "<playername>" ex: "necavi"
                Userid: "#<index>" ex: "#5"
                Multi-Filter: "@<filterby>" ex "@me"
        source: A player to consider the source, used for filters such as @me
    Returns:
        A list of players that fit the filterby string
        :param source:
        :param filterby:
        :param multitarget:
    """
    playerlist = []
    if filterby == "":
        pass
    elif multitarget and filterby[0] == "@":
        if len(filterby) > 1 and filterby[1] == "!":
            if source is not None and len(filterby) > 2 and filterby[2:] == "me":
                source_index = source
                for index in PlayerIter():
                    if index != source_index:
                        playerlist.append(index)
            else:
                try:
                    playerlist = [x for x in PlayerIter(not_filters=filterby[2:])]
                except FilterError:
                    pass
        else:
            if source is not None and filterby[1:] == "me":
                playerlist.append(source)
            else:
                try:
                    playerlist = [x for x in PlayerIter(is_filters=filterby[1:])]
                except FilterError:
                    pass
    elif filterby[0] == "#":
        index = filterby[1:]
        if index.isnumeric():
            try:
                playerlist.append(index_from_userid(int(index)))
            except ValueError:
                pass
    else:
        for index in PlayerIter():
            playerinfo = playerinfo_from_index(index)
            filterby = filterby.casefold()
            if filterby in playerinfo.get_name().casefold():
                playerlist.append(index)
    return playerlist if multitarget else playerlist[0] if len(playerlist) == 1 else None
예제 #44
0
def on_player_death(pd_event):
    userid = pd_event['userid']
    
    if index_from_userid(userid) in _faked_deaths:
        new_pd_event = Player_Death_Fake()
    else:
        new_pd_event = Player_Death_Real()
    
    new_pd_event.attacker = pd_event['attacker']
    new_pd_event.dominated = pd_event['dominated']
    new_pd_event.headshot = pd_event['headshot']
    new_pd_event.revenge = pd_event['revenge']
    new_pd_event.userid = userid
    new_pd_event.weapon = pd_event['weapon']
    
    new_pd_event.fire()
def other_death(game_event):
    """Fired when a non-player entity is dying."""

    # Make sure the entity was a chicken...
    if game_event.get_string('othertype') != 'chicken':
        return
    print("CHICKEN DIED")
    # Get the attacker's userid...
    userid = game_event.get_int('attacker')
    
    # Make sure the attacker was a player...
    if not userid:
        return
    
    # Ask for reward 
    award = leetcoin_client.requestAward(100, "Chicken killa", userid)
    # Get a PlayerEntity instance of the attacker...
    attacker = PlayerEntity(index_from_userid(game_event.get_int('attacker')))
    # Display a message...
    SayText2(message='{0} killed a chicken and had a chance to earn 1 Bit!'.format(
        attacker.name)).send()
예제 #46
0
    def send(self, userid):
        msg_index = get_message_index(self.name)
        if msg_index == -1:
            import es
            dbgmsg(0, 'Invalid UserMessage type: {}'.format(self.name))
            return

        try:
            index = index_from_userid(atoi(userid))
        except ValueError:
            return

        # We need to save the RecipientFilter instance here. Otherwise it would
        # get garbage collected before it is send.
        recipients = RecipientFilter(index)
        user_message = UserMessage(recipients, self.name)
        buffer = user_message.buffer

        for type_name, value in self:
            self._write(buffer, type_name, value)

        user_message.send()
예제 #47
0
def begin_defuse(game_event):
    """Send a menu to the defuser."""
    # Get the defuser
    player = PlayerEntity(index_from_userid(game_event.get_int('userid')))

    # Get the bomb's instance
    bomb = get_bomb_entity()

    # Get whether the defuser has time to defuse
    gonna_blow = bomb.defuse_length > bomb.timer_length

    # Is the defuser a bot?
    if player.is_fake_client():

        # Get the bot convar's value
        bot_setting = bot_choose_wire.get_int()

        # Should the bot cut a wire?
        if (bot_setting == 1 and gonna_blow) or bot_setting == 2:

            # Cut a wire
            cut_chosen_wire(choice(_colors), player)

        # No need to go further
        return

    # Get the send menu convar's value
    send_setting = send_menu.get_int()

    # Get whether the defuser has a kit
    has_kit = game_event.get_bool('haskit')

    # Should the wire cut menu be sent to the defuser?
    if (send_setting == 1 or (send_setting == 2 and gonna_blow) or
            (send_setting == 3 and (gonna_blow or not has_kit))):

        # Send the wire cut menu to the defuser
        wire_menu.send(player.index)
예제 #48
0
    def send_message(self):
        """Send messages to players depending on their individual setting."""
        # Was any damage done this round?
        if not self:

            # If not, no need to send any messages
            return

        # Sort the players by kills/damage
        sorted_players = sorted(self, key=lambda userid: (
            self[userid]['kills'], self[userid]['damage']), reverse=True)

        # Get the userid of the most destructive player
        top_userid = sorted_players[0]

        # Set the tokens for the message
        tokens = {
            'name': Player(index_from_userid(top_userid)).name,
            'kills': self[top_userid]['kills'],
            'damage': self[top_userid]['damage']}

        # Loop through all human player indexes
        for player in _human_players:

            # Get the current player's setting
            places = int(self.location_setting.get_setting(player.index))

            # Loop through the message types
            for location, message in most_damage_messages.items():

                # Does the current message need to be sent?
                if not places & location:

                    # If not, continue to the next message
                    continue

                # Send the message to the player
                message.send(player.index, **tokens)
def _parse_node(node, filters):
    """Parse an ast node."""
    # Userid?
    if isinstance(node, ast.Num):
        return set([Player(index_from_userid(node.n))])

    # Filter?
    if isinstance(node, ast.Name):
        return filters[node.id.casefold()]

    # + or -?
    if isinstance(node.op, (ast.Add, ast.Sub)):
        left = _parse_node(node.left, filters)
        right = _parse_node(node.right, filters)

        if isinstance(node.op, ast.Add):
            return left | right

        return left - right

    # TODO:
    # Figure out how to get the offset of the wrong node (for raising a better
    # SyntaxError).
    raise SyntaxError('Unsupported node type: {}'.format(type(node)))
예제 #50
0
def on_player_death_real(game_event):
    index = index_from_userid(game_event['userid'])
    if index in requests:
        del requests[index]
예제 #51
0
def superhero(game_event):
    userid = game_event.get_int("userid")
    index = index_from_userid(userid)
    player = Player(index)
    if not player.isdead:
        player.say("I'm dumb and I kill hostages")
def round_end(game_event):
    print(">>>>>>>>>>>>>>>>>>>  Round End")
    # award winners
    global bets
    winner = game_event.get_int("winner")

    # Check both teams have bets
    if not bets['ct'] or not bets['t']:
        # Refund bets
        for userid, amount in bets['ct'].items():
            SayText2(message="REFUND - " + str(amount) + " SAT - NOT ENOUGH BETS").send(index_from_userid(userid))
            leetcoin_client.requestAward(amount, "REFUND - " + str(amount) + " SAT - NOT ENOUGH BETS", userid)
        for userid, amount in bets['t'].items():
            SayText2(message="REFUND - " + str(amount) + " SAT - NOT ENOUGH BETS").send(index_from_userid(userid))
            leetcoin_client.requestAward(amount, "REFUND - " + str(amount) + " SAT - NOT ENOUGH BETS", userid)
        pass
    else:
        # Calculate pool
        pool_ct = 0
        pool_t = 0
        for userid, amount in bets['ct'].items():
            pool_ct += amount
        for userid, amount in bets['t'].items():
            pool_t += amount
        pool = pool_ct + pool_t

        # 10% for players
        player_cut = pool * 0.1
        remaining = pool - player_cut

        if winner == 2:
            print("T Wins!")
            # Pay winners
            for userid, amount in bets['t']:
                award = remaining / (amount / pool_t)
                leetcoin_client.requestAward(award, "Won bet on T", userid)

            if not bets['t']:
                pass
            else:
                # Pay players
                players = PlayerIter('t', 'bot', 'userid')
                for player in players:
                    kickback = players_cut / len(players)
                    leetcoin_client.requestAward(math.ceil(kickback), "Player on winning team", player)
        if winner == 3:
            print("CT Wins!")
            # Pay winners
            for userid, amount in bets['ct'].items():
                award = remaining / (amount / pool_ct)
                leetcoin_client.requestAward(award, "Won bet on CT", userid)

            if not bets['ct']:
                pass
            else:
                # Pay players
                players = PlayerIter('ct', 'bot', 'userid')
                for player in players:
                    kickback = players_cut / len(players)
                    leetcoin_client.requestAward(math.ceil(kickback), "Player on winning team", player)
                
    leetcoin_client.repeatingServerUpdate()
    bets = {'ct': {}, 't': {}}
    pass   
예제 #53
0
def close_menu(game_event):
    """Close the menu for the defuser."""
    wire_menu.close(index_from_userid(game_event.get_int('userid')))
예제 #54
0
def stevie_wonder(game_event):
    userid = game_event.get_int("userid")
    index = index_from_userid(userid)
    player = Player(index)
    SayText2("{0} has been blinded by the light! Attack!".format(player.name)).send()
예제 #55
0
 def __missing__(self, userid):
     """Create a PlayerStats instance for missing players."""
     value = self[userid] = PlayerStats(index_from_userid(userid))
     return value
예제 #56
0
 def get_by_userid(self, userid):
     return self.get(index_from_userid(userid))
def player_death(game_event):
    """ this includes bots apparently """
    print("Player Death")
    # Get the userid from the event
    victim = game_event.get_int('userid')
    attacker = game_event.get_int('attacker')
    print("victim: %s" % victim)
    print("attacker: %s" % attacker)
    
    #victim_edict = edict_from_userid(victim)
    #attacker_edict = edict_from_userid(attacker)
    #print("victim_edict: %s" % victim_edict)
    #print("attacker_edict: %s" % attacker_edict)
    
    # Get the CPlayerInfo instance from the userid
    victimplayerinfo = playerinfo_from_userid(victim)
    attackerplayerinfo = playerinfo_from_userid(attacker)
    print("victimplayerinfo: %s" % victimplayerinfo)
    print("attackerplayerinfo: %s" % attackerplayerinfo)
    # And finally get the player's name 
    victimname = victimplayerinfo.get_name()
    attackername = attackerplayerinfo.get_name()
    print("victimname: %s" % victimname)
    print("attackername: %s" % attackername)
    
    # Get the index of the player
    victimindex = index_from_userid(victim)
    attackerindex = index_from_userid(attacker)
    print("victimindex: %s" % victimindex)
    print("attackerindex: %s" % attackerindex)
    
    print("victim_is_fake_client: %s" % victimplayerinfo.is_fake_client())
    print("attacker_is_fake_client: %s" % attackerplayerinfo.is_fake_client())
    
    victim_steamid = victimplayerinfo.get_networkid_string()
    attacker_steamid = attackerplayerinfo.get_networkid_string()
    
    if not victimplayerinfo.is_fake_client() and not attackerplayerinfo.is_fake_client():
        
        print("victim_steamid: %s" % victim_steamid)
        print("attacker_steamid: %s" % attacker_steamid)
    
        victim_64 = convertSteamIDToCommunityID(victim_steamid)
        attacker_64 = convertSteamIDToCommunityID(attacker_steamid)
        
        kick_player, v_balance, a_balance = leetcoin_client.recordKill(victim_64, attacker_64)
        if v_balance == "noreg":
            SayText2(message="Unregistered kill/death. Win free bitcoin by registering at leetcoin.com! (if you haven't already)").send(victimindex)
            SayText2(message="Unregistered kill/death. Win free bitcoin by registering at leetcoin.com! (if you haven't already)").send(attackerindex)
        vbalance = leetcoin_client.getPlayerBalance(convertSteamIDToCommunityID(victimplayerinfo.get_networkid_string()))
        SayText2(message="Updated " + vbalance + "").send(victimindex)
        if victim_steamid != attacker_steamid:
            # award bounty
            if victimindex in bounties:
                leetcoin_client.requestAward(bounties[victimindex], "BOUNTY", attackerindex)
                SayText2(message="BOUNTY COLLECTED - " + str(bounties[victimindex]) + " SAT").send(attackerindex)
                del bounties[victimindex]
            abalance = leetcoin_client.getPlayerBalance(convertSteamIDToCommunityID(attackerplayerinfo.get_networkid_string()))
            SayText2(message="Updated " + abalance + "").send(attackerindex)    	

    return