Exemple #1
0
def _pre_damage_call_events(stack_data):
    take_damage_info = make_object(TakeDamageInfo, stack_data[1])
    if not take_damage_info.attacker:
        return
    entity = Entity(take_damage_info.attacker)
    attacker = players[entity.index] if entity.is_player() else None
    victim = players[index_from_pointer(stack_data[0])]

    event_args = {
        'attacker': attacker,
        'victim': victim,
        'take_damage_info': take_damage_info,
    }

    if attacker:
        if victim.team == attacker.team:
            attacker.hero.call_events('player_pre_teammate_attack', player=attacker,
                **event_args)
            victim.hero.call_events('player_pre_teammate_victim', player=victim, **event_args)
            return

        attacker.hero.call_events('player_pre_attack', player=attacker, **event_args)
        victim.hero.call_events('player_pre_victim', player=victim, **event_args)

        if victim.health <= take_damage_info.damage:
            attacker.hero.call_events('player_pre_death', player=victim, **event_args)
Exemple #2
0
	def player_give_weapon(self, userid):
		try:
			player = Player.from_userid(userid)
			if not player.address or player.steamid == 'BOT':
				return
			if player.team not in (2,3):
				return
			# get player team
			pteam = self.get_player_team(userid)
			pdata = self.get_player_data(userid)
			for index in player.weapon_indexes():
				weapon = Entity(index)
				player.drop_weapon(weapon.pointer, player.origin, player.origin)
				weapon.remove()
			# get new weapons
			player.give_named_item('weapon_knife', 0, None, True)
			if pteam in pdata['loadout1']:
				if str(pdata['class']) in pdata['loadout1'][pteam]:
					if 'primary' in pdata['loadout1'][pteam][str(pdata['class'])]:
						player.give_named_item(pdata['loadout1'][pteam][str(pdata['class'])]['primary'], 0, None, True)
					if 'secondary' in pdata['loadout1'][pteam][str(pdata['class'])]:
						player.give_named_item(pdata['loadout1'][pteam][str(pdata['class'])]['secondary'], 0, None, True)
					for item in self.weapons:
						if int(self.weapons[item]['rank']) <= int(pdata['rank'][str(pdata['class'])]) and int(self.weapons[item]['type']) == 3 and pteam == self.weapons[item]['team'] and int(pdata['class']) == self.weapons[item]['class']:
							for x in range(0, self.weapons[item]['amount']):
								Delay(0, player.give_named_item, self.weapons[item]['slug'], 0, None, True)
			# give kevlar (and helmet on lvl 20 or above)
			if int(pdata['rank'][str(pdata['class'])]) < 20:
				player.give_named_item('item_kevlar', 0, None, True)
			else:
				player.give_named_item('item_assaultsuit', 0, None, True)
			# ready for spawn let other plugins know
			self.callbacks.execute('player_is_spawned', player.userid)
		except:
			msg('INFO', 'could not give weapon to player')
Exemple #3
0
def dissolve_ragdoll(userid, current_type):
    """Dissolve/remove the player's ragdoll."""
    # Get the ragdoll entity
    try:
        inthandle = Player.from_userid(userid).ragdoll
    except ValueError:
        return

    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_{userid}'.format(userid=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 = magnitude.get_int()

    # Set the dissolve type
    dissolver_entity.dissolve_type = current_type

    # Dissolve the ragdoll
    dissolver_entity.dissolve('ragdoll_{userid}'.format(userid=userid))
Exemple #4
0
def _pre_damage_call_events(stack_data):
    take_damage_info = make_object(TakeDamageInfo, stack_data[1])
    if not take_damage_info.attacker:
        return
    entity = Entity(take_damage_info.attacker)
    attacker = players[entity.index] if entity.is_player() else None
    victim = players[index_from_pointer(stack_data[0])]

    event_args = {
        'attacker': attacker,
        'victim': victim,
        'take_damage_info': take_damage_info,
    }

    if attacker:
        if victim.team == attacker.team:
            attacker.hero.call_events('player_pre_teammate_attack',
                                      player=attacker,
                                      **event_args)
            victim.hero.call_events('player_pre_teammate_victim',
                                    player=victim,
                                    **event_args)
            return

        attacker.hero.call_events('player_pre_attack',
                                  player=attacker,
                                  **event_args)
        victim.hero.call_events('player_pre_victim',
                                player=victim,
                                **event_args)

        if victim.health <= take_damage_info.damage:
            attacker.hero.call_events('player_pre_death',
                                      player=victim,
                                      **event_args)
Exemple #5
0
def _pre_on_take_damage(args):
    info = make_object(TakeDamageInfo, args[1])

    entity = Entity(info.attacker) if info.attacker else None
    if entity is not None and entity.is_player():
        attacker = wcgo.player.Player(entity.index)
    else:
        attacker = None

    victim = wcgo.player.Player(index_from_pointer(args[0]))
    eargs = {
        'attacker': attacker,
        'victim': victim,
        'info': info,
    }
    # Adds the weapon argument dependent on scenario
    if attacker is not None and attacker.active_weapon != -1:
        eargs['weapon'] = Weapon(index_from_inthandle(attacker.active_weapon))
    else:
        eargs['weapon'] = None

    if attacker is None or attacker.userid == victim.userid:
        victim.hero.execute_skills('player_pre_self_injury', player=victim, **eargs)
        return
    if not (attacker.steamid == 'BOT' and attacker.hero is None):
        attacker.hero.execute_skills('player_pre_attack', player=attacker, **eargs)
    if not (victim.steamid == 'BOT' and victim.hero is None):
        victim.hero.execute_skills('player_pre_victim', player=victim, **eargs)
