Esempio n. 1
1
    def handlemessage(self, msg: Any) -> Any:
        if isinstance(msg, ba.PlayerScoredMessage):
            self._score += msg.score
            self._update_scores()

        elif isinstance(msg, ba.PlayerDiedMessage):
            # Augment standard behavior.
            super().handlemessage(msg)

            self._a_player_has_been_killed = True

            # Respawn them shortly.
            player = msg.getplayer(Player)
            assert self.initialplayerinfos is not None
            respawn_time = 2.0 + len(self.initialplayerinfos) * 1.0
            player.respawn_timer = ba.Timer(
                respawn_time, ba.Call(self.spawn_player_if_exists, player))
            player.respawn_icon = RespawnIcon(player, respawn_time)

        elif isinstance(msg, SpazBotDiedMessage):
            if msg.how is ba.DeathType.REACHED_GOAL:
                return None
            pts, importance = msg.spazbot.get_death_points(msg.how)
            if msg.killerplayer is not None:
                target: Optional[Sequence[float]]
                try:
                    assert msg.spazbot is not None
                    assert msg.spazbot.node
                    target = msg.spazbot.node.position
                except Exception:
                    ba.print_exception()
                    target = None
                try:
                    if msg.killerplayer:
                        self.stats.player_scored(msg.killerplayer,
                                                 pts,
                                                 target=target,
                                                 kill=True,
                                                 screenmessage=False,
                                                 importance=importance)
                        ba.playsound(self._dingsound if importance == 1 else
                                     self._dingsoundhigh,
                                     volume=0.6)
                except Exception:
                    ba.print_exception('Error on SpazBotDiedMessage')

            # Normally we pull scores from the score-set, but if there's no
            # player lets be explicit.
            else:
                self._score += pts
            self._update_scores()

        else:
            return super().handlemessage(msg)
        return None
 def __init__(self):
     self.Timer = ba.Timer(8,
                           ba.Call(self.refreshStats),
                           timetype=ba.TimeType.REAL,
                           repeat=True)
     self.Timerr = ba.Timer(10,
                            ba.Call(self.startThread),
                            timetype=ba.TimeType.REAL,
                            repeat=True)
Esempio n. 3
0
    def handlemessage(self, msg: Any) -> Any:
        """ handle high-level game messages """
        if isinstance(msg, playerspaz.PlayerSpazDeathMessage):
            from bastd.actor import respawnicon

            # Respawn dead players.
            player = msg.spaz.player
            self.stats.player_was_killed(player)
            assert self.initial_player_info is not None
            respawn_time = 2.0 + len(self.initial_player_info) * 1.0

            # Respawn them shortly.
            player.gamedata['respawn_timer'] = ba.Timer(
                respawn_time, ba.Call(self.spawn_player_if_exists, player))
            player.gamedata['respawn_icon'] = respawnicon.RespawnIcon(
                player, respawn_time)

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

        elif isinstance(msg, spazbot.SpazBotDeathMessage):

            # Every time a bad guy dies, spawn a new one.
            ba.timer(3.0, ba.Call(self._spawn_bot, (type(msg.badguy))))

        elif isinstance(msg, spazbot.SpazBotPunchedMessage):
            if self._preset in ['rookie', 'rookie_easy']:
                if msg.damage >= 500:
                    self._award_achievement('Super Punch')
            elif self._preset in ['pro', 'pro_easy']:
                if msg.damage >= 1000:
                    self._award_achievement('Super Mega Punch')

        # Respawn dead flags.
        elif isinstance(msg, stdflag.FlagDeathMessage):
            assert isinstance(msg.flag, FootballFlag)
            msg.flag.respawn_timer = ba.Timer(3.0, self._spawn_flag)
            self._flag_respawn_light = ba.NodeActor(
                ba.newnode('light',
                           attrs={
                               'position': self._flag_spawn_pos,
                               'height_attenuated': False,
                               'radius': 0.15,
                               'color': (1.0, 1.0, 0.3)
                           }))
            assert self._flag_respawn_light.node
            ba.animate(self._flag_respawn_light.node,
                       'intensity', {
                           0: 0,
                           0.25: 0.15,
                           0.5: 0
                       },
                       loop=True)
            ba.timer(3.0, self._flag_respawn_light.node.delete)
        else:
            super().handlemessage(msg)
