def kill(arguments, clientid):

    if arguments == [] or arguments == ['']:
        myself = clientid_to_myself(clientid)
        handlemsg(myself, ba.DieMessage())

    elif arguments[0] == 'all':
        handlemsg_all(ba.DieMessage())

    else:
        try:
            req_player = int(arguments[0])
            handlemsg(req_player, ba.DieMessage())
        except:
            return
Ejemplo n.º 2
0
    def _touch_return_update(self, team: ba.Team) -> None:

        # Count down only while its away from base and not being held.
        if (team.gamedata['home_flag_at_base']
                or team.gamedata['flag'].held_count > 0):
            team.gamedata['touch_return_timer_ticking'] = None
            return  # No need to return when its at home.
        if team.gamedata['touch_return_timer_ticking'] is None:
            team.gamedata['touch_return_timer_ticking'] = ba.NodeActor(
                ba.newnode('sound',
                           attrs={
                               'sound': self._ticking_sound,
                               'positional': False,
                               'loop': True
                           }))
        flag = team.gamedata['flag']
        flag.touch_return_time -= 0.1
        if flag.counter:
            flag.counter.text = '%.1f' % flag.touch_return_time
            flag.counter.color = (1, 1, 0, 1)
            flag.counter.scale = 0.02

        if flag.touch_return_time <= 0.0:
            self._award_players_touching_own_flag(team)
            flag.handlemessage(ba.DieMessage())
    def _tick(self) -> None:
        # If either flag is away from base and not being held, tick down its
        # respawn timer.
        for team in self.teams:
            flag = team.flag
            assert flag is not None

            if not team.home_flag_at_base and flag.held_count == 0:
                time_out_counting_down = True
                if flag.time_out_respawn_time is None:
                    flag.reset_return_times()
                assert flag.time_out_respawn_time is not None
                flag.time_out_respawn_time -= 1
                if flag.time_out_respawn_time <= 0:
                    flag.handlemessage(ba.DieMessage())
            else:
                time_out_counting_down = False

            if flag.node and flag.counter:
                pos = flag.node.position
                flag.counter.position = (pos[0], pos[1] + 1.3, pos[2])

                # If there's no self-touches on this flag, set its text
                # to show its auto-return counter.  (if there's self-touches
                # its showing that time).
                if team.flag_return_touches == 0:
                    flag.counter.text = (str(flag.time_out_respawn_time) if (
                        time_out_counting_down
                        and flag.time_out_respawn_time is not None
                        and flag.time_out_respawn_time <= 10) else '')
                    flag.counter.color = (1, 1, 1, 0.5)
                    flag.counter.scale = 0.014