Exemple #6
0
    def add_item(self, item: Entity) -> List[Optional[Dict]]:
        results = []

        item_placed = False
        for i in range(self.capacity):
            if self.items[i] is None:
                self.items[i] = item
                item_placed = True
                break

        if not item_placed:
            results.append({
                "message":
                "You cannot carry any more, your inventory is full"
            })
            results.append({"play_sound": "error"})
        else:
            results.append({"message": f"You pick up the {item.name}!"})
            if "Potion" in item.name:
                results.append({"play_sound": "pickup_potion"})
            if "Scroll" in item.name:
                results.append({"play_sound": "pickup_scroll"})

            item.remove_from_sprite_lists()
            results.append({"enemy_turn": True})

        return results
Exemple #7
0
 def get_vec(value):
     if isinstance(value, int):
         return Entity(value).origin
     elif isinstance(value, BaseEntity):
         return Entity(value.index).origin
     else:
         return value
    def dying(self, target: Entity) -> list:
        """
        Handle event of an entity dying

        :param target:
        """

        target.color = colors["dying"]
        # target.visible_color = colors["dying"]
        target.is_dead = True
        if target is self.player:
            results = [{"message": "Player has died!"}]
        else:
            # If a monster dies, set up a message and add a delay
            results = [
                {
                    "message": f"{target.name} has been killed!"
                },
                {
                    "delay": {
                        "time": DEATH_DELAY,
                        "action": {
                            "dead": target
                        }
                    }
                },
            ]
        return results
Exemple #9
0
    def spawn_flag(self, vector):
        "Spawn a flag onto the map from a vector instance."
        # Creating a flag prop.
        flag = Entity.create('prop_physics_override')
        flag.origin = vector
        flag.model = Flags.STATIONARY_MODEL
        flag.spawn_flags = 265
        flag.carrier = None
        flag.home = vector
        flag.spawn()

        # Simple Effect to mark Flags.
        entity = Entity.create('env_smokestack')
        entity.teleport(vector, None, None)
        entity.base_spread = 10
        entity.spread_speed = 75
        entity.initial_state = 0
        entity.speed = 105
        entity.rate = 100
        entity.start_size = 8
        entity.end_size = 4
        entity.twist = 360
        entity.jet_length = 100
        entity.render_mode = 18
        entity.render_amt = 100
        entity.render_color = Color(3, 5, 253)
        entity.add_output('SmokeMaterial {}'.format(Flags.EFFECT_MATERIAL))
        entity.turn_on()
        entity.set_parent(self[vector].pointer, -1)

        flag.effect = entity

        self[vector] = flag
Exemple #10
0
def _pre_take_damage(stack_data):
    """Set player health/armor to allow projectile kill."""
    if GunGameStatus.MATCH is not GunGameMatchStatus.ACTIVE:
        return

    take_damage_info = make_object(TakeDamageInfo, stack_data[1])
    attacker = Entity(take_damage_info.attacker)
    if attacker.classname != 'player':
        return

    victim = make_object(Entity, stack_data[0])
    if victim.team_index == attacker.team_index:
        if 'gg_ffa' not in gg_plugin_manager:
            return

    classname = Entity(take_damage_info.weapon).classname
    if classname not in _projectile_weapons:
        return

    if 'gg_teamplay' in gg_plugin_manager and victim.team_index == attacker.team_index:
        return

    attacker = player_dictionary.from_index(attacker.index)
    if weapon_manager[classname].basename != attacker.level_weapon:
        return

    victim.health = 1
    victim.armor = 0
Exemple #11
0
    def _set_weapon_clip(self,
                         value,
                         classname=None,
                         is_filters=None,
                         not_filters=None):
        """Set the player's clip value for the given arguments.

        Sets for the first weapon found from the given arguments.
        """
        # Get the index for the given arguments
        index = self.get_weapon_index(classname, is_filters, not_filters)

        # Was no index found?
        if index is None:

            # Raise an error
            raise LookupError('No index found for given arguments '
                              '"{0}, {1}, {2}" for player "{3}"'.format(
                                  classname, is_filters, not_filters,
                                  self.userid))

        # Get the entity's Entity instance
        weapon = Entity(index)

        # Set the weapon's clip value
        weapon.clip = value
Exemple #12
0
 def __init__(self, name, beer_id, created_by):
     """
     Constructor
     """
     Entity.__init__(self, created_by)
     self.name = name
     self.beer_id = beer_id
def _player_death(game_event):
    # Dead Strip
    remove_idle_weapons(status=GunGameMatchStatus.WARMUP)

    # Dissolver
    victim = game_event['userid']
    try:
        inthandle = Player.from_userid(victim).ragdoll
    except ValueError:
        return
    if inthandle == INVALID_ENTITY_INTHANDLE:
        return
    entity = Entity(index_from_inthandle(inthandle))
    entity.target_name = f'ragdoll_{victim}'
    dissolver_entity = Entity.find_or_create('env_entity_dissolver')
    dissolver_entity.magnitude = 2
    dissolver_entity.dissolve_type = 0
    dissolver_entity.dissolve(f'ragdoll_{victim}')

    # DeathMatch
    Delay(
        delay=2,
        callback=_respawn_player,
        args=(victim,),
        cancel_on_level_end=True,
    )
Exemple #14
0
    def place_stairs(self):
        exit = find(lambda room: room.name == 'exit', self.current_level.rooms)

        if (exit):
            x, y = exit.center

            self.down_stairs = Entity(Point(x, y),
                                      '>',
                                      'Stairs',
                                      COLORS.get('stairs'),
                                      render_order=RenderOrder.STAIRS,
                                      always_visible=True)
            self.down_stairs.add_component(Stairs(self.dungeon_level + 1),
                                           "stairs")

            self.current_level.add_entity(self.down_stairs)

        entrance = find(lambda room: room.name == 'entrance',
                        self.current_level.rooms)

        if (entrance):
            x, y = entrance.center

            self.up_stairs = Entity(Point(x, y),
                                    '<',
                                    'Stairs',
                                    COLORS.get('stairs'),
                                    render_order=RenderOrder.STAIRS,
                                    always_visible=True)
            self.up_stairs.add_component(Stairs(self.dungeon_level - 1),
                                         "stairs")

            self.current_level.add_entity(self.up_stairs)