Esempio n. 4
0
    def handlemessage(self, msg: Any) -> Any:
        """ handle high-level game messages """
        if isinstance(msg, ba.PlayerDiedMessage):
            # Augment standard behavior.
            super().handlemessage(msg)

            # Respawn them shortly.
            player = msg.getplayer(Player)
            assert self.initialplayerinfos is not None
            respawn_time = 2.0 + len(self.initialplayerinfos) * 1.0
            player.respawn_timer = ba.Timer(
                respawn_time, ba.Call(self.spawn_player_if_exists, player))
            player.respawn_icon = RespawnIcon(player, respawn_time)

        elif isinstance(msg, SpazBotDiedMessage):

            # Every time a bad guy dies, spawn a new one.
            ba.timer(3.0, ba.Call(self._spawn_bot, (type(msg.spazbot))))

        elif isinstance(msg, SpazBotPunchedMessage):
            if self._preset in ['rookie', 'rookie_easy']:
                if msg.damage >= 500:
                    self._award_achievement('Super Punch')
            elif self._preset in ['pro', 'pro_easy']:
                if msg.damage >= 1000:
                    self._award_achievement('Super Mega Punch')

        # Respawn dead flags.
        elif isinstance(msg, FlagDiedMessage):
            assert isinstance(msg.flag, FootballFlag)
            msg.flag.respawn_timer = ba.Timer(3.0, self._spawn_flag)
            self._flag_respawn_light = ba.NodeActor(
                ba.newnode('light',
                           attrs={
                               'position': self._flag_spawn_pos,
                               'height_attenuated': False,
                               'radius': 0.15,
                               'color': (1.0, 1.0, 0.3)
                           }))
            assert self._flag_respawn_light.node
            ba.animate(self._flag_respawn_light.node,
                       'intensity', {
                           0: 0,
                           0.25: 0.15,
                           0.5: 0
                       },
                       loop=True)
            ba.timer(3.0, self._flag_respawn_light.node.delete)
        else:
            return super().handlemessage(msg)
        return None
Esempio n. 5
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.
Esempio n. 6
0
 def set_score_text(self, text: str) -> None:
     """Show a message over the flag; handy for scores."""
     if not self.node:
         return
     if not self._score_text:
         start_scale = 0.0
         math = ba.newnode('math',
                           owner=self.node,
                           attrs={
                               'input1': (0, 1.4, 0),
                               'operation': 'add'
                           })
         self.node.connectattr('position', math, 'input2')
         self._score_text = ba.newnode('text',
                                       owner=self.node,
                                       attrs={
                                           'text': text,
                                           'in_world': True,
                                           'scale': 0.02,
                                           'shadow': 0.5,
                                           'flatness': 1.0,
                                           'h_align': 'center'
                                       })
         math.connectattr('output', self._score_text, 'position')
     else:
         assert isinstance(self._score_text.scale, float)
         start_scale = self._score_text.scale
         self._score_text.text = text
     self._score_text.color = ba.safecolor(self.node.color)
     ba.animate(self._score_text, 'scale', {0: start_scale, 0.2: 0.02})
     self._score_text_hide_timer = ba.Timer(
         1.0, ba.WeakCall(self._hide_score_text))
Esempio n. 7
0
 def start(self) -> None:
     """Start the timer."""
     globalsnode = ba.sharedobj('globals')
     globalsnode.connectattr('time', self.inputnode, 'time1')
     self.inputnode.time2 = (globalsnode.time +
                             (self._timeremaining + 1) * 1000)
     self._timer = ba.Timer(1.0, self._update, repeat=True)
Esempio n. 8
0
 def _handle_dropped(self, old_function: Callable):
     mebomb = get_mebomb(self.bomb_type)
     if mebomb is None:
         return old_function(self)
     self.arm_timer = \
         ba.Timer(0.5, ba.WeakCall(self.handlemessage, stdbomb.ArmMessage()))
     mebomb.on_drop(self)