Ejemplo n.º 4
0
    def on_player_leave(self, player: ba.Player) -> None:
        ba.TeamGameActivity.on_player_leave(self, player)

        # A player leaving disqualifies the team if 'Entire Team Must Finish'
        # is on (otherwise in teams mode everyone could just leave except the
        # leading player to win).
        if (isinstance(self.session, ba.DualTeamSession)
                and self.settings.get('Entire Team Must Finish')):
            ba.screenmessage(ba.Lstr(
                translate=('statements',
                           '${TEAM} is disqualified because ${PLAYER} left'),
                subs=[('${TEAM}', player.team.name),
                      ('${PLAYER}', player.get_name(full=True))]),
                             color=(1, 1, 0))
            player.team.gamedata['finished'] = True
            player.team.gamedata['time'] = None
            player.team.gamedata['lap'] = 0
            ba.playsound(ba.getsound('boo'))
            for otherplayer in player.team.players:
                otherplayer.gamedata['lap'] = 0
                otherplayer.gamedata['finished'] = True
                try:
                    if otherplayer.actor is not None:
                        otherplayer.actor.handlemessage(ba.DieMessage())
                except Exception:
                    ba.print_exception('Error sending diemessages')

        # Defer so team/player lists will be updated.
        ba.pushcall(self._check_end_game)
    def on_player_leave(self, player: Player) -> None:
        super().on_player_leave(player)
        # Remove us from spawn-order.

        # Update icons in a moment since our team will be gone from the
        # list then.
        #==
        if player.getname() in self.myPlayers:
            self.playerInGameNodeFunc()

            if player.is_alive():
                if self.myPlayers[self.count - 2] == str(player.getname()):
                    winningPlayer = self.playerFromName(
                        self.myPlayers[self.count - 1])
                else:
                    winningPlayer = self.playerFromName(
                        self.myPlayers[self.count - 2])

                if winningPlayer:
                    winningPlayer.team.survival_seconds += 1
                    if winningPlayer.is_alive():
                        winningPlayer.actor.handlemessage(
                            ba.DieMessage(immediate=True))

            if self.myPlayers.index(player.getname()) < self.count:
                self.count -= 1
            self.myPlayers.remove(str(player.getname()))
            if player.is_alive(): self.spawnPlayer()
            else:
                if len(self.myPlayers) > 2: self.upNextNodeFunc()
                if len(self.myPlayers) == 2:
                    if self.upNextNode: self.upNextNode.delete()
    def _touch_return_update(self, team: Team) -> None:
        # Count down only while its away from base and not being held.
        assert team.flag is not None
        if team.home_flag_at_base or team.flag.held_count > 0:
            team.touch_return_timer_ticking = None
            return  # No need to return when its at home.
        if team.touch_return_timer_ticking is None:
            team.touch_return_timer_ticking = ba.NodeActor(
                ba.newnode('sound',
                           attrs={
                               'sound': self._ticking_sound,
                               'positional': False,
                               'loop': True
                           }))
        flag = team.flag
        if flag.touch_return_time is not None:
            flag.touch_return_time -= 0.1
            if flag.counter:
                flag.counter.text = f'{flag.touch_return_time:.1f}'
                flag.counter.color = (1, 1, 0, 1)
                flag.counter.scale = 0.02

            if flag.touch_return_time <= 0.0:
                self._award_players_touching_own_flag(team)
                flag.handlemessage(ba.DieMessage())
    def handlemessage(self, m):
        #self._handlemessageSanityCheck()
        if isinstance(m, ba.OutOfBoundsMessage): self.handlemessage(ba.DieMessage())
        elif isinstance(m, ba.DieMessage):
            if hasattr(self,"light") and self.light is not None:self.light.delete()
            if hasattr(self,"smokeTimer"):self.smokeTimer = None
            if hasattr(self,"surround"):self.surround = None
            if hasattr(self,"sparkTimer"):self.sparkTimer = None
            if hasattr(self,"snowTimer"):self.snowTimer = None
            if hasattr(self,"metalTimer"):self.metalTimer = None
            if hasattr(self,"DistortionTimer"):self.DistortionTimer = None
            if hasattr(self,"slimeTimer"):self.slimeTimer = None
            if hasattr(self,"KamikazeCheck"):self.KamikazeCheck = None
            if hasattr(self,"neroLightTimer"):self.neroLightTimer = None
            if hasattr(self,"checkDeadTimer"):self.checkDeadTimer = None
            if hasattr(self,"HealTimer"):self.HealTimer = None
            if hasattr(self,"scorchTimer"):self.scorchTimer = None
            if hasattr(self,"scorchNode"):self.scorchNode = None
            if not self._hasDead:
                spaz = self.spazRef()
                #print str(spaz) + "Spaz"
                if spaz is not None and spaz.is_alive() and spaz.node.exists(): spaz.node.color = self.spazNormalColor
                killer = spaz.last_player_attacked_by if spaz is not None else None
                try:
                    if killer in (None,ba.Player(None)) or killer.actor is None or not killer.actor.exists() or killer.actor.hitPoints <= 0:killer = None
                except:
                    killer = None
                    #if hasattr(self,"hasDead") and not self.hasDead:
                self._hasDead = True

        ba.Actor.handlemessage(self, m)
    def emitIce(self):
        spaz = self.spazRef()

        if spaz is None or not spaz.is_alive() or not spaz.node.exists():
            self.handlemessage(ba.DieMessage())
            return
        ba.emitfx(position=spaz.node.position , velocity=spaz.node.velocity, count=random.randint(2,8), scale=0.4, spread=0.2, chunk_type="ice")
 def emitDistortion(self):
     spaz = self.spazRef()
     if spaz is None or not spaz.is_alive() or not spaz.node.exists():
         self.handlemessage(ba.DieMessage())
         return
     ba.emitfx(position=spaz.node.position,emit_type="distortion",spread=1.0)
     ba.emitfx(position=spaz.node.position, velocity=spaz.node.velocity,count=random.randint(1,5),emit_type="tendrils",tendril_type="smoke")
 def handlemessage(self, m):
     ba.Actor.handlemessage(self, m)
     if isinstance(m, ba.DieMessage):
         if self.surroundTimer is not None: self.surroundTimer = None
         self.node.delete()
     elif isinstance(m, ba.OutOfBoundsMessage):
         self.handlemessage(ba.DieMessage())