def pre_on_take_damage(args):
    # Get the victim
    victim = make_object(Player, args[0])

    # Get TakeDamageInfo object
    info = make_object(TakeDamageInfo, args[1])

    # Was it a self-inflicted damage?
    if info.attacker == victim.index:
        return

    # Check if attacker is a player
    entity = Entity(info.attacker)
    if not entity.is_player():
        return

    # Get the attacker
    attacker = Player(info.attacker)

    # Do our thing
    if attacker.is_bot() and not victim.is_bot():
        info.damage *= caches_from[victim.index].multiplier

    elif not attacker.is_bot() and victim.is_bot():
        info.damage *= caches_to[attacker.index].multiplier
Exemple #16
0
    def _on_player_pre_attack(self, attacker, victim, **kwargs):
        if randint(1, 100) > 20 or self.cooldowns['blizzard'] > 0 or self.level == 0:
            return

        self._center = victim.origin
        self._player = attacker
        self._players_hit.clear()
        self._repeater = Repeat(self._repeat)
        self._repeater.start(0.1)

        self._effect = TempEntity('BeamRingPoint', center=self._center, start_radius=self.range,
            end_radius=self.range+1, model_index=self._model.index, halo_index=self._model.index,
            life_time=7, amplitude=10, red=200, green=200, blue=255, alpha=245, flags=0,
            start_width=10, end_width=10)
        self._effect.create()

        self._stack = Entity.create('env_smokestack')

        self._stack.teleport(self._center, QAngle(0, 180, 0), None)
        self._stack.base_spread = self.range / 2
        self._stack.spread_speed = 10
        self._stack.start_size = 2
        self._stack.end_size = 1
        self._stack.jet_length = 100
        self._stack.angles = QAngle(0, 0, 0)
        self._stack.rate = 600
        self._stack.speed = 100
        self._stack.twist = 180
        self._stack.render_mode = RenderMode.TRANS_COLOR
        self._stack.render_amt = 100
        self._stack.render_color = Color(200, 200, 255)
        self._stack.add_output('SmokeMaterial particle/rain.vmt')
        self._stack.turn_on()

        self._stack2 = Entity.create('env_smokestack')

        self._stack2.teleport(self._center, None, QAngle(0, 180, 0))
        self._stack2.base_spread = self.range / 4
        self._stack2.spread_speed = self.range / 2
        self._stack2.start_size = 2
        self._stack2.end_size = 1
        self._stack2.jet_length = 100
        self._stack2.angles = QAngle(0, 180, 0)
        self._stack2.rate = 600
        self._stack2.speed = 100
        self._stack2.twist = 120
        self._stack2.render_mode = RenderMode.TRANS_COLOR
        self._stack2.render_amt = 100
        self._stack2.render_color = Color(200, 200, 255)
        self._stack2.add_output('SmokeMaterial particle/rain.vmt')
        self._stack2.turn_on()

        send_wcs_saytext_by_index(self._msg_a.format(name=victim.name), attacker.index)

        self._stack.delay(7, self._stack.turn_off)
        self._stack2.delay(7, self._stack2.turn_off)
        Delay(7, self._repeater.stop)

        self.cooldowns['blizzard'] = 10
 def __init__(self, duration, beer_id, created_by, id=None):
     """
     Constructor
     """
     Entity.__init__(self, created_by)
     self.id = id
     self.beer_id = beer_id
     self.duration = duration
 def __init__(self, name, image, beer_id, created_by, id=None):
     """
     Constructor
     """
     Entity.__init__(self, created_by)
     self.name = name
     self.image = image
     self.beer_id = beer_id
Exemple #19
0
    def __init__(self, world, team_id, team_name):
        
        Entity.__init__(self, world)

        self.c.add("team", id=team_id, name=team_name)
        self.c.add("attrs")
        self.c["attrs"].create("energy", val=0, mx=1000)
        self.c.add("inventory")
Exemple #20
0
 def __init__(self, world):
     
     Entity.__init__(self, world)
     
     # Leaves disappear after a certain number of seconds.
     self.c.add("age", lifespan=120)
     
     self.c.add("inventory", can_be_taken=True)
Exemple #21
0
def _change_model_world_model(entity):
    'Changes a weapons world model upon being created.'
    ## Technically a <BaseEntity> instance, but who cares? hehe
    if entity.classname not in worldmodel_manager:
        return
    model = worldmodel_manager[entity.classname]
    weapon = Entity(entity.index)
    weapon._set_model(model.path)
Exemple #22
0
def on_entity_spawned(base_entity):
    """Remove hostage entities and disable map entity functions as soon as they spawn."""
    if base_entity.classname == 'hostage_entity':
        base_entity.remove()

    elif base_entity.classname.startswith('func_'):
        with suppress(ValueError):
            entity = Entity(base_entity.index)
            entity.call_input('Disable')
Exemple #23
0
def on_entity_spawned(base_entity):
    """Remove forbidden entities when they have spawned."""
    if base_entity.classname in forbidden_entities:
        base_entity.remove()

    # Disable map functions as well
    elif base_entity.classname in map_functions:
        entity = Entity(base_entity.index)
        entity.call_input('Disable')
Exemple #24
0
 def __init__(self,position={"x":0,"y":0}):
     image = pygame.image.load('lib/players/playerStart.png').convert()
     rect = image.get_rect()
     Entity.__init__(self,rect,image)
     self.keyCode = 'ps'
     self.type = C.TYPE_PLAYER_START
     self.rect.left = position['x']
     self.rect.top = position['y']
     self.mass = 2