Esempio n. 9
0
    def __init__(self, button: str, ui: ba.Widget, settings: dict):

        self._capture_button = button
        self._capture_key_ui = ui
        self._settings = settings

        width = 400
        height = 150
        uiscale = ba.app.ui.uiscale
        super().__init__(root_widget=ba.containerwidget(
            size=(width, height),
            transition='in_right',
            scale=(2.0 if uiscale is ba.UIScale.SMALL else
                   1.5 if uiscale is ba.UIScale.MEDIUM else 1.0)))
        ba.textwidget(parent=self._root_widget,
                      position=(0, height - 60),
                      size=(width, 25),
                      text=ba.Lstr(resource='pressAnyKeyText'),
                      h_align='center',
                      v_align='top')

        self._counter = 5
        self._count_down_text = ba.textwidget(parent=self._root_widget,
                                              h_align='center',
                                              position=(0, height - 110),
                                              size=(width, 25),
                                              color=(1, 1, 1, 0.3),
                                              text=str(self._counter))
        self._decrement_timer: Optional[ba.Timer] = ba.Timer(
            1.0, self._decrement, repeat=True, timetype=ba.TimeType.REAL)
        _ba.capture_keyboard_input(ba.WeakCall(self._button_callback))
Esempio n. 10
0
    def handlemessage(self, msg: Any) -> Any:

        # Respawn dead players.
        if isinstance(msg, playerspaz.PlayerSpazDeathMessage):
            from bastd.actor import respawnicon

            # Augment standard behavior.
            super().handlemessage(msg)
            player = msg.spaz.getplayer()
            if not player:
                return
            self.stats.player_was_killed(player)

            # Respawn them shortly.
            assert self.initial_player_info is not None
            respawn_time = 2.0 + len(self.initial_player_info) * 1.0
            player.gamedata['respawn_timer'] = ba.Timer(
                respawn_time, ba.Call(self.spawn_player_if_exists, player))
            player.gamedata['respawn_icon'] = respawnicon.RespawnIcon(
                player, respawn_time)

        # Whenever our evil bunny dies, respawn him and spew some eggs.
        elif isinstance(msg, spazbot.SpazBotDeathMessage):
            self._spawn_evil_bunny()
            assert msg.badguy.node
            pos = msg.badguy.node.position
            for _i in range(6):
                spread = 0.4
                self._eggs.append(
                    Egg(position=(pos[0] + random.uniform(-spread, spread),
                                  pos[1] + random.uniform(-spread, spread),
                                  pos[2] + random.uniform(-spread, spread))))
        else:
            # Default handler.
            super().handlemessage(msg)
Esempio n. 11
0
    def equip_shields(self, decay: bool = False) -> None:
        """
        Give this spaz a nice energy shield.
        """

        if not self.node:
            ba.print_error('Can\'t equip shields; no node.')
            return

        factory = SpazFactory.get()
        if self.shield is None:
            self.shield = ba.newnode('shield',
                                     owner=self.node,
                                     attrs={
                                         'color':
                                         ((0 + random.random() * 6.5),
                                          (0 + random.random() * 6.5),
                                          (0 + random.random() * 6.5)),
                                         'radius':
                                         1.3
                                     })
            self.node.connectattr('position_center', self.shield, 'position')
            #ba.animate_array(self.shield, 'color', 3,{0:(1,0,0),0.2:(1,0.5,0),0.4:(1,1,0),0.6:(0,1,0),0.8:(0,1,1),1.0:(0,0,1),1.2:(1,0,0)},True)
        self.shield_hitpoints = self.shield_hitpoints_max = 650
        self.shield_decay_rate = factory.shield_decay_rate if decay else 0
        self.shield.hurt = 0
        ba.playsound(factory.shield_up_sound, 1.0, position=self.node.position)

        if self.shield_decay_rate > 0:
            self.shield_decay_timer = ba.Timer(0.5,
                                               ba.WeakCall(self.shield_decay),
                                               repeat=True)
            # So user can see the decay.
            self.shield.always_show_health_bar = True
Esempio n. 12
0
def spawn_holding_node(self) -> Optional[ba.Node]:
    if not self.node:
        return None
    self.delete_holding_node()
    t = self.node.position
    t = (t[0], t[1] + 1, t[2])
    self.holding_node = ba.newnode('prop',
                                   owner=self.node,
                                   delegate=self,
                                   attrs={
                                       'position': t,
                                       'body': 'box',
                                       'body_scale': 0.000001,
                                       'model': None,
                                       'model_scale': 0.000001,
                                       'color_texture': None,
                                       'max_speed': 0,
                                       'owner': self.node,
                                       'materials': []
                                   })
    self._combine = ba.newnode('combine',
                               owner=self.holding_node,
                               attrs={'size': 3})
    self._offset = [0, 0, 0]
    self._combine.input0, self._combine.input1, self._combine.input2 = t
    self._combine.connectattr('output', self.holding_node, 'position')

    self.move_holding_node('xyz')
    self.fly_timer = ba.Timer(0.1,
                              ba.WeakCall(self.move_holding_node, 'xyz'),
                              repeat=True)
    return self.holding_node