Ejemplo n.º 11
0
    def _tick(self) -> None:
        if self.node:

            # Grab our initial position after one tick (in case we fall).
            if self._initial_position is None:
                self._initial_position = self.node.position

                # Keep track of when we first move; we don't count down
                # until then.
            if not self._has_moved:
                nodepos = self.node.position
                if (max(
                        abs(nodepos[i] - self._initial_position[i])
                        for i in list(range(3))) > 1.0):
                    self._has_moved = True

            if self._held_count > 0 or not self._has_moved:
                assert self._dropped_timeout is not None
                assert self._counter
                self._count = self._dropped_timeout
                self._counter.text = ''
            else:
                self._count -= 1
                if self._count <= 10:
                    nodepos = self.node.position
                    assert self._counter
                    self._counter.position = (nodepos[0], nodepos[1] + 1.3,
                                              nodepos[2])
                    self._counter.text = str(self._count)
                    if self._count < 1:
                        self.handlemessage(ba.DieMessage())
                else:
                    assert self._counter
                    self._counter.text = ''
Ejemplo n.º 12
0
    def __init__(self,
                 position=(0, 5, 0),
                 direction=(0, 2, 0),
                 source_player=None,
                 owner=None,
                 color=(1, 1, 1)) -> None:
        super().__init__()
        self._color = color

        self.node = ba.newnode('light',
                               delegate=self,
                               attrs={
                                   'position': position,
                                   'color': self._color
                               })
        ba.animate(self.node, 'radius', {0: 0, 0.1: 0.5, 0.5: 0})

        self.source_player = source_player
        self.owner = owner
        self._life_timer = ba.Timer(
            0.5, ba.WeakCall(self.handlemessage, ba.DieMessage()))

        pos = position
        vel = tuple(i / 5 for i in ba.Vec3(direction).normalized())
        for _ in range(500):  # Optimization :(
            ba.newnode('explosion',
                       owner=self.node,
                       attrs={
                           'position': pos,
                           'radius': 0.2,
                           'color': self._color
                       })
            pos = (pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2])

        for node in _ba.getnodes():
            if node and node.getnodetype() == 'spaz':
                # pylint: disable=invalid-name
                m3 = ba.Vec3(position)
                a = ba.Vec3(direction[2], direction[1], direction[0])
                m1 = ba.Vec3(node.position)
                # pylint: enable=invalid-name
                # distance between node and line
                dist = (a * (m1 - m3)).length() / a.length()
                if dist < 0.3:
                    if node and node != self.owner and node.getdelegate(
                            PlayerSpaz, True).getplayer(
                                ba.Player, True).team != self.owner.team:
                        node.handlemessage(ba.FreezeMessage())
                        pos = self.node.position
                        hit_dir = (0, 10, 0)

                        node.handlemessage(
                            ba.HitMessage(pos=pos,
                                          magnitude=50,
                                          velocity_magnitude=50,
                                          radius=0,
                                          srcnode=self.node,
                                          source_player=self.source_player,
                                          force_direction=hit_dir))