Exemple #25
0
 def test_add_new(self):
     Entity.erase_all_entities()
     an_NPC = self.new_NPC()
     a_player = self.new_player()
     a_thing = self.new_thing()
     self.assertEquals(Entity.all_NPCs, [an_NPC])
     self.assertEquals(Entity.player, a_player)
     self.assertEquals(Entity.all_things, [a_thing])
     Entity.erase_all_entities()
    def create(
        self, origin, number, color, angle, size, without_decoy=False, 
        velocity=None
    ):
        """Creates and combines a 'decoy_projectile' and a 'point_worldtext' to
        represent the FloatingNumber entity.

        The 'decoy_projectile' is used to add movement / animation to the 
        'point_worldtext'.
        """
        # Create and setup the 'point_worldtext'.
        self.world_text = Entity.create('point_worldtext')
        self.world_text.text = number
        self.world_text.text_size = size
        self.world_text.text_color = color

        # Add the FloatingNumber instance to the dictionary.
        number_instances[self.world_text.index] = self

        # Don't go further if we don't need a 'decoy_projectile'.
        if without_decoy:
            return

        # Create and setup the 'decoy_projectile'.
        self.decoy = Entity.create('decoy_projectile')
        self.decoy.spawn()
        self.decoy.gravity = 0.23
        self.decoy.color = INVISIBLE
        # Remove the 'decoy_projectile' bounce sound.
        self.decoy.set_property_uchar('movecollide', 0)
        # Make the decoy not solid.
        self.decoy.solid_type = SolidType.NONE
        self.decoy.solid_flags = SolidFlags.NOT_SOLID
        self.decoy.collision_group = CollisionGroup.NONE
        # Parent the 'point_worldtext' to the 'decoy_projectile'.
        self.world_text.set_parent(self.decoy, -1)
        self.world_text.teleport(calculate_offset(number, size), None, None)
        # Strip the FL_EDICT_ALWAYS flag from the 'point_worldtext' after
        # setting the parent, otherwise hiding the entity in the SetTransmit
        # hook won't work.
        self.state_flags = self.state_flags ^ FL_EDICT_ALWAYS

        self.decoy.teleport(
            origin,
            angle,
            velocity if velocity else Vector(
                random.choice(random_velocity),
                random.choice(random_velocity),
                65
                )
            )
        # Remove the 'decoy_projectile' after a short delay.
        # Since the 'point_worldtext' is parented to the 'decoy_projectile', it
        # will also get removed.
        self.decoy.delay(0.55, self.decoy.remove)
Exemple #27
0
 def test_reset(self):
     """
     1. create a new NPC, player, thing, 2.reset Entity class, 3. check if there is any entity stored in Entity
     """
     self.new_NPC()
     self.new_player()
     self.new_thing()
     Entity.erase_all_entities()
     self.assertEquals(Entity.all_NPCs, [])
     self.assertEquals(Entity.player, None)
     self.assertEquals(Entity.all_things, [])
 def __init__(self, email, borning_date, password_token, po_balance, photo,
              _credits, created_by):
     """
     Constructor
     """
     Entity.__init__(self, created_by)
     self.email = email
     self.borning_date = borning_date
     self.password_token = password_token
     self.positive_balance = po_balance
     self.photo = photo
     self.credits = _credits
Exemple #29
0
def _get_start_from_weapon(player):
    """Return the weapon's position."""
    weapon = player.active_weapon
    if weapon is None:
        return

    world_model = string_tables[Model.precache_table][weapon.world_model_index]
    header = model_cache.get_model_header(model_cache.find_model(world_model))

    has_muzzle = False
    for index in range(header.attachments_count):
        if header.get_attachment(index).name != 'muzzle_flash':
            continue
        has_muzzle = True

    if not has_muzzle:
        return

    bone = _find_bone(player.model_header, 'ValveBiped.Bip01_R_Hand')
    if bone == -1:
        return

    GetBoneTransform = player.make_virtual_function(
        199,
        Convention.THISCALL,
        [DataType.POINTER, DataType.INT, DataType.POINTER],
        DataType.VOID,
    )

    matrix = Matrix3x4()
    GetBoneTransform(player, bone, matrix)

    angles = matrix.angles
    angles.z += 180

    prop = Entity.create('prop_dynamic_override')
    prop.model_name = world_model
    prop.effects = EntityEffects.NODRAW
    prop.solid_type = SolidType.NONE
    prop.origin = matrix.position
    prop.angle = Vector(*angles)
    prop.spawn()

    null = Entity.create('info_null')
    null.set_parent(prop)
    null.call_input('SetParentAttachment', 'muzzle_flash')

    origin = null.get_property_vector('m_vecAbsOrigin')

    null.spawn()
    prop.remove()

    return origin
Exemple #30
0
 def __init__(self,
              tiles,
              x=1,
              y=1,
              char='-',
              color=tcod.white,
              name="item",
              blocks=False,
              moves=False,
              deletes=True):
     Entity.__init__(self, tiles, x, y, char, color, name, blocks, moves)
     self.deletes = deletes
Exemple #31
0
    def __init__(self, index, caching=True):
        """Initialize the object.

        :param int index:
            A valid player index.
        :param bool caching:
            Whether to lookup the cache for an existing instance or not.
        :raise ValueError:
            Raised if the index is invalid.
        """
        PlayerMixin.__init__(self, index)
        Entity.__init__(self, index)
Exemple #32
0
def key(point=None, unlocks=None):
    key = Entity(point,
                 'k',
                 'key',
                 COLORS.get('light_door'),
                 blocks=False,
                 interaction=Interactions.NONE,
                 render_order=RenderOrder.ITEM,
                 item=Item())
    key.add_component(Unlock(unlocks.uuid), 'unlock')

    return key