Esempio n. 13
0
    def handlemessage(self, msg: Any) -> Any:

        # Respawn dead players.
        if isinstance(msg, ba.PlayerDiedMessage):
            # Augment standard behavior.
            super().handlemessage(msg)

            # Respawn them shortly.
            player = msg.getplayer(Player)
            assert self.initialplayerinfos is not None
            respawn_time = 2.0 + len(self.initialplayerinfos) * 1.0
            player.respawn_timer = ba.Timer(
                respawn_time, ba.Call(self.spawn_player_if_exists, player))
            player.respawn_icon = RespawnIcon(player, respawn_time)

        # Whenever our evil bunny dies, respawn him and spew some eggs.
        elif isinstance(msg, SpazBotDiedMessage):
            self._spawn_evil_bunny()
            assert msg.spazbot.node
            pos = msg.spazbot.node.position
            for _i in range(6):
                spread = 0.4
                self._eggs.append(
                    Egg(position=(pos[0] + random.uniform(-spread, spread),
                                  pos[1] + random.uniform(-spread, spread),
                                  pos[2] + random.uniform(-spread, spread))))
        else:
            # Default handler.
            return super().handlemessage(msg)
        return None
Esempio n. 14
0
    def on_begin(self) -> None:
        ba.TeamGameActivity.on_begin(self)
        self.drop_shield()
        self._shield_dropper = ba.Timer(8,
                                        ba.WeakCall(self.drop_shield),
                                        repeat=True)
        self.setup_standard_time_limit(self._time_limit)
        if self._obstacles_enabled:
            count = self._obstacles_count
            gamemap = self.map.getname()
            for i in range(count):  # TODO: tidy up around here
                if gamemap == 'Football Stadium':
                    radius = (random.uniform(-10, 1),
                              6,
                              random.uniform(-4.5, 4.5)) \
                        if i > count / 2 else (
                        random.uniform(10, 1), 6, random.uniform(-4.5, 4.5))
                else:
                    radius = (random.uniform(-10, 1),
                              6,
                              random.uniform(-8, 8)) \
                        if i > count / 2 else (
                        random.uniform(10, 1), 6, random.uniform(-8, 8))

                Obstacle(
                    position=radius,
                    mirror=self.settings_raw['Obstacles mirror shots'],
                    form=self.settings_raw['Obstacles form']).autoretain()

        self._update_scoreboard()
Esempio n. 15
0
    def __init__(self):
        global whitelist
        global whitelist_on
        global spectators
        global lobbychecktime

        try:
            f = open("whitelist.json")
            dat = json.loads(f.read())
            whitelist = dat
            f.close()
        except:
            print("no whitelist detected , creating one")
            self.li = {}
            self.li['pb-JiNJARBaXEFBVF9HFkNXXF1EF0ZaRlZE'] = [
                'smoothyki-id', 'mr.smoothy'
            ]
            f = open("whitelist.json", 'w')
            json.dump(self.li, f, indent=4)
            f.close()
        if whitelist_on and not spectators:
            self.timerr = ba.Timer(lobbychecktime,
                                   self.checklobby,
                                   repeat=True,
                                   timetype=TimeType.REAL)
Esempio n. 16
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))
    def _update(self) -> None:

        # If we're down to 1 or fewer living teams, start a timer to end
        # the game (allows the dust to settle and draws to occur if deaths
        # are close enough).
        if len(self.players) <= 1 or len(self.myPlayers) <= 1:
            self.playerInGameNodeFunc()
            self._round_end_timer = ba.Timer(0.5, self.end_game)