Ejemplo n.º 13
0
    def handlemessage(self, msg: Any) -> Any:
        """Message handling for rocket"""
        super().handlemessage(msg)
        if isinstance(msg, ImpactMessage):
            self.node.handlemessage(ba.DieMessage())

        elif isinstance(msg, ba.DieMessage):
            if self.node:
                Blast(position=self.node.position,
                      blast_radius=2,
                      source_player=self.source_player)

                self.node.delete()
                self._emit_timer = None

        elif isinstance(msg, ba.OutOfBoundsMessage):
            self.handlemessage(ba.DieMessage())
Ejemplo n.º 14
0
    def handlemessage(self, msg: Any) -> Any:
        super().handlemessage(msg)
        if isinstance(msg, ba.DieMessage):
            if self.node:
                self.node.delete()

        elif isinstance(msg, ba.OutOfBoundsMessage):
            self.handlemessage(ba.DieMessage())
Ejemplo n.º 15
0
 def death_material(self) -> ba.Material:
     """A ba.Material that sends a ba.DieMessage() to anything
     that touches it; handy for terrain below a cliff, etc.
     """
     if self._death_material is None:
         mat = self._death_material = ba.Material()
         mat.add_actions(
             ('message', 'their_node', 'at_connect', ba.DieMessage()))
     return self._death_material
Ejemplo n.º 16
0
    def _handle_reached_end(self) -> None:
        spaz = ba.getcollision().opposingnode.getdelegate(SpazBot, True)
        if not spaz.is_alive():
            return  # Ignore bodies flying in.

        self._flawless = False
        pos = spaz.node.position
        ba.playsound(self._bad_guy_score_sound, position=pos)
        light = ba.newnode('light',
                           attrs={
                               'position': pos,
                               'radius': 0.5,
                               'color': (1, 0, 0)
                           })
        ba.animate(light, 'intensity', {0.0: 0, 0.1: 1, 0.5: 0}, loop=False)
        ba.timer(1.0, light.delete)
        spaz.handlemessage(
            ba.DieMessage(immediate=True, how=ba.DeathType.REACHED_GOAL))

        if self._lives > 0:
            self._lives -= 1
            if self._lives == 0:
                self._bots.stop_moving()
                self.continue_or_end_game()
            assert self._lives_text is not None
            assert self._lives_text.node
            self._lives_text.node.text = str(self._lives)
            delay = 0.0

            def _safesetattr(node: ba.Node, attr: str, value: Any) -> None:
                if node:
                    setattr(node, attr, value)

            for _i in range(4):
                ba.timer(
                    delay,
                    ba.Call(_safesetattr, self._lives_text.node, 'color',
                            (1, 0, 0, 1.0)))
                assert self._lives_bg is not None
                assert self._lives_bg.node
                ba.timer(
                    delay,
                    ba.Call(_safesetattr, self._lives_bg.node, 'opacity', 0.5))
                delay += 0.125
                ba.timer(
                    delay,
                    ba.Call(_safesetattr, self._lives_text.node, 'color',
                            (1.0, 1.0, 0.0, 1.0)))
                ba.timer(
                    delay,
                    ba.Call(_safesetattr, self._lives_bg.node, 'opacity', 1.0))
                delay += 0.125
            ba.timer(
                delay,
                ba.Call(_safesetattr, self._lives_text.node, 'color',
                        (0.8, 0.8, 0.8, 1.0)))