Exemple #33
0
def _get_start_from_weapon(player):
    """Return the weapon's position."""
    weapon = player.active_weapon
    if weapon is None:
        return

    world_model = string_tables[Model.precache_table][weapon.world_model_index]
    header = model_cache.get_model_header(model_cache.find_model(world_model))

    has_muzzle = False
    for index in range(header.attachments_count):
        if header.get_attachment(index).name != 'muzzle_flash':
            continue
        has_muzzle = True

    if not has_muzzle:
        return

    bone = _find_bone(player.model_header, 'ValveBiped.Bip01_R_Hand')
    if bone == -1:
        return

    GetBoneTransform = player.make_virtual_function(
        199,
        Convention.THISCALL,
        [DataType.POINTER, DataType.INT, DataType.POINTER],
        DataType.VOID,
    )

    matrix = Matrix3x4()
    GetBoneTransform(player, bone, matrix)

    angles = matrix.angles
    angles.z += 180

    prop = Entity.create('prop_dynamic_override')
    prop.model_name = world_model
    prop.effects = EntityEffects.NODRAW
    prop.solid_type = SolidType.NONE
    prop.origin = matrix.position
    prop.angle = Vector(*angles)
    prop.spawn()

    null = Entity.create('info_null')
    null.set_parent(prop)
    null.call_input('SetParentAttachment', 'muzzle_flash')

    origin = null.get_property_vector('m_vecAbsOrigin')

    null.spawn()
    prop.remove()

    return origin
Exemple #34
0
 def __init__(self,
              floor,
              tiles,
              x=1,
              y=1,
              char='/',
              color=tcod.gray,
              name="none",
              blocks=True,
              moves=True):
     Entity.__init__(self, tiles, x, y, char, color, name, blocks, moves)
     self.floor = floor
Exemple #35
0
	def bomb_dropped(self, userid, bombentindex):
		# get c4
		tmp_bomb = Entity(bombentindex)
		# get origin of c4
		vector = tmp_bomb.origin
		# remove c4
		tmp_bomb.remove()
		# proof for a medkit
		self.create_medkit(userid, bombentindex, vector)
		# proof for an ammobox
		self.create_ammobox(userid, bombentindex, vector)
		# proof for an tugs
		self.create_tugs(userid, bombentindex, vector)
Exemple #36
0
 def __init__(self):
     self.looping = True
     self.player = Player(240, 240)
     self.player.weapons.append(Switcheroo())
     self.player.weapons.append(Magnet())
     self.entities = []
     self.entities.append(self.player)
     self.entities.append(Entity(100, 380))
     self.entities.append(Entity(300, 380))
     self.objects = []
     self.objects.append(KillPart(350, 100))
     self.objects.append(KillPart(160, 200))
     self.objects.append(KillPart(240, 400))
     self.clock = pygame.time.Clock()
Exemple #37
0
def _spend_skills_on_level_up(player, race, amount):
    """
    Callback for the race_level_up event to handle menu sending,
    bot auto-upgrades and level up effects.
    """
    if (race.level > sum(skill.max_level for skill in race.skills)
            or race.level > race.max_level):
        return

    spend_skills_menu.send(player.index)

    if player.steamid == 'BOT':
        while race.unused_points > 0:
            skill = find_upgradable_skill(race)
            if skill:
                skill.level_up(1)

    levelup_sound.origin = player.origin
    levelup_sound.play(player.index)
    pointer = player.give_named_item('env_smokestack', 0, None, False)
    entity = Entity(index_from_pointer(pointer))

    for output in ('basespread 10', 'spreadspeed 60', 'initial 0', 'speed 105',
                   'rate 50', 'startsize 7', 'endsize 2', 'twist 0',
                   'jetlength 100', 'angles 0 0 0', 'rendermode 18',
                   'renderamt 100', 'rendercolor 255 255 3',
                   'SmokeMaterial effects/yellowflare.vmt'):
        entity.add_output(output)

    entity.turn_on()
    attach_entity_to_player(player, entity)
    entity.delay(0.5, entity.turn_off)
Exemple #38
0
 def __init__(self, beer_id, user_id, pay_type_id, climate_id, v_date,
              _token, _qr, pay_product, created_by):
     """
     Constructor
     """
     Entity.__init__(self, created_by)
     self.beer_id = beer_id
     self.user_id = user_id
     self.pay_type_id = pay_type_id
     self.climate_id = climate_id
     self.visit_date = v_date
     self._token = _token
     self.payment_product = pay_product
     self._qr = _qr
    def weapon_indexes(
            self, classname=None, is_filters=None, not_filters=None):
        """Iterate over all currently held weapons by thier index."""
        # Is the weapon array supported for the current game?
        if _weapon_prop_length is None:
            return

        # Loop through the length of the weapon array
        for offset in range(_weapon_prop_length):

            # Get the player's current weapon at this offset
            handle = self.get_property_int(
                weapon_manager.myweapons + '%03i' % offset)

            # Get the weapon's index
            index = index_from_inthandle(handle, raise_exception=False)

            # Is this a valid index?
            if not index:

                # Move onto the next offset
                continue

            # Get the weapon's edict
            edict = Entity(index)

            # Get the weapon's classname
            weapon_class = edict.get_class_name()

            # Was a classname given and the current
            # weapon is not of that classname?
            if classname is not None and weapon_class != classname:

                # Do not yield this index
                continue

            # Import WeaponClassIter to use its functionality
            from filters.weapons import WeaponClassIter

            # Was a weapon type given and the
            # current weapon is not of that type?
            if not (is_filters is None and not_filters is None):
                if weapon_class not in list(WeaponClassIter(
                        is_filters, not_filters, 'classname')):

                    # Do not yield this index
                    continue

            # Yield the index
            yield index