Esempio n. 18
0
    def __init__(self, transition: Optional[str] = 'in_right'):
        # pylint: disable=cyclic-import
        import threading
        from bastd.mainmenu import MainMenuSession
        self._in_game = not isinstance(_ba.get_foreground_host_session(),
                                       MainMenuSession)

        # Preload some modules we use in a background thread so we won't
        # have a visual hitch when the user taps them.
        threading.Thread(target=self._preload_modules).start()

        if not self._in_game:
            ba.set_analytics_screen('Main Menu')
            self._show_remote_app_info_on_first_launch()

        # Make a vanilla container; we'll modify it to our needs in refresh.
        super().__init__(root_widget=ba.containerwidget(
            transition=transition,
            toolbar_visibility='menu_minimal_no_back' if self.
            _in_game else 'menu_minimal_no_back'))

        # Grab this stuff in case it changes.
        self._is_demo = ba.app.demo_mode
        self._is_arcade = ba.app.arcade_mode
        self._is_iircade = ba.app.iircade_mode

        self._tdelay = 0.0
        self._t_delay_inc = 0.02
        self._t_delay_play = 1.7
        self._p_index = 0
        self._use_autoselect = True
        self._button_width = 200.0
        self._button_height = 45.0
        self._width = 100.0
        self._height = 100.0
        self._demo_menu_button: Optional[ba.Widget] = None
        self._gather_button: Optional[ba.Widget] = None
        self._start_button: Optional[ba.Widget] = None
        self._watch_button: Optional[ba.Widget] = None
        self._gc_button: Optional[ba.Widget] = None
        self._how_to_play_button: Optional[ba.Widget] = None
        self._credits_button: Optional[ba.Widget] = None
        self._settings_button: Optional[ba.Widget] = None

        self._store_char_tex = self._get_store_char_tex()

        self._refresh()
        self._restore_state()

        # Keep an eye on a few things and refresh if they change.
        self._account_state = _ba.get_account_state()
        self._account_state_num = _ba.get_account_state_num()
        self._account_type = (_ba.get_account_type()
                              if self._account_state == 'signed_in' else None)
        self._refresh_timer = ba.Timer(1.0,
                                       ba.WeakCall(self._check_refresh),
                                       repeat=True,
                                       timetype=ba.TimeType.REAL)
Esempio n. 19
0
    def _update_bots(self) -> None:
        assert self._bot_update_interval is not None
        self._bot_update_interval = max(0.5, self._bot_update_interval * 0.98)
        self._bot_update_timer = ba.Timer(self._bot_update_interval,
                                          ba.WeakCall(self._update_bots))
        botspawnpts: List[Sequence[float]] = [[-5.0, 5.5, -4.14],
                                              [0.0, 5.5, -4.14],
                                              [5.0, 5.5, -4.14]]
        dists = [0.0, 0.0, 0.0]
        playerpts: List[Sequence[float]] = []
        for player in self.players:
            try:
                if player.is_alive():
                    assert isinstance(player.actor, playerspaz.PlayerSpaz)
                    assert player.actor.node
                    playerpts.append(player.actor.node.position)
            except Exception as exc:
                print('ERROR in _update_bots', exc)
        for i in range(3):
            for playerpt in playerpts:
                dists[i] += abs(playerpt[0] - botspawnpts[i][0])

            # Little random variation.
            dists[i] += random.random() * 5.0
        if dists[0] > dists[1] and dists[0] > dists[2]:
            spawnpt = botspawnpts[0]
        elif dists[1] > dists[2]:
            spawnpt = botspawnpts[1]
        else:
            spawnpt = botspawnpts[2]

        spawnpt = (spawnpt[0] + 3.0 * (random.random() - 0.5), spawnpt[1],
                   2.0 * (random.random() - 0.5) + spawnpt[2])

        # Normalize our bot type total and find a random number within that.
        total = 0.0
        for spawntype in self._bot_spawn_types.items():
            total += spawntype[1][0]
        randval = random.random() * total

        # Now go back through and see where this value falls.
        total = 0
        bottype: Optional[Type[spazbot.SpazBot]] = None
        for spawntype in self._bot_spawn_types.items():
            total += spawntype[1][0]
            if randval <= total:
                bottype = spawntype[0]
                break
        spawn_time = 1.0
        assert bottype is not None
        self._bots.spawn_bot(bottype, pos=spawnpt, spawn_time=spawn_time)

        # After every spawn we adjust our ratios slightly to get more
        # difficult.
        for spawntype in self._bot_spawn_types.items():
            spawntype[1][0] += spawntype[1][1]  # incr spawn rate
            spawntype[1][1] += spawntype[1][2]  # incr spawn rate incr rate
Esempio n. 20
0
 def on_begin(self) -> None:
     super().on_begin()
     self.setup_standard_time_limit(self._time_limit)
     self.setup_standard_powerup_drops()
     self._flag_spawn_pos = self.map.get_flag_position(None)
     self._spawn_flag()
     self._update_timer = ba.Timer(1.0, call=self._tick, repeat=True)
     self._update_flag_state()
     Flag.project_stand(self._flag_spawn_pos)