Ejemplo n.º 17
0
    def __init__(self, settings: dict):
        super().__init__(settings)
        shared = SharedObjects.get()
        self._scoreboard = Scoreboard()
        self._cheer_sound = ba.getsound('cheer')
        self._chant_sound = ba.getsound('crowdChant')
        self._foghorn_sound = ba.getsound('foghorn')
        self._swipsound = ba.getsound('swip')
        self._whistle_sound = ba.getsound('refWhistle')
        self.puck_model = ba.getmodel('puck')
        self.puck_tex = ba.gettexture('puckColor')
        self._puck_sound = ba.getsound('metalHit')
        self.puck_material = ba.Material()
        self.puck_material.add_actions(actions=(('modify_part_collision',
                                                 'friction', 0.5)))
        self.puck_material.add_actions(conditions=('they_have_material',
                                                   shared.pickup_material),
                                       actions=('modify_part_collision',
                                                'collide', False))
        self.puck_material.add_actions(
            conditions=(
                ('we_are_younger_than', 100),
                'and',
                ('they_have_material', shared.object_material),
            ),
            actions=('modify_node_collision', 'collide', False),
        )
        self.puck_material.add_actions(conditions=('they_have_material',
                                                   shared.footing_material),
                                       actions=('impact_sound',
                                                self._puck_sound, 0.2, 5))

        # Keep track of which player last touched the puck
        self.puck_material.add_actions(
            conditions=('they_have_material', shared.player_material),
            actions=(('call', 'at_connect',
                      self._handle_puck_player_collide), ))

        # We want the puck to kill powerups; not get stopped by them
        self.puck_material.add_actions(
            conditions=('they_have_material',
                        PowerupBoxFactory.get().powerup_material),
            actions=(('modify_part_collision', 'physical', False),
                     ('message', 'their_node', 'at_connect', ba.DieMessage())))
        self._score_region_material = ba.Material()
        self._score_region_material.add_actions(
            conditions=('they_have_material', self.puck_material),
            actions=(('modify_part_collision', 'collide',
                      True), ('modify_part_collision', 'physical', False),
                     ('call', 'at_connect', self._handle_score)))
        self._puck_spawn_pos: Optional[Sequence[float]] = None
        self._score_regions: Optional[List[ba.NodeActor]] = None
        self._puck: Optional[Puck] = None
        self._score_to_win = int(settings['Score to Win'])
        self._time_limit = float(settings['Time Limit'])
 def circleMove(self):
     spaz = self.spazRef()
     if spaz is None or not spaz.is_alive() or not spaz.node.exists():
         self.handlemessage(ba.DieMessage())
         return
     p = spaz.node.position
     pt = self.getTargetPosition(p)
     pn = self.node.position
     d = [pt[0] - pn[0], pt[1] - pn[1], pt[2] - pn[2]]
     speed = self.getMaxSpeedByDir(d)
     self.node.velocity = speed
Ejemplo n.º 19
0
    def handlemessage(self, msg: Any) -> Any:
        # pylint: disable=too-many-branches
        if __debug__:
            self._handlemessage_sanity_check()

        if isinstance(msg, ba.PowerupAcceptMessage):
            factory = get_factory()
            assert self.node
            if self.poweruptype == 'health':
                ba.playsound(factory.health_powerup_sound,
                             3,
                             position=self.node.position)
            ba.playsound(factory.powerup_sound, 3, position=self.node.position)
            self._powersgiven = True
            self.handlemessage(ba.DieMessage())

        elif isinstance(msg, _TouchedMessage):
            if not self._powersgiven:
                node = ba.get_collision_info('opposing_node')
                if node:
                    node.handlemessage(
                        ba.PowerupMessage(self.poweruptype,
                                          source_node=self.node))

        elif isinstance(msg, ba.DieMessage):
            if self.node:
                if msg.immediate:
                    self.node.delete()
                else:
                    ba.animate(self.node, 'model_scale', {0: 1, 0.1: 0})
                    ba.timer(0.1, self.node.delete)

        elif isinstance(msg, ba.OutOfBoundsMessage):
            self.handlemessage(ba.DieMessage())

        elif isinstance(msg, ba.HitMessage):
            # Don't die on punches (that's annoying).
            if msg.hit_type != 'punch':
                self.handlemessage(ba.DieMessage())
        else:
            super().handlemessage(msg)