Exemple #40
0
def map_scroll(point=None):
    usable = ScrollUsable(scroll_name="Mapping Scroll",
                          scroll_spell=tome.mapping)

    item = Entity(point,
                  '#',
                  usable.name,
                  COLORS.get('equipment_uncommon'),
                  render_order=RenderOrder.ITEM,
                  item=Item(),
                  usable=usable)

    item.add_component(IdentifiableScroll(), "identifiable")

    return item
Exemple #41
0
    def perform(self):
        self._performed = True

        global _entities_spawned_this_approach, _entities_spawned_this_tick
        _entities_spawned_this_approach += 1
        _entities_spawned_this_tick += 1

        global _total_entities
        _total_entities += 1

        entity = Entity.create(BLOCK_ENTITY)
        entity.model = self._prototype.model
        entity.health = self._prototype.health
        entity.set_property_int('m_Material', self._prototype.material)
        entity.teleport(self._origin)
        entity.spawn()

        if self._sound_effects:
            Sound(
                choice(_level_properties['block_restore_sounds']),
                index=SOUND_FROM_WORLD,
                volume=0.25,
                attenuation=Attenuation.NORMAL,
                origin=self._origin
            ).play()

        self._callback(entity)
Exemple #42
0
def level_up(player):
    """Display the level up effect on a player."""
    entity = Entity.create('env_smokestack')

    # This might be completely unnecessary.
    # The only time I can think that this might be necessary is
    #   if the max entity limit is reached, but I am not sure this would
    #   catch that, or if there would be another error that would occur.
    if not entity.basehandle.is_valid():
        return

    entity.teleport(player.origin, None, None)
    entity.base_spread = 10
    entity.spread_speed = 60
    entity.initial_state = 0
    entity.speed = 105
    entity.rate = 50
    entity.start_size = 7
    entity.end_size = 2
    entity.twist = 0
    entity.jet_length = 100
    entity.angles = NULL_VECTOR
    entity.render_mode = 18
    entity.render_amt = 100
    entity.render_color = Color(255, 255, 3)
    entity.add_output('SmokeMaterial effects/yellowflare.vmt')
    entity.turn_on()
    entity.set_parent(player.pointer, -1)
    Delay(2, _remove_smoke, entity)
Exemple #43
0
def strip(command):
    if len(command) == 2:
        if exists(int(command[1])):
            player = Player.from_userid(int(command[1]))
            entity = Entity.create('player_weaponstrip')
            entity.call_input("Strip", activator=player)
            entity.remove()
Exemple #44
0
	def endround(self, condition):
		"""CSS:
		0 TERRORIST     "Target_Bombed"
		1 CT            "VIP_Escaped"
		2 TERRORIST     "VIP_Assassinated"
		3 TERRORIST     "Terrorists_Escaped"
		4 CT            "CTs_PreventEscape"
		5 CT            "Escaping_Terrorists_Neutralized"
		6 CT            "Bomb_Defused"
		7 CT            "CTs_Win"
		8 TERRORIST        "Terrorists_Win"
		9 World            "Round_Draw"
		10 CT            "All_Hostages_Rescued"
		11 CT            "Target_Saved"
		12 TERRORIST     "Hostages_Not_Rescued"
		13 CT            "Terrorists_Not_Escaped"
		14 TERRORIST    "VIP_Not_Escaped"
		15 World        "Game_Commencing"
		16 World        "UNKNOWN"
		"""
		if self.is_endround == False:
			self.is_endround = True
			info_map_parameters = Entity.find_or_create("info_map_parameters")
			info_map_parameters.call_input('FireWinCondition', condition)
			# play sound
			self.sounds.play_random('endround')
Exemple #45
0
    def _add_weapon_ammo(self,
                         value,
                         classname=None,
                         is_filters=None,
                         not_filters=None):
        """Add ammo to the player's current value for the given arguments.

        Adds for the first weapon found from the given arguments.
        """
        # Get the index for the given arguments
        index = self.get_weapon_index(classname, is_filters, not_filters)

        # Was no index found?
        if index is None:

            # Raise an error
            raise LookupError('No index found for given arguments '
                              '"{0}, {1}, {2}" for player "{3}"'.format(
                                  classname, is_filters, not_filters,
                                  self.userid))

        # Get the entity's Entity instance
        weapon = Entity(index)

        # Get the current ammo value
        current = self.get_property_int(weapon_manager.ammoprop +
                                        '%03d' % weapon.ammoprop)

        # Add ammo to the current value
        self.set_property_int(
            weapon_manager.ammoprop + '%03d' % weapon.ammoprop,
            current + value)
Exemple #46
0
def wcs_sub_strip_command(command_info, player:convert_userid_to_player):
    if player is None:
        return

    entity = Entity.create('player_weaponstrip')
    entity.call_input('Strip', activator=player)
    entity.remove()
Exemple #47
0
def listener_on_tick():
    for sprinting_player in player_manager.values():
        if sprinting_player.player.ground_entity == -1:
            sprinting_player.ensure_speed(AIRBORNE_PLAYER_SPEED)
        else:
            if sprinting_player.sprinting:
                sprinting_player.ensure_speed(SPRINTING_PLAYER_SPEED)
            else:
                sprinting_player.ensure_speed(DEFAULT_PLAYER_SPEED)

        if sprinting_player.sprinting:
            inthandle = sprinting_player.player.active_weapon
            if inthandle == INVALID_ENTITY_INTHANDLE:
                continue

            entity = Entity(index_from_inthandle(inthandle))
            entity.next_attack = global_vars.current_time + 1
            entity.next_secondary_fire_attack = global_vars.current_time + 1