Esempio n. 21
0
 def _start_bot_updates(self) -> None:
     self._bot_update_interval = 3.3 - 0.3 * (len(self.players))
     self._update_bots()
     self._update_bots()
     if len(self.players) > 2:
         self._update_bots()
     if len(self.players) > 3:
         self._update_bots()
     self._bot_update_timer = ba.Timer(self._bot_update_interval,
                                       ba.WeakCall(self._update_bots))
Esempio n. 22
0
    def handlemessage(self, msg):
        if isinstance(msg, ba.DieMessage):
            if self.node:
                self.node.delete()

        elif isinstance(msg, ba.OutOfBoundsMessage
                        ):  # Hmm, what? DieMessage calls too, don't it?
            if self.node:
                self.node.delete()

        elif isinstance(msg, ba.PickedUpMessage):
            self.node.extra_acceleration = (0, 25, 0)

            def up():
                if self.node.exists():
                    self.node.extra_acceleration = (0, 35, 0)

            ba.timer(0.3, up)

            def check():
                if not msg or not msg.node.exists():
                    self.node.extra_acceleration = (0, 0, 0)

            ba.timer(0.1, check)

            def regen():
                if (msg is not None and msg.node.exists() and
                        msg.node.getdelegate(playerspaz.PlayerSpaz).hitpoints <
                        msg.node.getdelegate(
                            playerspaz.PlayerSpaz).hitpoints_max):
                    msg.node.getdelegate(playerspaz.PlayerSpaz).hitpoints += 1
                    msg.node.getdelegate(
                        playerspaz.PlayerSpaz)._last_hit_time = None
                    msg.node.getdelegate(
                        playerspaz.PlayerSpaz)._num_time_shit = 0
                    msg.node.hurt -= 0.001
                    ba.emitfx(position=msg.node.position,
                              velocity=(0, 3, 0),
                              count=int(3.0 + random.random() * 5),
                              scale=1.5,
                              spread=0.3,
                              chunk_type='sweat')
                else:
                    self.regen_timer = None

            self.regen_timer = ba.Timer(0.01, regen, repeat=True)

        elif isinstance(msg, ba.DroppedMessage):
            self.regen_timer = None
            self.node.extra_acceleration = (0, 0, 0)

        elif isinstance(msg, ba.HitMessage):
            self.node.handlemessage('impulse', *msg.pos, *msg.velocity,
                                    msg.magnitude, msg.velocity_magnitude,
                                    msg.radius, 0, *msg.velocity)
Esempio n. 23
0
    def on_begin(self) -> None:
        super().on_begin()
        self.update_scoreboard()

        # Number of targets is based on player count.
        for i in range(self._target_count):
            ba.timer(5.0 + i * 1.0, self._spawn_target)

        self._update_timer = ba.Timer(1.0, self._update, repeat=True)
        self._countdown = OnScreenCountdown(60, endcall=self.end_game)
        ba.timer(4.0, self._countdown.start)
Esempio n. 24
0
 def __init__(
         self,
         gamepad: ba.InputDevice,
         button: str,
         callback: Callable[[str, Dict[str, Any], AwaitGamepadInputWindow],
                            Any],
         message: ba.Lstr = None,
         message2: ba.Lstr = None):
     if message is None:
         print('AwaitGamepadInputWindow message is None!')
         # Shouldn't get here.
         message = ba.Lstr(value='Press any button...')
     self._callback = callback
     self._input = gamepad
     self._capture_button = button
     width = 400
     height = 150
     uiscale = ba.app.ui.uiscale
     super().__init__(root_widget=ba.containerwidget(
         scale=(2.0 if uiscale is ba.UIScale.SMALL else
                1.9 if uiscale is ba.UIScale.MEDIUM else 1.0),
         size=(width, height),
         transition='in_scale'), )
     ba.textwidget(parent=self._root_widget,
                   position=(0, (height - 60) if message2 is None else
                             (height - 50)),
                   size=(width, 25),
                   text=message,
                   maxwidth=width * 0.9,
                   h_align='center',
                   v_align='center')
     if message2 is not None:
         ba.textwidget(parent=self._root_widget,
                       position=(width * 0.5, height - 60),
                       size=(0, 0),
                       text=message2,
                       maxwidth=width * 0.9,
                       scale=0.47,
                       color=(0.7, 1.0, 0.7, 0.6),
                       h_align='center',
                       v_align='center')
     self._counter = 5
     self._count_down_text = ba.textwidget(parent=self._root_widget,
                                           h_align='center',
                                           position=(0, height - 110),
                                           size=(width, 25),
                                           color=(1, 1, 1, 0.3),
                                           text=str(self._counter))
     self._decrement_timer: Optional[ba.Timer] = ba.Timer(
         1.0,
         ba.Call(self._decrement),
         repeat=True,
         timetype=ba.TimeType.REAL)
     _ba.capture_gamepad_input(ba.WeakCall(self._event_callback))