Ejemplo n.º 20
0
    def clear(self) -> None:
        """Immediately clear out any bots in the set."""

        # Don't do this if the activity is shutting down or dead.
        activity: Optional[ba.Activity] = ba.getactivity(doraise=False)
        if activity is None or activity.expired:
            return

        for i in range(len(self._bot_lists)):
            for bot in self._bot_lists[i]:
                bot.handlemessage(ba.DieMessage(immediate=True))
            self._bot_lists[i] = []
Ejemplo n.º 21
0
    def _fade_in(self) -> None:
        for node in self._nodes:
            ba.animate(node, 'opacity', {0: 0.0, 2.0: 1.0})

        # If we were given a lifespan, transition out after it.
        if self._lifespan is not None:
            ba.timer(self._lifespan,
                     ba.WeakCall(self.handlemessage, ba.DieMessage()))
        self._update()
        self._update_timer = ba.Timer(1.0,
                                      ba.WeakCall(self._update),
                                      repeat=True)
Ejemplo n.º 22
0
    def clear(self) -> None:
        """Immediately clear out any bots in the set."""

        # Don't do this if the activity is shutting down or dead.
        activity = ba.getactivity(doraise=False)
        if activity is None or activity.expired:
            return

        for i, bot_list in enumerate(self._bot_lists):
            for bot in bot_list:
                bot.handlemessage(ba.DieMessage(immediate=True))
            self._bot_lists[i] = []
 def update_Scorch(self):
     spaz = self.spazRef()
     if spaz is not None and spaz.is_alive() and spaz.node.exists():
         color = (random.random(),random.random(),random.random())
         if not hasattr(self,"scorchNode") or self.scorchNode == None:
             self.scorchNode = None
             self.scorchNode = ba.newnode("scorch",attrs={"position":(spaz.node.position),"size":1.17,"big":True})
             spaz.node.connectattr("position",self.scorchNode,"position")
         ba.animate_array(self.scorchNode,"color",3,{0:self.scorchNode.color,500:color}, timetype=tt, timeformat=tf)
     else:
         self.scorchTimer = None
         self.scorchNode.delete()
         self.handlemessage(ba.DieMessage())
Ejemplo n.º 24
0
    def handlemessage(self, msg: Any) -> Any:
        assert not self.expired

        if isinstance(msg, ba.PowerupAcceptMessage):
            factory = PowerupBoxFactory.get()
            assert self.node
            if self.poweruptype == 'health':
                ba.playsound(factory.health_powerup_sound,
                             3,
                             position=self.node.position)
            ba.playsound(factory.powerup_sound, 3, position=self.node.position)
            self._powersgiven = True
            self.handlemessage(ba.DieMessage())

        elif isinstance(msg, _TouchedMessage):
            if not self._powersgiven:
                node = ba.getcollision().opposingnode
                node.handlemessage(
                    ba.PowerupMessage(self.poweruptype, sourcenode=self.node))

        elif isinstance(msg, ba.DieMessage):
            if self.node:
                if msg.immediate:
                    self.node.delete()
                else:
                    ba.animate(self.node, 'model_scale', {0: 1, 0.1: 0})
                    ba.timer(0.1, self.node.delete)

        elif isinstance(msg, ba.OutOfBoundsMessage):
            self.handlemessage(ba.DieMessage())

        elif isinstance(msg, ba.HitMessage):
            # Don't die on punches (that's annoying).
            if msg.hit_type != 'punch':
                self.handlemessage(ba.DieMessage())
        else:
            return super().handlemessage(msg)
        return None