Exemple #48
0
 def give_spark_entity(self):
     entity = self.spark_entity = Entity.create('env_spark')
     entity.spawn_flags = 896
     entity.angles = Vector(-90, 0, 0)
     entity.magnitude = 8
     entity.trail_length = 3
     entity.set_parent(self, -1)
     entity.origin = self.origin
     entity.start_spark()
 def give_spark_entity(self):
     """Give the player an env_spark effect."""
     entity = self.spark_entity = Entity.create('env_spark')
     entity.spawn_flags = 896
     entity.angles = QAngle(-90, 0, 0)
     entity.magnitude = 8
     entity.trail_length = 3
     entity.set_parent(self, -1)
     entity.origin = self.origin
     entity.start_spark()
Exemple #50
0
def _on_level_change(hero):
    player = hero.owner
    spend_skills.send(player)
    pointer = player.give_named_item('env_smokestack')
    entity = Entity(index_from_pointer(pointer))

    Model('effects/yellowflare.vmt')
    for output in ('basespread 10', 'spreadspeed 60', 'initial 0', 'speed 105',
        'rate 50', 'startsize 7', 'endsize 2', 'twist 0', 'jetlength 100',
        'angles 0 0 0', 'rendermode 18', 'renderamt 100',
        'rendercolor 255 255 3', 'SmokeMaterial effects/yellowflare.vmt'):
        entity.add_output(output)

    entity.turn_on()
    entity.set_parent(player.pointer, -1)
    entity.delay(0.5, entity.turn_off, cancel_on_level_end=True)
Exemple #51
0
    def process(self, time_passed):
        Entity.process(self, time_passed)

        energy = self.c["attrs"].get("energy")
        health = self.c["attrs"].get("health")

        # Should the ant die?
        if health.val <= 0:
            self.flags.add("dead")
            return

        # Burn energy each turn.
        energy.val -= 2.*time_passed

        # Is ant energy so low that we need to dump health into energy?
        if energy.val == 0:
            energy.val += 100
            health.val -= 10
        
        # Heading matches course of velocity.
        self.c["facing"].set(self.c["velocity"].course)
Exemple #52
0
    def __init__(self, world, base):
        
        Entity.__init__(self, world)
                
        self.brain.add_state(antbrainstates.Exploring())
        self.brain.add_state(antbrainstates.Seeking())
        self.brain.add_state(antbrainstates.Delivering())
        self.brain.add_state(antbrainstates.EnergyDepleted())
        self.brain.add_state(antbrainstates.PowerUp())
        # Default state.
        self.brain.set_state("exploring")
        
        self.c.add("attrs")
        self.c["attrs"].create("energy", val=100)
        self.c["attrs"].create("health", val=100)
        
        self.c.add("facing")
        self.c.add("velocity", max_speed=120., acceleration=30., rotation_speed=180.)
        self.c.add("destination")
        self.c.add("inventory")

        # {Entity} What is our home base.
        self.base = base
Exemple #53
0
    def _set_weapon_clip(
            self, value, classname=None, is_filters=None, not_filters=None):
        """Set the player's clip value for the given arguments.

        Sets for the first weapon found from the given arguments.
        """
        # Get the index for the given arguments
        index = self.get_weapon_index(classname, is_filters, not_filters)

        # Was no index found?
        if index is None:

            # Raise an error
            raise LookupError(
                'No index found for given arguments '
                '"{0}, {1}, {2}" for player "{3}"'.format(
                    classname, is_filters, not_filters, self.userid))

        # Get the entity's Entity instance
        weapon = Entity(index)

        # Set the weapon's clip value
        weapon.clip = value
def _gg_win(game_event):
    """Increase the win total for the winner and end the map."""
    # Set the match status
    GunGameStatus.MATCH = GunGameMatchStatus.POST

    # Get the winner
    winner = player_dictionary[game_event['winner']]

    # Increase the winner's win total if they are not a bot
    if not winner.is_fake_client():
        winner.wins += 1

    # Send the winner messages
    message_manager.chat_message(
        message='Winner:Long',
        index=winner.index,
        winner=winner.name,
    )
    for second in range(4):
        Delay(
            delay=second,
            callback=message_manager.center_message,
            kwargs={
                'message': 'Winner:Short',
                'winner': winner.name,
            },
            cancel_on_level_end=True,
        )
    color = {2: RED, 3: BLUE}.get(winner.team_index, WHITE)
    message_manager.top_message(
        message='Winner:Short',
        color=color,
        winner=winner.name
    )

    # Play the winner sound
    winner_sound = sound_manager.play_sound('winner')

    # Set the dynamic chat time, if needed
    if dynamic_chat_time.get_bool() and winner_sound is not None:
        with suppress(MutagenError):
            ConVar('mp_chattime').set_float(winner_sound.duration)

    # End the match to move to the next map
    entity = Entity.find_or_create('game_end')
    entity.end_game()

    # Do not remove! This fixes a lot of console spam and hanging on map end.
    queue_command_string('bot_kick')
Exemple #55
0
 def test_remove_old(self):
     Entity.erase_all_entities()
     # add and remove an NPC
     an_NPC = self.new_NPC()
     self.assertNotEquals(Entity.all_NPCs, [])
     Entity.remove_old(an_NPC)
     self.assertEquals(Entity.all_NPCs, [])
     # add and remove a player
     a_player = self.new_player()
     self.assertNotEquals(Entity.player, None)
     Entity.remove_old(a_player)
     self.assertEquals(Entity.player, None)
     # add and remove an thing
     a_thing = self.new_thing()
     self.assertNotEquals(Entity.all_things, [])
     Entity.remove_old(a_thing)
     self.assertEquals(Entity.all_things, [])