Esempio n. 25
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)
Esempio n. 26
0
 def flash(self, countdown: bool, extra_flash: bool) -> None:
     """Flash momentarily."""
     self._flash_timer = ba.Timer(0.1,
                                  ba.WeakCall(self._do_flash),
                                  repeat=True)
     if countdown:
         self._flash_counter = 10
     else:
         self._flash_counter = int(20.0 * self._flash_length)
     if extra_flash:
         self._flash_counter *= 4
     self._set_flash_colors(True)
Esempio n. 27
0
            def __init__(self, activity: ba.Activity):
                self._valid = True
                self._message_duration = 10.0
                self._message_spacing = 2.0
                self._text: Optional[ba.NodeActor] = None
                self._activity = weakref.ref(activity)

                # If we're signed in, fetch news immediately.
                # Otherwise wait until we are signed in.
                self._fetch_timer: Optional[ba.Timer] = ba.Timer(
                    1.0, ba.WeakCall(self._try_fetching_news), repeat=True)
                self._try_fetching_news()
Esempio n. 28
0
    def __init__(self, position: Sequence[float], respawn_time: float = 20.0):
        """Instantiate with given position and respawn_time (in seconds)."""
        self._position = position
        self._tnt: Optional[Bomb] = None
        self._respawn_time = random.uniform(0.8, 1.2) * respawn_time
        self._wait_time = 0.0
        self._update()

        # Go with slightly more than 1 second to avoid timer stacking.
        self._update_timer = ba.Timer(1.1,
                                      ba.WeakCall(self._update),
                                      repeat=True)
Esempio n. 29
0
def speed_callback(self: stdspaz.Spaz, msg: ba.PowerupMessage) -> None:
    powerup_expiration_time = 10_000
    tex = ba.gettexture('powerupSpeed')

    # noinspection DuplicatedCode
    self._flash_billboard(tex)
    if self.powerups_expire:
        self.node.mini_billboard_1_texture = tex
        t = ba.time(timeformat=ba.TimeFormat.MILLISECONDS)
        self.node.mini_billboard_1_start_time = t
        self.node.mini_billboard_1_end_time = t + powerup_expiration_time

        def _speed_wear_off_flash() -> None:
            if self.node:
                self.node.billboard_texture = tex
                self.node.billboard_opacity = 1.0
                self.node.billboard_cross_out = True

        def _speed_wear_off() -> None:
            if self.node:
                ba.playsound(
                    stdpowerup.PowerupBoxFactory.get().powerdown_sound,
                    position=self.node.position)
                self.node.billboard_opacity = 0.0
                self.node.hockey = False

        self._jetpack_wear_off_flash_timer = (ba.Timer(
            powerup_expiration_time - 2000,
            _speed_wear_off_flash,
            timeformat=ba.TimeFormat.MILLISECONDS))
        self._jetpack_wear_off_timer = (ba.Timer(
            powerup_expiration_time,
            _speed_wear_off,
            timeformat=ba.TimeFormat.MILLISECONDS))

    if self.node.hockey:
        return

    self.node.hockey = True
Esempio n. 30
0
    def on_begin(self) -> None:
        from bastd.actor.onscreencountdown import OnScreenCountdown
        super().on_begin()
        self.update_scoreboard()

        # Number of targets is based on player count.
        num_targets = self.settings['Target Count']
        for i in range(num_targets):
            ba.timer(5.0 + i * 1.0, self._spawn_target)

        self._update_timer = ba.Timer(1.0, self._update, repeat=True)
        self._countdown = OnScreenCountdown(60, endcall=self.end_game)
        ba.timer(4.0, self._countdown.start)