Ejemplo n.º 25
0
    def __init__(self, settings: Dict[str, Any]):
        from bastd.actor.scoreboard import Scoreboard
        from bastd.actor import powerupbox
        super().__init__(settings)
        self._scoreboard = Scoreboard()
        self._cheer_sound = ba.getsound("cheer")
        self._chant_sound = ba.getsound("crowdChant")
        self._foghorn_sound = ba.getsound("foghorn")
        self._swipsound = ba.getsound("swip")
        self._whistle_sound = ba.getsound("refWhistle")
        self.puck_model = ba.getmodel("puck")
        self.puck_tex = ba.gettexture("puckColor")
        self._puck_sound = ba.getsound("metalHit")
        self.puck_material = ba.Material()
        self.puck_material.add_actions(actions=(("modify_part_collision",
                                                 "friction", 0.5)))
        self.puck_material.add_actions(
            conditions=("they_have_material", ba.sharedobj('pickup_material')),
            actions=("modify_part_collision", "collide", False))
        self.puck_material.add_actions(
            conditions=(("we_are_younger_than", 100),
                        'and', ("they_have_material",
                                ba.sharedobj('object_material'))),
            actions=("modify_node_collision", "collide", False))
        self.puck_material.add_actions(
            conditions=("they_have_material",
                        ba.sharedobj('footing_material')),
            actions=("impact_sound", self._puck_sound, 0.2, 5))

        # Keep track of which player last touched the puck
        self.puck_material.add_actions(
            conditions=("they_have_material", ba.sharedobj('player_material')),
            actions=(("call", "at_connect",
                      self._handle_puck_player_collide), ))

        # We want the puck to kill powerups; not get stopped by them
        self.puck_material.add_actions(
            conditions=("they_have_material",
                        powerupbox.get_factory().powerup_material),
            actions=(("modify_part_collision", "physical", False),
                     ("message", "their_node", "at_connect", ba.DieMessage())))
        self._score_region_material = ba.Material()
        self._score_region_material.add_actions(
            conditions=("they_have_material", self.puck_material),
            actions=(("modify_part_collision", "collide",
                      True), ("modify_part_collision", "physical", False),
                     ("call", "at_connect", self._handle_score)))
        self._puck_spawn_pos: Optional[Sequence[float]] = None
        self._score_regions: Optional[List[ba.NodeActor]] = None
        self._puck: Optional[Puck] = None
    def handlemessage(self, msg: Any) -> Any:

        if isinstance(msg, ba.PlayerDiedMessage):
            #==
            losingPlayer = msg.getplayer(Player)
            if len(self.myPlayers) > 1:
                if self.playerFromName(self.myPlayers[self.count -
                                                      2]) == losingPlayer:
                    winningPlayer = self.playerFromName(
                        self.myPlayers[self.count - 1])
                else:
                    winningPlayer = self.playerFromName(
                        self.myPlayers[self.count - 2])
                if str(losingPlayer.getname()) in self.myPlayers:
                    self.myPlayers.remove(str(losingPlayer.getname()))
                if winningPlayer.team.survival_seconds <= losingPlayer.team.survival_seconds:
                    winningPlayer.team.survival_seconds = losingPlayer.team.survival_seconds + 1
                else:
                    winningPlayer.team.survival_seconds += 1
                winningPlayer.wins += 1
                if winningPlayer.is_alive() and not len(self.myPlayers) == 1:
                    winningPlayer.actor.handlemessage(
                        ba.DieMessage(immediate=True))
                self.count -= 1
                self.spawnPlayer()
            #==

            # Augment standard behavior.
            super().handlemessage(msg)

            player: Player = msg.getplayer(Player)

            player.lives -= 1
            if player.lives < 0:
                ba.print_error("Got lives < 0 in Elim; this shouldn't happen.")
                player.lives = 0

            # If we have any icons, update their state.

            # Play big death sound on our last death
            # or for every one in solo mode.
            if player.lives == 0:
                ba.playsound(SpazFactory.get().single_player_death_sound)

            # If we hit zero lives, we're dead (and our team might be too).
            if player.lives == 0:
                pass
            else:
                self.respawn_player(player)