Exemple #56
0
	def create_medkit(self, userid, bombentindex, vector):
		try:
			locked = False
			# get player and team
			player = Player.from_userid(userid)
			pdata = self.rank.get_player_data(userid)
			if not int(pdata['class']) in self.rank.classes:
				return
			if not self.rank.classes[int(pdata['class'])]['can_have_medkit'] >= 1:
				return
			pteam = self.rank.get_player_team(userid)
			# delete old medkit if we spawn a new one
			self.delete_pack(userid)
			# create healthpack
			self.packs_lock.acquire()
			locked = True
			# set medkit color
			if pteam == 'CT':
				color = self.color_ct
			else:
				color = self.color_t
			tmp_ent = Entity.create('prop_physics_override')
			self.pack[player.userid] = {
				'ent': tmp_ent.index,
				'type': 'health',
				'amount': 200,
				'give': 10,
				'distance': 100,
				'userid': userid,
				'team': pteam,
				'next_glow': 0,
				'color': color,
			}
			tmp_ent.origin = vector
			tmp_ent.model = Model('models/props/cs_italy/bin01.mdl')
			tmp_ent.spawn_flags = 4
			tmp_ent.color = color
			# spawn healthpack
			tmp_ent.spawn()
			# set health
			tmp_ent.call_input('SetHealth', 100)
			tmp_ent.set_property_uchar("m_takedamage", TakeDamage.YES)
			self.packs_lock.release()
			locked = False
		except:
			if locked:
				self.packs_lock.release()
			msg('ERROR', 'could not create healthpack')
def _end_match(game_event):
    # Set the match status
    GunGameStatus.MATCH = GunGameMatchStatus.POST

    # Get the winning team information
    winning_team = teamwork_manager[game_event['winner']]

    # Send the winner messages
    message_manager.chat_message(
        index=winning_team.index,
        message='TeamWork:Winner:Long',
        team_name=winning_team.name,
    )
    for second in range(4):
        Delay(
            delay=second,
            callback=message_manager.center_message,
            kwargs={
                'message': 'TeamWork:Winner:Short',
                'team_name': winning_team.name,
            },
            cancel_on_level_end=True,
        )
    color = {2: RED, 3: BLUE}.get(winning_team, WHITE)
    message_manager.top_message(
        message='TeamWork:Winner:Short',
        color=color,
        team_name=winning_team.name,
    )

    # Play the winner sound
    winner_sound = sound_manager.play_sound('winner')

    # Set the dynamic chat time, if needed
    if dynamic_chat_time.get_bool() and winner_sound is not None:
        with suppress(MutagenError):
            ConVar('mp_chattime').set_float(winner_sound.duration)

    # End the match to move to the next map
    entity = Entity.find_or_create('game_end')
    entity.end_game()

    # Do not remove! This fixes a lot of console spam and hanging on map end.
    queue_command_string('bot_kick')

    # Reset the teams
    _clear_team_dictionary()
Exemple #58
0
def _player_spawn(game_event):
    """Give the player their level weapon."""
    # Is GunGame active?
    if GunGameStatus.MATCH is not GunGameMatchStatus.ACTIVE:
        return

    # Use try/except to get the player's instance
    try:
        player = player_dictionary[game_event['userid']]
    except ValueError:
        return

    # Verify that the player is on a team
    if player.team < 2:
        return

    # Spawn protection
    player.give_spawn_protection()

    # Give the player their new weapon
    player.strip_weapons()
    player.give_level_weapon()

    # Give CTs defusers, if need be
    if player.team == 3 and give_defusers.get_bool():
        player.has_defuser = True

    # Give player armor, if necessary
    armor_type = {1: 'kevlar', 2: 'assaultsuit'}.get(give_armor.get_int())
    if armor_type is not None:
        equip = Entity.find_or_create('game_player_equip')
        equip.add_output('{weapon} 1'.format(weapon=_melee_weapon))
        equip.add_output(
            'item_{armor_type} 1'.format(
                armor_type=armor_type
            ),
            caller=player,
            activator=player,
        )

    # Skip bots
    if player.is_fake_client():
        return

    # Send the player their level information
    _send_level_info(player)
Exemple #59
0
def _gg_win(game_event):
    """Increase the win total for the winner and end the map."""
    # Set the match status
    GunGameStatus.MATCH = GunGameMatchStatus.POST

    # Get the winner
    winner = player_dictionary[game_event['winner']]

    # Increase the winner's win total if they are not a bot
    if not winner.is_fake_client():
        winner.wins += 1

    # Send the winner messages
    message_manager.chat_message(
        message='Winner:Long',
        index=winner.index,
        winner=winner.name,
    )
    for second in range(4):
        Delay(
            second,
            message_manager.center_message,
            kwargs={
                'message': 'Winner:Short',
                'winner': winner.name,
            }
        )
    color = {2: RED, 3: BLUE}.get(winner.team, WHITE)
    message_manager.top_message(
        message='Winner:Short',
        color=color,
        winner=winner.name
    )

    # Play the winner sound
    winner_sound = sound_manager.play_sound('winner')

    # Set the dynamic chat time, if needed
    if dynamic_chat_time.get_bool():
        with suppress(MutagenError):
            ConVar('mp_chattime').set_float(winner_sound.duration)

    # End the match to move to the next map
    entity = Entity.find_or_create('game_end')
    entity.end_game()
def change_level(round_end=False):
    if status.next_map is None:
        raise RuntimeError("It's already time to change the level, "
                           "but next map is yet to be decided")

    if config_manager['instant_change_level'] or round_end:
        log.log_debug("Ending the game...")

        game_end_entity = Entity.find_or_create('game_end')
        game_end_entity.end_game()

    else:
        log.log_debug("Waiting for the round end to end the game...")

        status.round_end_needed = True

        if config_manager['timeleft_auto_lastround_warning']:
            broadcast(strings_common['timeleft_last_round'])