Ejemplo n.º 27
0
    def _start_updating(self) -> None:

        # Ok, our delay has passed. Now lets periodically see if we can fade
        # in (if a touch-screen is present we only want to show up if gamepads
        # are connected, etc).
        # Also set up a timer so if we haven't faded in by the end of our
        # duration, abort.
        if self._lifespan is not None:
            self._cancel_timer = ba.Timer(
                self._lifespan,
                ba.WeakCall(self.handlemessage, ba.DieMessage(immediate=True)))
        self._fade_in_timer = ba.Timer(1.0,
                                       ba.WeakCall(self._check_fade_in),
                                       repeat=True)
        self._check_fade_in()  # Do one check immediately.
 def neonLightSwitch(self,shine,Highlight,NameColor):
     spaz = self.spazRef()
     if spaz is not None and spaz.is_alive() and spaz.node.exists():
         color = (random.random(),random.random(),random.random())
         if NameColor: ba.animate_array(spaz.node,"nameColor",3,{0:spaz.node.nameColor,500:ba.safecolor(color)}, timetype=tt, timeformat=tf)
         if shine:color = tuple([min(10., 10 * x) for x in color])
         ba.animate_array(spaz.node,"color",3,{0:spaz.node.color,500:color}, timetype=tt, timeformat=tf)
         if Highlight:
             #print spaz.node.highlight
             color = (random.random(),random.random(),random.random())
             if shine:color = tuple([min(10., 10 * x) for x in color])
             ba.animate_array(spaz.node,"highlight",3,{0:spaz.node.highlight,500:color}, timetype=tt, timeformat=tf)
     else:
         self.neroLightTimer = None
         self.handlemessage(ba.DieMessage())
Ejemplo n.º 29
0
    def handlemessage(self, msg: Any) -> Any:
        if isinstance(msg, ba.DieMessage):
            if self.node:
                self.node.delete()

        elif isinstance(msg, ba.OutOfBoundsMessage):
            if self.node:
                self.handlemessage(ba.DieMessage())

        elif isinstance(msg, ba.HitMessage):
            self.node.handlemessage('impulse', msg.pos[0], msg.pos[1],
                                    msg.pos[2], msg.velocity[0],
                                    msg.velocity[1], msg.velocity[2],
                                    msg.magnitude, msg.velocity_magnitude,
                                    msg.radius, 0, msg.velocity[0],
                                    msg.velocity[1], msg.velocity[2])
Ejemplo n.º 30
0
    def _on_egg_player_collide(self) -> None:
        if not self.has_ended():
            egg_node, playernode = ba.get_collision_info(
                'source_node', 'opposing_node')
            if egg_node is not None and playernode is not None:
                egg = egg_node.getdelegate()
                assert isinstance(egg, Egg)
                spaz = playernode.getdelegate()
                assert isinstance(spaz, playerspaz.PlayerSpaz)
                player = (spaz.getplayer()
                          if hasattr(spaz, 'getplayer') else None)
                if player and egg:
                    player.team.gamedata['score'] += 1

                    # Displays a +1 (and adds to individual player score in
                    # teams mode).
                    self.stats.player_scored(player, 1, screenmessage=False)
                    if self._max_eggs < 5:
                        self._max_eggs += 1.0
                    elif self._max_eggs < 10:
                        self._max_eggs += 0.5
                    elif self._max_eggs < 30:
                        self._max_eggs += 0.3
                    self._update_scoreboard()
                    ba.playsound(self._collect_sound,
                                 0.5,
                                 position=egg.node.position)

                    # Create a flash.
                    light = ba.newnode('light',
                                       attrs={
                                           'position': egg_node.position,
                                           'height_attenuated': False,
                                           'radius': 0.1,
                                           'color': (1, 1, 0)
                                       })
                    ba.animate(light,
                               'intensity', {
                                   0: 0,
                                   0.1: 1.0,
                                   0.2: 0
                               },
                               loop=False)
                    ba.timer(0.200, light.delete)
                    egg.handlemessage(ba.DieMessage())