BombSquadCore Python API

last updated on 2018-11-14 for BombSquad version 1.5.0 build 20000

This page documents the Python classes and functions in the 'bs' module,
which are the ones most relevant to modding BombSquad. If you come across something you feel should be included here or could be better explained, please let me know. Happy modding!


Table of Contents

Gameplay Classes

Gameplay Functions

General Utility Classes

General Utility Functions

Media Classes

Media Functions

Message Classes

User Interface Classes

User Interface Functions

Misc

Misc


bs.Activity

<top level class>

Units of execution wrangled by a bs.Session.

category: Gameplay Classes

Examples of Activities include games, score-screens, cutscenes, etc.
A bs.Session has one 'current' Activity at any time, though their existence
can overlap during transitions.

Attributes:

players, settings, teams

players

The list of bs.Players in the Activity. This gets populated just
before on_begin() is called and is updated automatically as players
join or leave the game.

settings

The settings dict passed in when the activity was made.

teams

The list of bs.Teams in the Activity. This gets populated just before
on_begin() is called and is updated automatically as players join or
leave the game. (at least in free-for-all mode where every player
gets their own team; in teams mode there are always 2 teams
regardless of the player count).

Methods:

<constructor>, add_actor_weak_ref(), create_player_node(), end(), getsession(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_transitioning_out(), on_begin(), on_expire(), on_player_join(), on_player_leave(), on_team_join(), on_team_leave(), on_transition_in(), on_transition_out(), retain_actor()

<constructor>

bs.Activity(settings)

Creates an activity in the current bs.Session.

The activity will not be actually run until bs.Session.setactivity()
is called. 'settings' should be a dict of key/value pairs specific
to the activity.

Activities should preload as much of their media/etc as possible in
their constructor, but none of it should actually be used until they
are transitioned in.

add_actor_weak_ref()

add_actor_weak_ref(self, actor)

Add a weak-reference to a bs.Actor to the bs.Activity.

(called by the bs.Actor base class)

create_player_node()

create_player_node(self, player)

Create the 'player' node associated with the provided bs.Player.

end()

end(self, results=None, delay=0, force=False)

Commences Activity shutdown and delivers results to the bs.Session.

'delay' is the time delay before the Activity actually ends
(in seconds). Further calls to end() will be ignored up until
this time, unless 'force' is True, in which case the new results
will replace the old.

getsession()

getsession(self)

Return the bs.Session this bs.Activity belongs to.

If the Session no longer exists, returns None.

handlemessage()

handlemessage(self, msg)

General message handling; can be passed any message object.

has_begun()

has_begun(self)

Return whether on_begin() has been called.

has_ended()

has_ended(self)

Return whether the activity has commenced ending.

has_transitioned_in()

has_transitioned_in(self)

Return whether on_transition_in() has been called.

is_expired()

is_expired(self)

Return whether the activity is expired.

An activity is set as expired when shutting down.
At this point no new nodes, timers, etc should be made,
run, etc, and the activity should be considered a 'zombie'.

is_transitioning_out()

is_transitioning_out(self)

Return whether on_transition_out() has been called.

on_begin()

on_begin(self)

Called once the previous bs.Activity has finished transitioning out.

At this point the activity's initial players and teams are filled in
and it should begin its actual game logic.

on_expire()

on_expire(self)

Called when your activity is being expired.

If your activity has created anything explicitly that may be retaining
a strong reference to the activity and preventing it from dying, you
should clear that out here. From this point on your activity's sole
purpose in life is to hit zero references and die so the next activity
can begin.

on_player_join()

on_player_join(self, player)

Called when a new bs.Player has joined the Activity.

(including the initial set of Players)

on_player_leave()

on_player_leave(self, player)

Called when a bs.Player is leaving the Activity.

on_team_join()

on_team_join(self, team)

Called when a new bs.Team joins the Activity.

(including the initial set of Teams)

on_team_leave()

on_team_leave(self, team)

Called when a bs.Team leaves the Activity.

on_transition_in()

on_transition_in(self)

Called when the Activity is first becoming visible.

Upon this call, the Activity should fade in backgrounds,
start playing music, etc. It does not yet have access to bs.Players
or bs.Teams, however. They remain owned by the previous Activity
up until bs.Activity.on_begin() is called.

on_transition_out()

on_transition_out(self)

Called when your activity begins transitioning out.

Note that this may happen at any time even if finish() has not been
called.

retain_actor()

retain_actor(self, actor)

Add a strong-reference to a bs.Actor to this Activity.

The referene will be lazily released once bs.Actor.exists()
returns False for the Actor. The bs.Actor.autoretain() method
is a convenient way to access this same functionality.


bs.Actor

<top level class>

High level logical entities in a game/activity.

category: Gameplay Classes

Actors act as controllers, combining some number of bs.Nodes,
bs.Textures, bs.Sounds, etc. into one cohesive unit.

Some example actors include bs.Bomb, bs.Flag, and bs.Spaz.

One key feature of Actors is that they generally 'die'
(killing off or transitioning out their nodes) when the last Python
reference to them disappears, so you can use logic such as:

    # create a flag Actor in our game activity
    self.flag = bs.Flag(position=(0, 10, 0))
    # later, destroy the flag..
    # (provided nothing else is holding a reference to it)
    # we could also just assign a new flag to this value.
    # either way, the old flag disappears.
    self.flag = None

This is in contrast to the behavior of the more low level bs.Nodes,
which are always explicitly created and destroyed and don't care
how many Python references to them exist.

Note, however, that you can use the bs.Actor.autoretain() method
if you want an Actor to stick around until explicitly killed
regardless of references.

Another key feature of bs.Actor is its handlemessage() method, which
takes a single arbitrary object as an argument. This provides a safe way
to communicate between bs.Actor, bs.Activity, bs.Session, and any other
class providing a handlemessage() method. The most universally handled
message type for actors is the bs.DieMessage.

    # another way to kill the flag from the example above:
    # we can safely call this on any type with a 'handlemessage' method
    # (though its not guaranteed to always have a meaningful effect)
    # in this case the Actor instance will still be around, but its exists()
    # and is_alive() methods will both return False
    self.flag.handlemessage(bs.DieMessage())

Methods:

<constructor>, autoretain(), exists(), getactivity(), handlemessage(), is_alive(), is_expired(), on_expire()

<constructor>

bs.Actor(node=None)

Instantiates an Actor in the current bs.Activity.

If 'node' is provided, it is stored as the 'node' attribute
and the default bs.Actor.handlemessage() and bs.Actor.exists()
implementations will apply to it. This allows the creation of
simple node-wrapping Actors without having to create a new subclass.

autoretain()

autoretain(self)

Keep this Actor alive without needing to hold a reference to it.

This keeps the bs.Actor in existence by storing a reference to it
with the bs.Activity it was created in. The reference is lazily
released once bs.Actor.exists() returns False for it or when the
Activity is set as expired. This can be a convenient alternative
to storing references explicitly just to keep a bs.Actor from dying.
For convenience, this method returns the bs.Actor it is called with,
enabling chained statements such as: myflag = bs.Flag().autoretain()

exists()

exists(self)

Returns whether the Actor is still present in a meaningful way.

Note that a dying character should still return True here as long as
their corpse is visible; this is about presence, not being 'alive'
(see bs.Actor.is_alive() for that).

If this returns False, it is assumed the Actor can be completely
deleted without affecting the game; this call is often used
when pruning lists of Actors, such as with bs.Actor.autoretain()

The default implementation of this method returns 'node.exists()'
if the Actor has a 'node' attr; otherwise True.

Note that the boolean operator for the Actor class calls this method,
so a simple "if myactor" test will conveniently do the right thing
even if myactor is set to None.

getactivity()

getactivity(self, doraise=True)

Return the bs.Activity this Actor is associated with.

If the Activity no longer exists, raises an Exception
or returns None depending on whether 'doraise' is set.

handlemessage()

handlemessage(self, msg)

General message handling; can be passed any message object.

The default implementation will handle bs.DieMessages by
calling self.node.delete() if self contains a 'node' attribute.

is_alive()

is_alive(self)

Returns whether the Actor is 'alive'.

What this means is up to the Actor.
It is not a requirement for Actors to be
able to die; just that they report whether
they are Alive or not.

is_expired()

is_expired(self)

Returns whether the Actor is expired.

(see bs.Actor.on_expire())

on_expire()

on_expire(self)

Called for remaining bs.Actors when their bs.Activity shuts down.

Actors can use this opportunity to clear callbacks
or other references which have the potential of keeping the
bs.Activity alive inadvertently (Activities can not exit cleanly while
any Python references to them remain.)

Once an actor is expired (see bs.Actor.is_expired()) it should no
longer perform any game-affecting operations (creating, modifying,
or deleting nodes, media, timers, etc.) Attempts to do so will
likely result in errors.


bs.App

<top level class>

A class for high level app functionality and state.

category: General Utility Classes

Use bs.app() to access the single shared instance of this class.

Note that properties not documented here should be considered internal
and subject to change without warning.

Attributes:

build_number, config, config_file_path, debug_build, interface_type, language, locale, on_tv, platform, subplatform, system_scripts_directory, test_build, ui_bounds, user_agent_string, user_scripts_directory, version, vr_mode

build_number

Integer build number.

This value increases by at least 1 with each release of the game.
It is independent of the human readable bs.App.version string.

config

The bs.AppConfig instance representing the app's config state.

config_file_path

Where the game's config file is stored on disk.

debug_build

Whether the game was compiled in debug mode.

Debug builds generally run substantially slower than non-debug
builds due to compiler optimizations being disabled and extra
checks being run.

interface_type

Interface mode the game is in; can be 'large', 'medium', or 'small'.

'large' is used by system such as desktop PC where elements on screen
remain usable even at small sizes, allowing more to be shown.
'small' is used by small devices such as phones, where elements on
screen must be larger to remain readable and usable.
'medium' is used by tablets and other middle-of-the-road situations
such as VR or TV.

language

The name of the language the game is running in.

This can be selected explicitly by the user or may be set
automatically based on bs.App.locale or other factors.

locale

Raw country/language code detected by the game (such as 'en_US').

Generally for language-specific code you should look at
bs.App.language, which is the language the game is using
(which may differ from locale if the user sets a language, etc.)

on_tv

Bool value for if the game is running on a TV.

platform

Name of the current platform.

Examples are: 'mac', 'windows', android'.

subplatform

String for subplatform.

Can be empty. For the 'android' platform, subplatform may
be 'google', 'amazon', etc.

system_scripts_directory

Path where the game is looking for its bundled scripts.

test_build

Whether the game was compiled in test mode.

Test mode enables extra checks and features that are useful for
release testing but which do not slow the game down significantly.

ui_bounds

Bounds of the 'safe' screen area in ui space.

This tuple contains: (x-min, x-max, y-min, y-max)

user_agent_string

String containing various bits of info about OS/device/etc.

user_scripts_directory

Path where the game is looking for custom user scripts.

version

Human-readable version string; something like '1.3.24'.

This should not be interpreted as a number; it may contain
string elements such as 'alpha', 'beta', 'test', etc.
If a numeric version is needed, use 'bs.App.build_number'.

vr_mode

Bool value for if the game is running in VR.

Methods:

handle_app_pause(), handle_app_resume(), handle_deep_link(), launch_coop_game(), pause(), resume(), return_to_main_menu_session_gracefully()

handle_app_pause()

handle_app_pause(self)

Called when the app goes to a suspended state.

handle_app_resume()

handle_app_resume(self)

Run when the app resumes from a suspended state.

handle_deep_link()

handle_deep_link(self, url)

Handle a deep link URL.

launch_coop_game()

launch_coop_game(self, game, force=False, args=None)

High level way to launch a co-op session locally.

pause()

pause(self)

Pause the game due to a user request or menu popping up.

If there's a foreground host-activity that says it's pausable, tell it
to pause ..we now no longer pause if there are connected clients.

resume()

resume(self)

Resume the game due to a user request or menu closing.

If there's a foreground host-activity that's currently paused, tell it
to resume.

return_to_main_menu_session_gracefully()

return_to_main_menu_session_gracefully(self)

Attempt to cleanly get back to the main menu.


bs.AppConfig

inherits from: dict

A special dict that holds the game's persistant configuration values.

category: General Utility Classes

It also provides methods for fetching values with app-defined fallback
defaults, applying contained values to the game, and committing the
config to storage.

Call bs.appconfig() to get the single shared instance of this class.

AppConfig data is stored as json on disk on so make sure to only place
json-friendly values in it (dict, list, str, float, int, bool).
Be aware that tuples will be quietly converted to lists.

Methods Defined or Overridden:

apply(), apply_and_commit(), builtin_keys(), commit(), default_value(), resolve()

apply()

apply(self)

Apply config values to the running app.

apply_and_commit()

apply_and_commit(self)

Run apply() followed by commit(); for convenience.

(This way the commit() will not occur if apply() hits invalid data)

builtin_keys()

builtin_keys(self)

Return the list of valid key names recognized by bs.AppConfig.

This set of keys can beused with resolve(), default_value(), etc.
It does not vary across platforms and may include keys that are
obsolete or not relevant on the current running version. (for instance
VR related keys on non-VR platforms). This is to minimize the amount
of platform checking necessary)

Note that it is perfectly legal to store arbitrary named data in the
config, but in that case it is up to the user to test for the existence
of the key in the config dict, fall back to consistent defaults, etc.

commit()

commit(self)

Commits the config to local storage.

Note that this call is asynchronous so the actual write to disk may not
occur immediately.

default_value()

default_value(self, key)

Given a string key, return its predefined default value.

This is the value that will be returned by bs.AppConfig.resolve() if
the key is not present in the config dict or of an incompatible type.

Raises an Exception for unrecognized key names. To get the list of keys
supported by this method, use bs.AppConfig.builtin_keys(). Note that it
is perfectly legal to store other data in the config; it just needs to
be accessed through standard dict methods and missing values handled
manually.

resolve()

resolve(self, key)

Given a string key, return a config value (type varies).

This will substitute application defaults for values not present in
the config dict, filter some invalid values, etc. Note that these
values do not represent the state of the app; simply the state of its
config. Use bs.App to access actual live state.

Raises an Exception for unrecognized key names. To get the list of keys
supported by this method, use bs.AppConfig.builtin_keys(). Note that it
is perfectly legal to store other data in the config; it just needs to
be accessed through standard dict methods and missing values handled
manually.


bs.Call

<top level class>

Wraps a callable and arguments into a single callable object.

category: General Utility Classes

The callable is strong-referenced so it won't die until this object does.
Note that a bound method (ex: myobj.dosomething) contains a reference
to 'self' (myobj in that case), so you will be keeping that object alive
too. Use bs.WeakCall if you want to pass a method to callback without
keeping its object alive.

Methods:

<constructor>

bs.Call(*args, **keywds)

Instantiate a Call; pass a callable as the first
arg, followed by any number of arguments or keywords.

# example: wrap a method call with 1 positional and 1 keyword arg
mycall = bs.Call(myobj.dostuff, argval1, namedarg=argval2)
# now we have a single callable to run that whole mess
# this is the same as calling myobj.dostuff(argval1, namedarg=argval2)
mycall()

bs.CollideModel

<top level class>

A reference to a collide-model.

category: Media Classes

Use bs.getcollidemodel() to instantiate one.


bs.Context

<top level class>

Context(source)

A game context state.

category: General Utility Classes

Many operations such as bs.newnode() or bs.gettexture() operate
implicitly on the current context. Each bs.Activity has its own Context and objects within that activity (nodes, media, etc) can only
interact with other objects from that context.

In general, as a modder, you should not need to worry about contexts,
since timers and other callbacks will take care of saving and
restoring the context automatically, but there may be rare cases where
you need to deal with them, such as when loading media in for use in
the UI (there is a special 'ui' context for all user-interface-related
functionality)

When instantiating a bs.Context instance, a single 'source' argument
is passed, which can be one of the following strings/objects:

'empty':
Gives an empty context; it can be handy to run code here to ensure
it does no loading of media, creation of nodes, etc.

'current':
Sets the context object to the current context.

'ui':
Sets to the UI context. UI functions as well as loading of media to
be used in said functions must happen in the UI context.

a bs.Activity instance:
Gives the context for the provided bs.Activity.
Most all code run during a game happens in an Activity's Context.

a bs.Session instance:
Gives the context for the provided bs.Session.
Generally a user should not need to run anything here.


Usage:

Contexts are generally used with the python 'with' statement, which
sets the context as current on entry and resets it to the previous
value on exit.

# example: load a few textures into the UI context
# (for use in widgets, etc)
with bs.Context('ui'):
   tex1 = bs.gettexture('foo_tex_1')
   tex2 = bs.gettexture('foo_tex_2')

bs.ContextCall

<top level class>

ContextCall(call)

A context-preserving callable.

category: General Utility Classes

A ContextCall wraps a callable object along with a reference
to the current context (see bs.Context); it handles restoring the
context when run and automatically clears itself if the context
it belongs to shuts down.

Generally you should not need to use this directly; all standard
BombSquad callbacks involved with timers, materials, UI functions,
etc. handle this under-the-hood you don't have to worry about it.
The only time it may be necessary is if you are implementing your
own callbacks, such as a worker thread that does some action and then
runs some game code when done. By wrapping said callback in one of
these, you can ensure that you will not inadvertantly be keeping the
current activity alive or running code in a torn-down (expired)
context.

You can also use bs.WeakCall for similar functionality, but
ContextCall has the added bonus that it will not run during context
shutdown, whereas bs.WeakCall simply looks at whether the target
object still exists.

# example A: code like this can inadvertantly prevent our activity
# (self) from ending until the operation completes, since the bound
# method we're passing (self.dosomething) contains a strong-reference
# to self).
start_some_long_action(callback_when_done=self.dosomething)
# example B: in this case our activity (self) can still die
# properly; the callback will clear itself when the activity starts
# shutting down, becoming a harmless no-op and releasing the reference
# to our activity.
start_long_action(callback_when_done=bs.ContextCall(self.mycallback))

bs.CoopGameActivity

inherits from: bs.GameActivity, bs.Activity

Base class for cooperative-mode games.

category: Gameplay Classes

Attributes Inherited:

players, settings, teams

Methods Inherited:

add_actor_weak_ref(), camera_flash(), continue_or_end_game(), create_config_ui(), create_player_node(), end(), end_game(), get_config_display_string(), get_description(), get_description_display_string(), get_display_string(), get_instance_description(), get_instance_display_string(), get_instance_scoreboard_description(), get_instance_scoreboard_display_string(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), getmap(), getname(), getsession(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_transitioning_out(), is_waiting_for_continue(), on_continue(), on_expire(), on_player_join(), on_player_leave(), on_team_join(), on_team_leave(), on_transition_in(), on_transition_out(), project_flag_stand(), respawn_player(), retain_actor(), set_has_ended(), set_immediate_end(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_info(), show_scoreboard_info(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), start_transition_in()

Methods Defined or Overridden:

<constructor>, celebrate(), fade_to_red(), get_score_type(), on_begin(), setup_low_life_warning_sound(), spawn_player_spaz(), supports_session_type()

<constructor>

bs.CoopGameActivity(settings)

Instantiate the Activity.

celebrate()

celebrate(self, duration)

Tells all existing player-controlled characters to celebrate.

Can be useful in co-op games when the good guys score or complete
a wave.
duration is given in seconds.

fade_to_red()

fade_to_red(self)

Fade the screen to red; (such as when the good guys have lost).

get_score_type()

get_score_type(self)

Return the score unit this co-op game uses ('point', 'seconds', etc.)

on_begin()

on_begin(self)

Called once the previous bs.Activity has finished transitioning out.

At this point the activity's initial players and teams are filled in
and it should begin its actual game logic.

setup_low_life_warning_sound()

setup_low_life_warning_sound(self)

Set up a beeping noise to play when any players are near death.

spawn_player_spaz()

spawn_player_spaz(self, player, position, angle=None)

Spawn and wire up a standard player spaz.

supports_session_type()

<class method>

supports_session_type(sessiontype)

Return whether this game supports the provided Session class.


bs.CoopSession

inherits from: bs.Session

A bs.Session which runs cooperative-mode games.

category: Gameplay Classes

These generally consist of 1-4 players against
the computer and include functionality such as
high score lists.

Attributes Inherited:

campaign, lobby, max_players, min_players, players, teams

Methods Inherited:

begin_next_activity(), end(), end_activity(), getactivity(), handlemessage(), launch_end_session_activity(), on_player_request(), on_team_join(), on_team_leave(), setactivity()

Methods Defined or Overridden:

<constructor>, get_current_game_instance(), get_custom_menu_entries(), on_activity_end(), on_player_leave(), restart()

<constructor>

bs.CoopSession()

Instantiate a co-op mode session.

get_current_game_instance()

get_current_game_instance(self)

Get the game instance currently being played.

get_custom_menu_entries()

get_custom_menu_entries(self)

Subclasses can override this to provide custom menu entries.

The returned value should be a list of dicts, each containing
a 'label' and 'call' entry, with 'label' being the text for
the entry and 'call' being the callable to trigger if the entry
is pressed.

on_activity_end()

on_activity_end(self, activity, results)

Method override for co-op sessions.

Jumps between co-op games and score screens.

on_player_leave()

on_player_leave(self, player)

Called when a previously-accepted bs.Player leaves the session.

restart()

restart(self)

Restart the current game activity.


bs.DieMessage

<top level class>

A message telling an object to die.

category: Message Classes

Most bs.Actors respond to this.

Attributes:

how, immediate

how

The particular reason for death; 'fall', 'impact', 'leftGame', etc.
This can be examined for scoring or other purposes.

immediate

If this is set to True, the actor should disappear immediately.
This is for 'removing' stuff from the game moreso than 'killing' it.
If False, the actor should die a 'normal' death and can take its time
with lingering corpses, sound effects, etc.

Methods:

<constructor>

bs.DieMessage(immediate=False, how='generic')

Instantiate with the given values.


bs.DropMessage

<top level class>

Tells an object that it has dropped what it was holding.

category: Message Classes


bs.DroppedMessage

<top level class>

Tells an object that it has been dropped.

category: Message Classes

Attributes:

node

The bs.Node doing the dropping.

Methods:

<constructor>

bs.DroppedMessage(node)

Instantiate with a given bs.Node.


bs.FreeForAllSession

inherits from: bs.TeamBaseSession, bs.Session

bs.Session type for free-for-all mode games.

category: Gameplay Classes

Attributes Inherited:

campaign, lobby, max_players, min_players, players, teams

Methods Inherited:

announce_game_results(), begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), get_ffa_series_length(), get_game_number(), get_max_players(), get_next_game_description(), get_series_length(), getactivity(), handlemessage(), launch_end_session_activity(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity()

Methods Defined or Overridden:

<constructor>

bs.FreeForAllSession()

Set up playlists and launches a bs.Activity to accept joiners.


bs.FreezeMessage

<top level class>

Tells an object to become frozen.

category: Message Classes

As seen in the effects of an ice bs.Bomb.


bs.GameActivity

inherits from: bs.Activity

Common base class for all game bs.Activities.

category: Gameplay Classes

Attributes Inherited:

players, settings, teams

Methods Inherited:

add_actor_weak_ref(), create_player_node(), getsession(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_transitioning_out(), on_expire(), on_team_join(), on_team_leave(), on_transition_out(), retain_actor(), set_has_ended(), set_immediate_end(), start_transition_in()

Methods Defined or Overridden:

<constructor>, camera_flash(), continue_or_end_game(), create_config_ui(), end(), end_game(), get_config_display_string(), get_description(), get_description_display_string(), get_display_string(), get_instance_description(), get_instance_display_string(), get_instance_scoreboard_description(), get_instance_scoreboard_display_string(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), getmap(), getname(), handlemessage(), is_waiting_for_continue(), on_begin(), on_continue(), on_player_join(), on_player_leave(), on_transition_in(), project_flag_stand(), respawn_player(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_info(), show_scoreboard_info(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), spawn_player_spaz(), supports_session_type()

<constructor>

bs.GameActivity(settings)

Instantiate the Activity.

camera_flash()

camera_flash(self, duration=999)

Create a strobing camera flash effect.

(as seen when a team wins a game)

continue_or_end_game()

continue_or_end_game(self)

If continues are allowed, prompts the player to purchase a continue
and calls either end_game or continue_game depending on the result

create_config_ui()

<class method>

create_config_ui(sessionclass, config, completion_call)

Launch an in-game UI to configure settings for a game type.

'sessionclass' should be the bs.Session class the game will be used in.

'config' should be an existing config dict (specifies 'edit' ui mode)
or None (specifies 'add' ui mode).

'completion_call' will be called with a filled-out config dict on
success or None on cancel.

Generally subclasses don't need to override this; if they override
bs.GameActivity.get_settings() and bs.GameActivity.get_supported_maps()
they can just rely on the default implementation here which calls those
methods.

end()

end(self, results=None, delay=0, force=False)

Commences Activity shutdown and delivers results to the bs.Session.

'delay' is the time delay before the Activity actually ends
(in seconds). Further calls to end() will be ignored up until
this time, unless 'force' is True, in which case the new results
will replace the old.

end_game()

end_game(self)

Tells the game to wrap itself up and call bs.Activity.end()
immediately. This method should be overridden by subclasses.

A game should always be prepared to end and deliver results, even if
there is no 'winner' yet; this way things like the standard time-limit
(bs.GameActivity.setup_standard_time_limit()) will work with the game.

get_config_display_string()

<class method>

get_config_display_string(config)

Given a game config dict, return a short description for it.
This is used when viewing game-lists or showing what game
is up next in a series.

get_description()

<class method>

get_description(sessiontype)

Subclasses should override this to return a description for this
activity type (in English) within the context of the given
bs.Session type.

get_description_display_string()

<class method>

get_description_display_string(sessiontype)

Return a translated version of get_description().

Sub-classes should override get_description(); not this.

get_display_string()

<class method>

get_display_string(settings=None)

Return a descriptive name for this game/settings combo.

Subclasses should override getname(); not this.

get_instance_description()

get_instance_description(self)

Return a description for this game instance, in English.

This is shown in the center of the screen below the game name at the
start of a game. It should start with a capital letter and end with a
period, and can be a bit more verbose than the version returned by
get_instance_scoreboard_description().

Note that translation is applied by looking up the specific returned
value as a key, so the number of returned variations should be limited;
ideally just one or two. To include arbitrary values in the
description, you can return a sequence of values in the following
form instead of just a string:

# this will give us something like 'Score 3 goals.' in English
# and can properly translate to 'Anota 3 goles.' in Spanish.
# If we just returned the string 'Score 3 Goals' here, there would
# have to be a translation entry for each specific number. ew.
return ['Score ${ARG1} goals.', self.settings['Score to Win']]

This way the first string can be consistently translated, with any arg
values then substituted into the result. ${ARG1} will be replaced with
the first value, ${ARG2} with the second, etc.

get_instance_display_string()

get_instance_display_string(self)

Return a name for this particular game instance.

get_instance_scoreboard_description()

get_instance_scoreboard_description(self)

Return a short description for this game instance in English.

This description is used above the game scoreboard in the
corner of the screen, so it should be as concise as possible.
It should be lowercase and should not contain periods or other
punctuation.

Note that translation is applied by looking up the specific returned
value as a key, so the number of returned variations should be limited;
ideally just one or two. To include arbitrary values in the
description, you can return a sequence of values in the following form
instead of just a string:

# this will give us something like 'score 3 goals' in English
# and can properly translate to 'anota 3 goles' in Spanish.
# If we just returned the string 'score 3 goals' here, there would
# have to be a translation entry for each specific number. ew.
return ['score ${ARG1} goals', self.settings['Score to Win']]

This way the first string can be consistently translated, with any arg
values then substituted into the result. ${ARG1} will be replaced
with the first value, ${ARG2} with the second, etc.

get_instance_scoreboard_display_string()

get_instance_scoreboard_display_string(self)

Return a name for this particular game instance.

This name is used above the game scoreboard in the corner
of the screen, so it should be as concise as possible.

get_resolved_score_info()

<class method>

get_resolved_score_info()

Call this to return a game's score info with all missing values
filled in with defaults. This should not be overridden; override
get_score_info() instead.

get_score_info()

<class method>

get_score_info()

Return info about game scoring setup; should be overriden by games.

They should return a dict containing any of the following (missing
values will be default):

'score_name': a label shown to the user for scores; 'Score',
'Time Survived', etc. 'Score' is the default.

'lower_is_better': a boolean telling whether lower scores are
preferable instead of higher (the default).

'none_is_winner': specifies whether a score value of None is considered
better than other scores or worse. Default is False.

'score_type': can be 'seconds', 'milliseconds', or 'points'.

'score_version': to change high-score lists used by a game without
renaming the game, change this. Defaults to empty string.

get_settings()

<class method>

get_settings(sessiontype)

Called by the default bs.GameActivity.create_config_ui()
implementation; should return a dict of config options to be presented
to the user for the given bs.Session type.

The format for settings is a list of 2-member tuples consisting
of a name and a dict of options.

Available Setting Options:

'default': This determines the default value as well as the
type (int, float, or bool)

'min_value': Minimum value for int/float settings.

'max_value': Maximum value for int/float settings.

'choices': A list of name/value pairs the user can choose from by name.

'increment': Value increment for int/float settings.

# example get_settings() implementation for a capture-the-flag game:
@classmethod
def get_settings(cls,sessiontype):
    return [("Score to Win", {
                'default': 3,
                'min_value': 1
            }),
            ("Flag Touch Return Time", {
                'default': 0,
                'min_value': 0,
                'increment': 1
            }),
            ("Flag Idle Return Time", {
                'default': 30,
                'min_value': 5,
                'increment': 5
            }),
            ("Time Limit", {
                'default': 0,
                'choices': [
                    ('None', 0), ('1 Minute', 60), ('2 Minutes', 120),
                    ('5 Minutes', 300), ('10 Minutes', 600),
                    ('20 Minutes', 1200)
                ]
            }),
            ("Respawn Times", {
                'default': 1.0,
                'choices': [
                    ('Shorter', 0.25), ('Short', 0.5), ('Normal', 1.0),
                    ('Long', 2.0), ('Longer', 4.0)
                ]
            }),
            ("Epic Mode", {
                'default': False
            })]

get_supported_maps()

<class method>

get_supported_maps(sessiontype)

Called by the default bs.GameActivity.create_config_ui()
implementation; should return a list of map names valid
for this game-type for the given bs.Session type.

get_team_display_string()

<class method>

get_team_display_string(name)

Given a team name, returns a localized version of it.

getmap()

getmap(self)

Return the bs.Map in use for this activity.

getname()

<class method>

getname()

Return a str name for this game type.

handlemessage()

handlemessage(self, msg)

General message handling; can be passed any message object.

is_waiting_for_continue()

is_waiting_for_continue(self)

Returns whether or not this activity is currently waiting for the
player to continue (or timeout)

on_begin()

on_begin(self)

Called once the previous bs.Activity has finished transitioning out.

At this point the activity's initial players and teams are filled in
and it should begin its actual game logic.

on_continue()

on_continue(self)

This is called if a game supports and offers a continue and the player
accepts. In this case the player should be given an extra life or
whatever is relevant to keep the game going.

on_player_join()

on_player_join(self, player)

Called when a new bs.Player has joined the Activity.

(including the initial set of Players)

on_player_leave()

on_player_leave(self, player)

Called when a bs.Player is leaving the Activity.

on_transition_in()

on_transition_in(self, music=None)

Method override; optionally can
be passed a 'music' string which is the suggested type of
music to play during the game.
Note that in some cases music may be overridden by
the map or other factors, which is why you should pass
it in here instead of simply playing it yourself.

project_flag_stand()

project_flag_stand(self, pos)

Project a flag-stand onto the ground at the given position.

Useful for games such as capture-the-flag to show where a
movable flag originated from.

respawn_player()

respawn_player(self, player, respawn_time=None)

Given a bs.Player, sets up a standard respawn timer,
along with the standard counter display, etc.
At the end of the respawn period spawn_player() will
be called if the Player still exists.
An explicit 'respawn_time' can optionally be provided
(in milliseconds).

setup_standard_powerup_drops()

setup_standard_powerup_drops(self, enable_tnt=True)

Create standard powerup drops for the current map.

setup_standard_time_limit()

setup_standard_time_limit(self, duration)

Create a standard game time-limit given the provided
duration in seconds.
This will be displayed at the top of the screen.
If the time-limit expires, end_game() will be called.

show_info()

show_info(self)

Show the game description.

show_scoreboard_info()

show_scoreboard_info(self)

Create the game info display.

This is the thing in the top left corner showing the name
and short description of the game.

show_zoom_message()

show_zoom_message(self, message, color=(0.9, 0.4, 0.0), scale=0.8, duration=2000, trail=False)

Zooming text used to announce game names and winners.

spawn_player()

spawn_player(self, player)

Spawn *something* for the provided bs.Player.

The default implementation simply calls spawn_player_spaz().

spawn_player_if_exists()

spawn_player_if_exists(self, player)

A utility method which calls self.spawn_player() *only* if the
bs.Player provided still exists; handy for use in timers and whatnot.

There is no need to override this; just override spawn_player().

spawn_player_spaz()

spawn_player_spaz(self, player, position=(0, 0, 0), angle=None)

Create and wire up a bs.PlayerSpaz for the provided bs.Player.

supports_session_type()

<class method>

supports_session_type(sessiontype)

Return whether this game supports the provided Session class.


bs.HitMessage

<top level class>

Tells an object it has been hit in some way.

category: Message Classes

This is used by punches, explosions, etc to convey
their effect to a target.

Methods:

<constructor>

bs.HitMessage(srcnode=None, pos=None, velocity=None, magnitude=1.0, velocity_magnitude=0.0, radius=1.0, source_player=None, kick_back=1.0, flat_damage=None, hit_type='generic', force_direction=None, hit_subtype='default')

Instantiate a message with given values.


bs.ImpactDamageMessage

<top level class>

Tells an object that it has been jarred violently.

category: Message Classes

Attributes:

intensity

The intensity of the impact.

Methods:

<constructor>

bs.ImpactDamageMessage(intensity)

Instantiate a messages with a given intensity value.


bs.InputDevice

<top level class>

An input-device such as a gamepad, touchscreen, or keyboard.

category: Gameplay Classes

Methods:

exists(), get_account_name(), get_allows_configuring(), get_axis_name(), get_button_name(), get_client_id(), get_id(), get_instance_number(), get_unique_identifier(), getname(), getplayer(), is_connected_to_remote_player(), is_controller_app(), is_remote_client(), remove_remote_player_from_game()

exists()

exists() -> bool

Returns whether the device still exists.
Most functionality will fail on a nonexistant device.

Note that you can also use the boolean operator for this same
functionality, so a statement such as "if myinput" will do
the right thing both for InputDevice objects and values of None.

get_account_name()

get_account_name(full) -> str

Returns the account name associated with this device. (used to get account names for remote players)

get_allows_configuring()

get_allows_configuring() -> bool

Returns whether the input-device can be configured.

get_axis_name()

get_axis_name() -> str

Given an axis ID, returns the name of the axis on this device.

get_button_name()

get_button_name(button_id) -> str

Given a button ID, returns the name of the key/button on this device.

get_client_id()

get_client_id() -> int

Returns the numeric client-id this device is associated with.
This is only meaningful for remote client inputs; for all local devices
this will return -1

get_id()

get_id() -> int

Returns the unique numeric ID for this input device.

get_instance_number()

get_instance_number() -> int

Returns the number of this device among devices of the same type.

get_unique_identifier()

get_unique_identifier() -> str

Returns a string that can be used to uniquely identify a
particular input-device, even among devices of the same type.
(used for saving prefs, etc)

getname()

getname() -> str

Returns the name of the device.

getplayer()

getplayer() -> bs.Player

Returns the bs.Player associated with this input-device, or None if there is none.

is_connected_to_remote_player()

is_connected_to_remote_player() -> bool

Returns whether or not this input-device is attached to a player on a remote host device.

is_controller_app()

is_controller_app() -> bool

Returns whether or not this input-device represents the BSRemote controller app.

is_remote_client()

is_remote_client() -> bool

Returns whether or not this input-device represents a remotely connected client.

remove_remote_player_from_game()

remove_remote_player_from_game() -> None

If this device is attached to a remote player, removes it
from the game.


bs.Level

<top level class>

Represents a distinct named co-op game/settings combination.

category: Gameplay Classes

Methods:

<constructor>, get_complete(), get_config_dict(), get_display_string(), get_high_scores(), get_index(), get_preview_tex(), get_preview_tex_name(), get_rating(), get_score_version_string(), get_settings(), getcampaign(), getgametype(), getname(), set_complete(), set_high_scores(), submit_rating()

<constructor>

bs.Level(name, gametype, settings, preview_tex_name, displayname=None)

Initializes a Level object with the provided values.

get_complete()

get_complete(self)

Returns whether this Level has been completed.

get_config_dict()

get_config_dict(self)

Return a dict containing the persistant state for this level.

get_display_string()

get_display_string(self)

Return a bs.Lstr representing the name of this Level.

get_high_scores()

get_high_scores(self)

Return the current high scores for this Level.

get_index()

get_index(self)

Return the zero-based index this Level is at in its Campaign.

Raises an Exception if not a Campaign Level.

get_preview_tex()

get_preview_tex(self)

Load/return the preview Texture for this Level.

get_preview_tex_name()

get_preview_tex_name(self)

Return the preview texture name for this Level.

get_rating()

get_rating(self)

Return the current rating for this Level.

get_score_version_string()

get_score_version_string(self)

Return the score version string for this Level.

If a Level's gameplay changes significantly, its version string
can be changed to separate its new high score lists/etc. from the old.

get_settings()

get_settings(self)

Returns the settings for this Level.

getcampaign()

getcampaign(self)

Return the bs.Campaign this Level is associated with, or None.

getgametype()

getgametype(self)

Return the game-type for this Level.

getname()

getname(self)

Return the unique name for this Level.

set_complete()

set_complete(self, val)

Set whether or not this level is complete.

set_high_scores()

set_high_scores(self, high_scores)

Set high scores for this level.

submit_rating()

submit_rating(self, rating)

Submit a rating for this Level, replacing the old if higher.


bs.Lstr

<top level class>

Used to specify strings in a language-independent way.

category: General Utility Classes

These should be used whenever possible in place of hard-coded strings
so that in-game or UI elements show up correctly on all clients in their
currently-active language.

To see available resource keys, look at any of the bs_language_*.py files
in the game or the translations pages at bombsquadgame.com/translate.

    # EXAMPLE 1: specify a string from a resource path
    mynode.text = bs.Lstr(resource='audioSettingsWindow.titleText')
    # EXAMPLE 2: specify a translated string via a category and english value;
    # if a translated value is available, it will be used; otherwise the
    # english value will be. To see available translation categories, look
    # under the 'translations' resource section.
    mynode.text = bs.Lstr(translate=('gameDescriptions', 'Defeat all enemies'))
    # EXAMPLE 3: specify a raw value and some substitutions.  Substitutions can
    # be used with resource and translate modes as well.
    mynode.text = bs.Lstr(value='${A} / ${B}',
                          subs=[('${A}', str(score)), ('${B}', str(total))])
    # EXAMPLE 4: Lstrs can be nested.  This example would display the resource
    # at res_a but replace ${NAME} with the value of the resource at res_b
    mytextnode.text = bs.Lstr(resource='res_a',
                              subs=[('${NAME}', bs.Lstr(resource='res_b'))])

Methods:

<constructor>, evaluate(), is_flat_value()

<constructor>

bs.Lstr(*args, **keywds)

Instantiate a Lstr.

Pass a value for either 'resource', 'translate',
or 'value'. (see Lstr help for examples).
'subs' can be a sequence of 2-member sequences consisting of values
and replacements.
'fallback_resource' can be a resource key that will be used if the
main one is not present for
the current language in place of falling back to the english value
('resource' mode only).
'fallback_value' can be a literal string that will be used if neither
the resource nor the fallback resource is found ('resource' mode only).

evaluate()

evaluate(self)

Evaluate the Lstr and returns a flat string in the current language.

You should avoid doing this as much as possible and instead pass
and store Lstr values.

is_flat_value()

is_flat_value(self)

Return True if the Lstr is a 'flat' value.

This is defined as a simple string value incorporating no translations,
resources, or substitutions. In this case it may be reasonable to
replace it with a raw string value, perform string manipulation on it,
etc.


bs.Map

inherits from: bs.Actor

A game map.

category: Gameplay Classes

Consists of a collection of terrain nodes, metadata, and other
functionality comprising a game map.

Methods Inherited:

autoretain(), exists(), getactivity(), is_alive(), is_expired(), on_expire()

Methods Defined or Overridden:

<constructor>, get_def_bound_box(), get_def_point(), get_def_points(), get_ffa_start_position(), get_flag_position(), get_music_type(), get_play_types(), get_preview_texture_name(), get_start_position(), getname(), handlemessage(), is_point_near_edge(), on_preload(), preload()

<constructor>

bs.Map(vr_overlay_offset=None)

Instantiate a map.

get_def_bound_box()

get_def_bound_box(self, name)

Return a 6 member bounds tuple or None if it is not defined.

get_def_point()

get_def_point(self, name)

Return a single defined point or a default value in its absence.

get_def_points()

get_def_points(self, name)

Returns a list of named points.

Return as many sequential ones are defined (flag1, flag2, flag3), etc.

get_ffa_start_position()

get_ffa_start_position(self, players)

Return a random starting position in one of the FFA spawn areas.

If a list of bs.Players is provided; the returned points will be
as far from these players as possible.

get_flag_position()

get_flag_position(self, team_index=None)

Return a flag position on the map for the given team index.

Pass None to get the default flag point.
(used for things such as king-of-the-hill)

get_music_type()

<class method>

get_music_type()

Return a music-type string that should be played on this map.

If None is returned, default music will be used.

get_play_types()

<class method>

get_play_types()

Return valid play types for this map.

get_preview_texture_name()

<class method>

get_preview_texture_name()

Return the name of the preview texture for this map.

get_start_position()

get_start_position(self, team_index)

Return a random starting position for the given team index.

getname()

<class method>

getname()

Return the unique name of this map, in English.

handlemessage()

handlemessage(self, msg)

General message handling; can be passed any message object.

The default implementation will handle bs.DieMessages by
calling self.node.delete() if self contains a 'node' attribute.

is_point_near_edge()

is_point_near_edge(self, point, running=False)

Return whether the provided point is near an edge of the map.

Simple bot logic uses this call to determine if they
are approaching a cliff or wall. If this returns True they will
generally not walk/run any farther away from the origin.
If 'running' is True, the buffer should be a bit larger.

on_preload()

<class method>

on_preload()

Called when the map is being preloaded.

It should return any media/data it requires to operate

preload()

<class method>

preload()

Preload map media.

This runs the class's on_preload() method as needed to prep it to run.
Preloading should generally be done in a bs.Activity's __init__ method.
Note that this is a classmethod since it is not operate on map
instances but rather on the class itself before instances are made


bs.Material

<top level class>

Material(name=None)

An entity applied to game objects to modify collision behavior.

category: Gameplay Classes

A material can affect physical characteristics, generate sounds,
or trigger callback functions when collisions occur.

Materials are applied to 'parts', which are groups of one or more
rigid bodies created as part of a bs.Node. Nodes can have any number
of parts, each with its own set of materials. Generally materials are
specified as array attributes on the Node. The 'spaz' node, for
example, has various attributes such as 'materials',
'roller_materials', and 'punch_materials', which correspond to the
various parts it creates.

Use bs.Material() to instantiate a blank material, and then use its
add_actions() method to define what the material does.

Methods:

add_actions(), getname()

add_actions()

add_actions(actions, conditions=None) -> None

Add one or more actions to the material, optionally with conditions.

Conditions:

Conditions are provided as tuples which can be combined to form boolean
logic. A single condition might look like ('condition_name', cond_arg),
or a more complex nested one might look like (('some_condition',
cond_arg), 'or', ('another_condition', cond2_arg)).

'and', 'or', and 'xor' are available to chain together 2 conditions, as seen above.

Available Conditions:

('they_have_material', material) - does the part we're hitting have a
given bs.Material?

('they_dont_have_material', material) - does the part we're hitting
not have a given bs.Material?

('eval_colliding') - is 'collide' true at this point in material
evaluation? (see the modify_part_collision action)

('eval_not_colliding') - is 'collide' false at this point in material
evaluation? (see the modify_part_collision action)

('we_are_younger_than', age) - is our part younger than 'age'
(in milliseconds)?

('we_are_older_than', age) - is our part older than 'age'
(in milliseconds)?

('they_are_younger_than', age) - is the part we're hitting younger than
'age' (in milliseconds)?

('they_are_older_than', age) - is the part we're hitting older than
'age' (in milliseconds)?

('they_are_same_node_as_us') - does the part we're hitting belong to
the same bs.Node as us?

('they_are_different_node_than_us') - does the part we're hitting
belong to a different bs.Node than us?

Actions:

In a similar manner, actions are specified as tuples. Multiple actions
can be specified by providing a tuple of tuples.

Available Actions:

('call', when, callable) - calls the provided callable; 'when' can be
either 'at_connect' or 'at_disconnect'. 'at_connect' means to fire
when the two parts first come in contact; 'at_disconnect' means to
fire once they cease being in contact.

('message', who, when, message_obj) - sends a message object; 'who' can
be either 'our_node' or 'their_node', 'when' can be 'at_connect' or
'at_disconnect', and message_obj is the message object to send.
This has the same effect as calling the node's handlemessage()
method.

('modify_part_collision', attr, value) - changes some characteristic
of the physical collision that will occur between our part and their
part. This change will remain in effect as long as the two parts
remain overlapping. This means if you have a part with a material
that turns 'collide' off against parts younger than 100ms, and it
touches another part that is 50ms old, it will continue to not
collide with that part until they separate, even if the 100ms
threshold is passed. Options for attr/value are: 'physical' (boolean
value; whether a *physical* response will occur at all), 'friction'
(float value; how friction-y the physical response will be),
'collide' (boolean value; whether *any* collision will occur at all,
including non-physical stuff like callbacks), 'use_node_collide'
(boolean value; whether to honor modify_node_collision overrides for
this collision), 'stiffness' (float value, how springy the physical
response is), 'damping' (float value, how damped the physical
response is), 'bounce' (float value; how bouncy the physical response
is).

('modify_node_collision', attr, value) - similar to
modify_part_collision, but operates at a node-level.
collision attributes set here will remain in effect as long as
*anything* from our part's node and their part's node overlap.
A key use of this functionality is to prevent new nodes from
colliding with eachother if they appear overlapped;
if modify_part_collision is used, only the individual parts that
were overlapping would avoid contact, but other parts could still
contact leaving the two nodes 'tangled up'. Using
modify_node_collision ensures that the nodes must completely
separate before they can start colliding. Currently the only attr
available here is 'collide' (a boolean value).

('sound', sound, volume) - plays a bs.Sound when a collision occurs, at
a given volume, regardless of the collision speed/etc.

('impact_sound', sound, targetImpulse, volume) - plays a sound when a
collision occurs, based on the speed of impact. Provide a bs.Sound, a
target-impulse, and a volume.

('skid_sound', sound, targetImpulse, volume) - plays a sound during a
collision when parts are 'scraping' against eachother. Provide a
bs.Sound, a target-impulse, and a volume.

('roll_sound', sound, targetImpulse, volume) - plays a sound during a
collision when parts are 'rolling' against eachother. Provide a
bs.Sound, a target-impulse, and a volume.

# example 1: create a material that lets us ignore
# collisions against any nodes we touch in the first
# 100 ms of our existence; handy for preventing us from
# exploding outward if we spawn on top of another object:
m = bs.Material()
m.add_actions(conditions=(('we_are_younger_than', 100),
                         'or',('they_are_younger_than', 100)),
             actions=('modify_node_collision', 'collide', False))
# example 2: send a DieMessage to anything we touch, but cause
# no physical response.  This should cause any bs.Actor to drop dead:
m = bs.Material()
m.add_actions(actions=(('modify_part_collision', 'physical', False),
                      ('message', 'their_node', 'at_connect', bs.DieMessage())))
# example 3: play some sounds when we're contacting the ground:
m = bs.Material()
m.add_actions(conditions=('they_have_material',
                          bs.sharedobj('footing_material')),
              actions=(('impact_sound', bs.getsound('metalHit'), 2, 5),
                       ('skid_sound', bs.getsound('metalSkid'), 2, 5)))

getname()

getname() -> str

Returns the material name. Name is only for debugging.


bs.Model

<top level class>

A reference to a model.

category: Media Classes

Models are used for drawing.
Use bs.getmodel() to instantiate one.


bs.Node

<top level class>

Reference to a Node; the low level building block of the game.

category: Gameplay Classes

At its core, a game is nothing more than a scene of Nodes
with attributes getting interconnected or set over time.

A bs.Node instance should be thought of as a weak-reference
to a game node; *not* the node itself. This means a Node's
lifecycle is completely independent of how many Pythonreferences
to it exist. To explicitly add a new node to the game, use
bs.newnode(), and to explicitly delete one, use bs.Node.delete().
bs.Node.exists() can be used to determine if a Node still points to
a live node in the game.

You can use bs.Node(None) to instantiate an invalid
Node reference (sometimes used as attr values/etc).

Methods:

add_death_action(), connectattr(), delete(), exists(), getdelegate(), getname(), getnodetype(), handlemessage()

add_death_action()

add_death_action(action) -> None

Add a callable object to be called upon this node's death.
Note that these actions are run just after the node dies, not before.

connectattr()

connectattr(srcattr, dstnode, dstattr) -> None

Connect one of this node's attributes to an attribute on another node.
This will immediately set the target attribute's value to that of the
source attribute, and will continue to do so once per step as long as
the two nodes exist. The connection can be severed by setting the target
attribute to any value or connecting another node attribute to it.

# example: create a locator and attach a light to it
light = bs.newnode('light')
loc = bs.newnode('locator', attrs={'position': (0,10,0)})
loc.connectattr('position', light, 'position')

delete()

delete(ignore_missing=True) -> None

Delete the node. Ignores already-deleted nodes unless ignore_missing is False, in which case an Exception is thrown.

exists()

exists() -> bool

Returns whether the Node still exists.
Most functionality will fail on a nonexistant Node, so it's never a bad
idea to check this.

Note that you can also use the boolean operator for this same
functionality, so a statement such as "if mynode" will do
the right thing both for Node objects and values of None.

getdelegate()

getdelegate() -> object

Returns the node's current delegate, which is the Python object
designated to handle the Node's messages.

getname()

getname() -> str

Return the name assigned to a Node; used mainly for debugging

getnodetype()

getnodetype() -> str

Return the type of Node referenced by this object as a string.
(Note this is different from the Python type which is always bs.Node)

handlemessage()

handlemessage(*args) -> None

General message handling; can be passed any message object.

All standard message objects are forwarded along to the bs.Node's
delegate for handling (generally the bs.Actor that made the node).

bs.Nodes are unique, however, in that they can be passed a second
form of message; 'node-messages'. These consist of a string type-name
as a first argument along with the args specific to that type name
as additional arguments.
Node-messages communicate directly with the low-level node layer
and are delivered simultaneously on all game clients,
acting as an alternative to setting node attributes.


bs.OldWindow

<top level class>

Temp for transitioning windows over to UILocationWindows.

Methods:

get_root_widget()

get_root_widget(self)

Return the root widget.


bs.OutOfBoundsMessage

<top level class>

A message telling an object that it is out of bounds.

category: Message Classes


bs.PickedUpMessage

<top level class>

Tells an object that it has been picked up by something.

category: Message Classes

Attributes:

node

The bs.Node doing the picking up.

Methods:

<constructor>

bs.PickedUpMessage(node)

Instantiate with a given bs.Node.


bs.PickUpMessage

<top level class>

Tells an object that it has picked something up.

category: Message Classes

Attributes:

node

The bs.Node that is getting picked up.

Methods:

<constructor>

bs.PickUpMessage(node)

Instantiate with a given bs.Node.


bs.Player

<top level class>

A reference to a player in the game.

category: Gameplay Classes

These are created and managed internally and
provided to your Session/Activity instances.
You can use bs.Player(None) to instantiate an invalid
Player reference (sometimes used as attr values/etc).
Be aware that, like bs.Nodes, bs.Player objects are 'weak'
references under-the-hood; a player can leave the game at
any point. For this reason, you should make judicious use of the
bs.Player.exists() method (or boolean operator) to ensure that a
Player is still present if retaining references to one for any
length of time.

Attributes:

actor, character, color, gamedata, highlight, node, sessiondata

actor

The current bs.Actor associated with this Player.

character

The character this player has selected in their profile. (string)

color

The base color for this Player.
In team games this will match the bs.Team's color.

gamedata

A dict for use by the current bs.Activity for
storing data associated with this Player.
This gets cleared for each new bs.Activity.

highlight

A secondary color for this player.
This is used for minor highlights and accents
to allow a player to stand apart from his teammates
who may all share the same team (primary) color.

node

The current bs.Node associated with this Player.

sessiondata

A dict for use by the current bs.Session for
storing data associated with this player.
This persists for the duration of the session.

Methods:

assign_input_call(), exists(), get_account_id(), get_icon(), get_id(), get_input_device(), get_team(), getname(), is_alive(), remove_from_game(), reset_input(), set_actor(), set_name()

assign_input_call()

assign_input_call(type, call) -> None

Set the python callable to be run for one or more types of input.
Valid type values are: 'jumpPress', 'jumpRelease', 'punchPress',
'punchRelease','bombPress', 'bombRelease', 'pickUpPress',
'pickUpRelease', 'upDown','leftRight','upPress', 'upRelease',
'downPress', 'downRelease', 'leftPress','leftRelease','rightPress',
'rightRelease', 'run', 'flyPress', 'flyRelease', 'startPress',
'startRelease'

exists()

exists() -> bool

Returns whether the player still exists.
Most functionality will fail on a nonexistant player.

Note that you can also use the boolean operator for this same
functionality, so a statement such as "if player" will do
the right thing both for Player objects and values of None.

get_account_id()

get_account_id() -> str

Return the Account ID this player is signed in under, if
there is one and it can be determined with relative certainty.
Returns None otherwise. Note that this may require an active
internet connection (especially for network-connected players)
and may return None for a short while after a player initially
joins (while verification occurs).

get_icon()

get_icon() -> dict

Returns the character's icon (images, colors, etc contained in a dict)

get_id()

get_id() -> int

Returns the unique numeric ID for this player.

get_input_device()

get_input_device() -> bs.InputDevice

Returns the player's input device.
It may return None in cases such as remote players.

get_team()

get_team() -> bs.Team

Returns the player's team.

getname()

getname(full=False, icon=True) -> str

Returns the player's name. If icon is True, the long version of the name
may include an icon.

is_alive()

is_alive() -> bool

Returns True if the player has a bs.Actor assigned and its
is_alive() method return True. False is returned otherwise.

remove_from_game()

remove_from_game() -> None

Removes the player from the game.

reset_input()

reset_input() -> None

Clears out the player's assigned input actions.

set_actor()

set_actor(actor) -> None

Set the player's associated bs.Actor.

set_name()

set_name(name) -> None

Set the player's name to the provided string.
A number will automatically be appended if the name is not unique from other players.


bs.PlayerScoredMessage

<top level class>

Message informing a bs.Activity that a bs.Player scored.

category: Message Classes

Attributes:

score

The score value.

Methods:

<constructor>

bs.PlayerScoredMessage(score)

Instantiate with the given values.


bs.PowerupAcceptMessage

<top level class>

A message informing a bs.Powerup that it was accepted.

category: Message Classes

This is generally sent in response to a bs.PowerupMessage
to inform the box (or whoever granted it) that it can go away.


bs.PowerupMessage

<top level class>

A message telling an object to accept a powerup.

category: Message Classes

This message is normally recieved by touching a bs.PowerupBox.

Attributes:

poweruptype, source_node

poweruptype

The type of powerup to be granted (a string).
See bs.Powerup.poweruptype for available type values.

source_node

The node the powerup game from, or None otherwise.
If a powerup is accepted, a bs.PowerupAcceptMessage should be sent
back to the source_node to inform it of the fact. This will generally
cause the powerup box to make a sound and disappear or whatnot.

Methods:

<constructor>

bs.PowerupMessage(poweruptype, source_node=None)

Instantiate with given values.

See bs.Powerup.poweruptype for available type values.


bs.Session

<top level class>

Defines a high level series of activities with a common purpose.

category: Gameplay Classes

Examples of sessions are bs.FreeForAllSession, bs.TeamsSession, and
bs.CoopSession.

A Session is responsible for wrangling and transitioning between various
bs.Activity instances such as mini-games and score-screens, and for
maintaining state between them (players, teams, score tallies, etc).

Attributes:

campaign, lobby, max_players, min_players, players, teams

campaign

The bs.Campaign instance this Session represents, or None if
there is no associated Campaign.

lobby

The bs.Lobby instance where new bs.Players go to select a
Profile/Team/etc. before being added to games.
Be aware this value may be None if a Session does not allow
any such selection.

max_players

The maximum number of Players allowed in the Session.

min_players

The minimun number of Players who must be present for the Session
to proceed past the initial joining screen.

players

All bs.Players in the Session. Most things should use the player
list in bs.Activity; not this. Some players, such as those who have
not yet selected a character, will only appear on this list.

teams

All the bs.Teams in the Session. Most things should use the team
list in bs.Activity; not this.

Methods:

<constructor>, begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), getactivity(), handlemessage(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity()

<constructor>

bs.Session(team_names=None, team_colors=None, use_team_colors=True, min_players=1, max_players=8, allow_mid_activity_joins=True)

Instantiate a session.

begin_next_activity()

begin_next_activity(self)

Called once the previous activity has been totally torn down.

This means we're ready to begin the next one

end()

end(self)

Initiates an end to the session and a return to the main menu.

Note that this happens asynchronously, allowing the
session and its activities to shut down gracefully.

end_activity()

end_activity(self, activity, results, delay, force)

Commence shutdown of a bs.Activity (if not already occurring).

'delay' is the time delay before the Activity actually ends
(in seconds). Further calls to end() will be ignored up until
this time, unless 'force' is True, in which case the new results
will replace the old.

get_custom_menu_entries()

get_custom_menu_entries(self)

Subclasses can override this to provide custom menu entries.

The returned value should be a list of dicts, each containing
a 'label' and 'call' entry, with 'label' being the text for
the entry and 'call' being the callable to trigger if the entry
is pressed.

getactivity()

getactivity(self)

Return the current foreground activity for this session.

handlemessage()

handlemessage(self, msg)

General message handling; can be passed any message object.

on_activity_end()

on_activity_end(self, activity, results)

Called when the current bs.Activity has ended.

The bs.Session should look at the results and start
another bs.Activity.

on_player_leave()

on_player_leave(self, player)

Called when a previously-accepted bs.Player leaves the session.

on_player_request()

on_player_request(self, player)

Called when a new bs.Player wants to join the Session.

This should return True or False to accept/reject.

on_team_join()

on_team_join(self, team)

Called when a new bs.Team joins the session.

on_team_leave()

on_team_leave(self, team)

Called when a bs.Team is leaving the session.

setactivity()

setactivity(self, activity)

Assign a new current bs.Activity for the session.

Note that this will not change the current context to the new
Activity's. Code must be run in the new activity's methods
(on_transition_in, etc) to get it. (so you can't do
session.setactivity(foo) and then bs.newnode() to add a node to foo)


bs.ShouldShatterMessage

<top level class>

Tells an object that it should shatter.

category: Message Classes


bs.Sound

<top level class>

A reference to a sound.

category: Media Classes

Use bs.getsound() to instantiate one.


bs.StandMessage

<top level class>

A message telling an object to move to a position in space.

category: Message Classes

Used when teleporting players to home base, etc.

Attributes:

angle, position

angle

The angle to face (in degrees)

position

Where to move to.

Methods:

<constructor>

bs.StandMessage(position=(0, 0, 0), angle=0)

Instantiate with a given position and angle.


bs.Team

<top level class>

A team of one or more bs.Players.

category: Gameplay Classes

Note that a player *always* has a team;
in some cases, such as free-for-all bs.Sessions,
each team consists of just one bs.Player.

Attributes:

color, gamedata, name, players, sessiondata

color

The team's color.

gamedata

A dict for use by the current bs.Activity
for storing data associated with this team.
This gets cleared for each new bs.Activity.

name

The team's name.

players

The list of bs.Players on the team.

sessiondata

A dict for use by the current bs.Session for
storing data associated with this team.
Unlike gamedata, this perists for the duration
of the session.

Methods:

<constructor>, celebrate(), get_id()

<constructor>

bs.Team(team_id=0, name='', color=(1, 1, 1))

Instantiate a bs.Team.

In most cases, all teams are provided to you by the bs.Session,
bs.Session, so calling this shouldn't be necessary.

celebrate()

celebrate(self, duration=10.0)

Tells all players on the team to celebrate.

duration is given in seconds.

get_id()

get_id(self)

Returns the numeric team ID.


bs.TeamBaseSession

inherits from: bs.Session

Common base class for bs.TeamsSession and bs.FreeForAllSession.

category: Gameplay Classes

Free-for-all-mode is essentially just teams-mode with each bs.Player having
their own bs.Team, so there is much overlap in functionality.

Attributes Inherited:

campaign, lobby, max_players, min_players, players, teams

Methods Inherited:

begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), getactivity(), handlemessage(), launch_end_session_activity(), on_player_leave(), on_player_request(), on_team_leave(), setactivity()

Methods Defined or Overridden:

<constructor>, announce_game_results(), get_ffa_series_length(), get_game_number(), get_max_players(), get_next_game_description(), get_series_length(), on_activity_end(), on_team_join()

<constructor>

bs.TeamBaseSession()

Set up playlists and launches a bs.Activity to accept joiners.

announce_game_results()

announce_game_results(self, activity, results, delay, announce_winning_team=True)

Show basic game result at the end of a game.

(before transitioning to a score screen).
This will include a zoom-text of 'BLUE WINS'
or whatnot, along with a possible audio
announcement of the same.

get_ffa_series_length()

get_ffa_series_length(self)

Return free-for-all series length

get_game_number()

get_game_number(self)

Returns which game in the series is currently being played.

get_max_players()

get_max_players(self)

Return max number of bs.Players allowed to join the game at once.

get_next_game_description()

get_next_game_description(self)

Returns a description of the next game on deck

get_series_length()

get_series_length(self)

Return teams series length

on_activity_end()

on_activity_end(self, activity, results)

Called when the current bs.Activity has ended.

The bs.Session should look at the results and start
another bs.Activity.

on_team_join()

on_team_join(self, team)

Called when a new bs.Team joins the session.


bs.TeamGameActivity

inherits from: bs.GameActivity, bs.Activity

Base class for teams and free-for-all mode games.

category: Gameplay Classes

(Free-for-all is essentially just a special case where every
bs.Player has their own bs.Team)

Attributes Inherited:

players, settings, teams

Methods Inherited:

add_actor_weak_ref(), camera_flash(), continue_or_end_game(), create_config_ui(), create_player_node(), end_game(), get_config_display_string(), get_description(), get_description_display_string(), get_display_string(), get_instance_description(), get_instance_display_string(), get_instance_scoreboard_description(), get_instance_scoreboard_display_string(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), getmap(), getname(), getsession(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_transitioning_out(), is_waiting_for_continue(), on_continue(), on_expire(), on_player_join(), on_player_leave(), on_team_join(), on_team_leave(), on_transition_out(), project_flag_stand(), respawn_player(), retain_actor(), set_has_ended(), set_immediate_end(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_info(), show_scoreboard_info(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), start_transition_in()

Methods Defined or Overridden:

<constructor>, end(), on_begin(), on_transition_in(), spawn_player_spaz(), supports_session_type()

<constructor>

bs.TeamGameActivity(settings)

Instantiate the Activity.

end()

end(self, results=None, announce_winning_team=True, announce_delay=0.1, force=False)

Method override; announces the single winning team
unless 'announce_winning_team' is False. (useful for games where
there is not a single most-important winner).

on_begin()

on_begin(self)

Called once the previous bs.Activity has finished transitioning out.

At this point the activity's initial players and teams are filled in
and it should begin its actual game logic.

on_transition_in()

on_transition_in(self, music=None)

Method override; optionally can
be passed a 'music' string which is the suggested type of
music to play during the game.
Note that in some cases music may be overridden by
the map or other factors, which is why you should pass
it in here instead of simply playing it yourself.

spawn_player_spaz()

spawn_player_spaz(self, player, position=None, angle=None)

Method override; spawns and wires up a standard bs.PlayerSpaz for
a bs.Player.

If position or angle is not supplied, a default will be chosen based
on the bs.Player and their bs.Team.

supports_session_type()

<class method>

supports_session_type(sessiontype)

Class method override;
returns True for bs.TeamsSessions and bs.FreeForAllSessions;
False otherwise.


bs.TeamGameResults

<top level class>

Results for a completed bs.TeamGameActivity.

category: Gameplay Classes

Upon completion, a game should fill one of these out and pass it to its
bs.Activity.end() call.

Methods:

<constructor>, get_lower_is_better(), get_player_info(), get_score_name(), get_score_type(), get_team_score(), get_team_score_str(), get_teams(), get_winners(), get_winning_team(), has_score_for_team(), set_game(), set_team_score()

<constructor>

bs.TeamGameResults()

Instantiate a results instance.

get_lower_is_better()

get_lower_is_better(self)

Return whether lower scores are better

get_player_info()

get_player_info(self)

Return info about the players represented by the results

get_score_name()

get_score_name(self)

Return the name associated with scores ('points', etc)

get_score_type()

get_score_type(self)

Return the type of score

get_team_score()

get_team_score(self, team)

Return the score for a given bs.Team

get_team_score_str()

get_team_score_str(self, team)

Return the score for the given bs.Team as a string,
properly formatted for the score type.

get_teams()

get_teams(self)

Return all bs.Teams in the results.

get_winners()

get_winners(self)

Return an ordered list of dicts containing score and teams

get_winning_team()

get_winning_team(self)

Return the winning bs.Team if there is exactly one; None othewise.

has_score_for_team()

has_score_for_team(self, team)

Return whether there is a score for a given bs.Team

set_game()

set_game(self, game)

Set the game these results are applying to.

set_team_score()

set_team_score(self, team, score)

Set the score for a given bs.Team.
This can be a number or None.
(see the none_is_winner arg in the constructor)


bs.TeamsSession

inherits from: bs.TeamBaseSession, bs.Session

bs.Session type for teams mode games.

category: Gameplay Classes

Attributes Inherited:

campaign, lobby, max_players, min_players, players, teams

Methods Inherited:

announce_game_results(), begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), get_ffa_series_length(), get_game_number(), get_max_players(), get_next_game_description(), get_series_length(), getactivity(), handlemessage(), launch_end_session_activity(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity()

Methods Defined or Overridden:

<constructor>

bs.TeamsSession()

Set up playlists and launches a bs.Activity to accept joiners.


bs.Texture

<top level class>

A reference to a texture.

category: Media Classes

Use bs.gettexture() to instantiate one.


bs.ThawMessage

<top level class>

Tells an object to stop being frozen.

category: Message Classes


bs.Timer

<top level class>

Timer(time, call, repeat=False, timetype='sim', timeformat='s')

Timers are used to run code at later points in time.

category: General Utility Classes

This class encapsulates a timer in the current bs.Context.
The underlying timer will be destroyed when either this object is
no longer referenced or when its Context (Activity, etc.) dies. If you
do not want to worry about keeping a reference to your timer around,
you should use the bs.timer() function instead.

time: length of time (in seconds by default) that the timer will wait
before firing. Note that the actual delay experienced may vary
depending on the timetype. (see below)

call: A callable Python object. Note that the timer will retain a
strong reference to the callable for as long as it exists, so you
may want to look into concepts such as bs.WeakCall if that is not
desired.

repeat: if True, the timer will fire repeatedly, with each successive
firing having the same delay as the first.

timetype can be either 'sim', 'base', or 'real'. It defaults to
'sim'. Types are explained below:

'sim' time maps to local simulation time in bs.Activity or bs.Session
Contexts. This means that it may progress slower in slow-motion play
modes, stop when the game is paused, etc. This time type is not
available in UI contexts.

'base' time is also linked to gameplay in bs.Activity or bs.Session
Contexts, but it progresses at a constant rate regardless of
slow-motion states or pausing. It can, however, slow down or stop
in certain cases such as network outages or game slowdowns due to
cpu load. Like 'sim' time, this is unavailable in UI contexts.

'real' time always maps to actual clock time with a bit of filtering
added, regardless of Context. (the filtering prevents it from going
backwards or jumping forward by large amounts due to the app being
backgrounded, system time changing, etc.)
Real time timers are currently only available in the UI context.

the 'timeformat' arg defaults to 's' for seconds but can also be 'ms'
if you want to pass time as milliseconds.

# example: use a Timer object to print repeatedly for a few seconds:
def say_it():
    bs.screenmessage('BADGER!')
def stop_saying_it():
    self.t = None
    bs.screenmessage('MUSHROOM MUSHROOM!')
# create our timer; it will run as long as we hold self.t
self.t = bs.Timer(0.3, say_it, repeat=True)
# now fire off a one-shot timer to kill it
bs.timer(3.89, stop_saying_it)

bs.UILocation

<top level class>

Defines a specific 'place' in the UI the user can navigate to.

category: User Interface Classes

Methods:

<constructor>, push_location(), restore_state(), save_state()

<constructor>

bs.UILocation()

Initialize self. See help(type(self)) for accurate signature.

push_location()

push_location(self, location)

Push a new location to the stack and transition to it.

restore_state()

restore_state(self)

Restore this instance's state from a dict.

save_state()

save_state(self)

Serialize this instance's state to a dict.


bs.UILocationWindow

inherits from: bs.UILocation

A UILocation consisting of a single root window widget.

category: User Interface Classes

Methods Inherited:

<constructor>, push_location(), restore_state(), save_state()

Methods Defined or Overridden:

get_root_widget()

get_root_widget(self)

Return the root widget for this window.


bs.Vec3

<top level class>

A vector of 3 floats.

category: General Utility Classes

These can be created the following ways (checked in this order):
- with no args, all values are set to 0
- with a single numeric arg, all values are set to that value
- with a single three-member sequence arg, sequence values are copied
- otherwise assumes individual x/y/z args (positional or keywords)

Attributes:

x, y, z

x

The vector's X component.

y

The vector's Y component.

z

The vector's Z component.

Methods:

cross(), dot(), length(), normalized()

cross()

cross(other) -> bs.Vec3

Returns the cross product of this vector and another.

dot()

dot(other) -> float

Returns the dot product of this vector and another.

length()

length() -> float

Returns the length of the vector.

normalized()

normalized() -> bs.Vec3

Returns a normalized version of the vector.


bs.WeakCall

<top level class>

Wrap a callable and arguments into a single callable object.

category: General Utility Classes

When passed a bound method as the callable, the instance portion
of it is weak-referenced, meaning the underlying instance is
free to die if all other references to it go away. Should this
occur, calling the WeakCall is simply a no-op.

Think of this as a handy way to tell an object to do something
at some point in the future if it happens to still exist.

    # EXAMPLE A: this code will create a FooClass instance and call its
    # bar() method 5 seconds later; it will be kept alive even though
    # we overwrite its variable with None because the bound method
    # we pass as a timer callback (foo.bar) strong-references it
    foo = FooClass()
    bs.timer(5.0, foo.bar)
    foo = None
    # EXAMPLE B: this code will *not* keep our object alive; it will die
    # when we overwrite it with None and the timer will be a no-op when it
    # fires
    foo = FooClass()
    bs.timer(5.0, bs.WeakCall(foo.bar))
    foo = None

Note: additional args and keywords you provide to the WeakCall()
constructor are stored as regular strong-references; you'll need
to wrap them in weakrefs manually if desired.

Methods:

<constructor>

bs.WeakCall(*args, **keywds)

Instantiate a WeakCall; pass a callable as the first
arg, followed by any number of arguments or keywords.

# example: wrap a method call with some positional and keyword args:
myweakcall = bs.WeakCall(myobj.dostuff, argval1, namedarg=argval2)
# now we have a single callable to run that whole mess..
# this is the same as calling myobj.dostuff(argval1, namedarg=argval2)
# (provided my_obj still exists; this will do nothing otherwise)
myweakcall()

bs.Widget

<top level class>

Internal type for low level UI elements; buttons, windows, etc.

category: User Interface Classes

This class represents a weak reference to a widget object
in the internal c++ layer. Currently, functions such as
bs.buttonwidget() must be used to instantiate or edit these.

Methods:

activate(), add_delete_callback(), delete(), exists(), get_children(), get_screen_space_center(), get_selected_child(), get_widget_type()

activate()

activate() -> None

Activates a widget; the same as if it had been clicked.

add_delete_callback()

add_delete_callback(call) -> None

Add a call to be run immediately after this widget is destroyed.

delete()

delete(ignore_missing=True) -> None

Delete the Widget. Ignores already-deleted Widgets if ignore_missing
is True; otherwise an Exception is thrown.

exists()

exists() -> bool

Returns whether the Widget still exists.
Most functionality will fail on a nonexistant widget.

Note that you can also use the boolean operator for this same
functionality, so a statement such as "if mywidget" will do
the right thing both for Widget objects and values of None.

get_children()

get_children() -> list

Returns any child Widgets of this Widget.

get_screen_space_center()

get_screen_space_center() -> tuple

Returns the coords of the Widget center relative to the center of the
screen. This can be useful for placing pop-up windows and other special
cases.

get_selected_child()

get_selected_child() -> bs.Widget

Returns the selected child Widget or None if nothing is selected.

get_widget_type()

get_widget_type() -> str

Return the internal type of the Widget as a string. Note that this is
different from the Python bs.Widget type, which is the same for all
widgets.


bs.animate()

animate(node, attr, keys, loop=False, offset=0, timetype='sim', timeformat='s')

Animate values on a target bs.Node.

category: Gameplay Functions

Creates an 'animcurve' node with the provided values and time as an input,
connect it to the provided attribute, and set it to die with the target.
Key values are provided as time:value dictionary pairs. Time values are
relative to the current time. By default, times are specified in seconds,
but timeformat can also be set to 'ms' to recreate the old behavior
(prior to bs 1.5) of taking milliseconds. Returns the animcurve node.


bs.animate_array()

animate_array(node, attr, size, keys, loop=False, offset=0, timetype='sim', timeformat='s')

Animate an array of values on a target bs.Node.

category: Gameplay Functions

Like bs.animate(), but operates on array attributes.


bs.app()

app() -> bs.App

Returns the global shared bs.App instance.

category: General Utility Functions


bs.buttonwidget()

buttonwidget(edit=None, parent=None, size=None, position=None,
on_activate_call=None, label=None, color=None, down_widget=None,
up_widget=None, left_widget=None, right_widget=None, texture=None,
text_scale=None, textcolor=None, enable_sound=True,
model_transparent=None, model_opaque=None, repeat=None, scale=None,
transition_delay=None, on_select_call=None, button_type=None,
extra_touch_border_scale=None, selectable=None, show_buffer_top=None,
icon=None, iconscale=None, icon_tint=None, icon_color=None,
autoselect=None, mask_texture=None, tint_texture=None,
tint_color=None, tint2_color=None, text_flatness=None,
text_res_scale=None, enabled=None) -> bs.Widget

Create or edit a button widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.camerashake()

camerashake(intensity=1.0) -> None

Shake the camera.

category: Gameplay Functions

Note that some cameras and/or platforms (such as VR) may not display
camera-shake, so do not rely on this always being visible to the
player as a gameplay cue.


bs.checkboxwidget()

checkboxwidget(edit=None, parent=None, size=None, position=None,
text=None, value=None, on_value_change_call=None,
on_select_call=None, text_scale=None, textcolor=None, scale=None,
is_radio_button=None, maxwidth=None, autoselect=None,
color=None) -> bs.Widget

Create or edit a check-box widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.columnwidget()

columnwidget(edit=None, parent=None, size=None, position=None,
background=None, selected_child=None, visible_child=None,
single_depth=None, print_list_exit_instructions=None,
left_border=None, top_border=None, bottom_border=None)
-> bs.Widget

Create or edit a column widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.containerwidget()

containerwidget(edit=None, parent=None, size=None, position=None,
background=None, selected_child=None, transition=None,
cancel_button=None, start_button=None, root_selectable=None,
on_activate_call=None, claims_left_right=None, claims_tab=None,
selection_loops=None, selection_loop_to_parent=None, scale=None,
on_outside_click_call=None, single_depth=None, visible_child=None,
stack_offset=None, color=None, on_cancel_call=None,
print_list_exit_instructions=None, click_activate=None,
always_highlight=None, selectable=None,
scale_origin_stack_offset=None, toolbar_visibility=None,
on_select_call=None, claim_outside_clicks=None, claims_up_down=None)
-> bs.Widget

Create or edit a container widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.do_once()

do_once() -> bool

Register a call at a location and return whether one already happened.

category: General Utility Functions

This is used by 'print_once()' type calls to keep from overflowing
logs. The call functions by registering the filename and line where
The call is made from. Returns True if this location has not been
registered already, and False if it has.


bs.emitfx()

emitfx(position, velocity=None, count=10, scale=1.0, spread=1.0, chunk_type='rock',
emit_type='chunks', tendril_type='smoke') -> None

Emit particles, smoke, etc. into the fx sim layer.

category: Gameplay Functions

The fx sim layer is a secondary dynamics simulation that runs in
the background and just looks pretty; it does not affect gameplay.
Note that the actual amount emitted may vary depending on graphics
settings, exiting element counts, or other factors.


bs.get_collision_info()

get_collision_info(*args) -> object

Return collision related values

category: Gameplay Functions

Returns a single collision value or tuple of values such as location,
depth, nodes involved, etc. Only call this in the handler of a
collision-triggered callback or message


bs.getactivity()

getactivity(doraise=True) -> bs.Activity

Returns the current bs.Activity instance.

category: Gameplay Functions

Note that this is based on context; thus code run in a timer generated
in Activity 'foo' will properly return 'foo' here, even if another
Activity has since been created or is transitioning in.
If there is no current Activity an Exception is raised, or if doraise is
False then None is returned instead.


bs.getcollidemodel()

getcollidemodel(name) -> bs.CollideModel

Return a collide-model, loading it if necessary.

category: Media Functions

Collide-models are used in physics calculations for such things as
terrain.

Note that this function returns immediately even if the media has yet to be loaded. To avoid hitches, instantiate your media objects in
advance of when you will be using them, allowing time for them to load
in the background if necessary.


bs.getmaps()

getmaps(playtype)

Return a list of bs.Map types supporting a playtype str.

category: Media Functions

Maps supporting a given play type must provide a particular set of
features and lend themselves to a certain style of play.

Play Types:

'melee'
General fighting map.
Has one or more 'spawn' locations.

'team_flag'
For games such as Capture The Flag where each team spawns by a flag.
Has two or more 'spawn' locations, each with a corresponding 'flag'
location (based on index).

'single_flag'
For games such as King of the Hill or Keep Away where multiple teams
are fighting over a single flag.
Has two or more 'spawn' locations and 1 'flag_default' location.

'conquest'
For games such as Conquest where flags are spread throughout the map
- has 2+ 'flag' locations, 2+ 'spawn_by_flag' locations.

'king_of_the_hill' - has 2+ 'spawn' locations, 1+ 'flag_default' locations,
and 1+ 'powerup_spawn' locations

'hockey'
For hockey games.
Has two 'goal' locations, corresponding 'spawn' locations, and one
'flag_default' location (for where puck spawns)

'football'
For football games.
Has two 'goal' locations, corresponding 'spawn' locations, and one
'flag_default' location (for where flag/ball/etc. spawns)

'race'
For racing games where players much touch each region in order.
Has two or more 'race_point' locations.


bs.getmodel()

getmodel(name) -> bs.Model

Return a model, loading it if necessary.

category: Media Functions

Note that this function returns immediately even if the media has yet
to be loaded. To avoid hitches, instantiate your media objects in
advance of when you will be using them, allowing time for them to load
in the background if necessary.


bs.getnodes()

getnodes() -> list

Return all nodes in the current bs.Context.
category: Gameplay Functions


bs.getsession()

getsession(doraise=True) -> bs.Session

category: Gameplay Functions

Returns the current bs.Session instance.
Note that this is based on context; thus code being run in the UI
context will return the UI context here even if a game Session also
exists, etc. If there is no current Session, an Exception is raised, or
if doraise is False then None is returned instead.


bs.getsound()

getsound(name) -> bs.Sound

Return a sound, loading it if necessary.

category: Media Functions

Note that this function returns immediately even if the media has yet
to be loaded. To avoid hitches, instantiate your media objects in
advance of when you will be using them, allowing time for them to load
in the background if necessary.


bs.gettexture()

gettexture(name) -> bs.Texture

Return a texture, loading it if necessary.

category: Media Functions

Note that this function returns immediately even if the media has yet
to be loaded. To avoid hitches, instantiate your media objects in
advance of when you will be using them, allowing time for them to load
in the background if necessary.


bs.hscrollwidget()

hscrollwidget(edit=None, parent=None, size=None, position=None,
background=None, selected_child=None, capture_arrows=None,
on_select_call=None, center_small_content=None, color=None,
highlight=None, border_opacity=None, simple_culling_h=None)
-> bs.Widget

Create or edit a horizontal scroll widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.imagewidget()

imagewidget(edit=None, parent=None, size=None, position=None,
color=None, texture=None, opacity=None, model_transparent=None,
model_opaque=None, has_alpha_channel=True, tint_texture=None,
tint_color=None, transition_delay=None, draw_controller=None,
tint2_color=None, tilt_scale=None, mask_texture=None,
radial_amount=None) -> bs.Widget

Create or edit an image widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.is_browser_likely_available()

is_browser_likely_available()

Return whether a browser likely exists on the current device.

category: General Utility Functions

If this returns False you may want to avoid calling bs.show_url()
with any lengthy addresses. (bs.show_url() will display an address
as a string in a window if unable to bring up a browser, but that
is only useful for simple URLs.)


bs.is_point_in_box()

is_point_in_box(pnt, box)

Return whether a given point is within a given box.

category: General Utility Functions

For use with standard def boxes (position|rotate|scale).


bs.log()

log(message, to_console=True, newline=True, to_server=True) -> None

category: General Utility Functions

Log a message. This goes to the default logging mechanism depending
on the platform (stdout on mac, android log on android, etc).

Log messages also go to the in-game console unless 'to_console'
is False. They are also sent to the master-server for use in analyzing
issues unless to_server is False.

Python's standard print() is wired to call this (with default values)
so in most cases you can just use that.


bs.new_activity()

new_activity(activity_type, settings=None) -> bs.Activity

Instantiates a bs.Activity given a type object.

category: General Utility Functions

Activities require special setup and thus cannot be directly
instantiated; You must go through this function.


bs.newnode()

newnode(type, owner=None, attrs=None, name=None, delegate=None) -> bs.Node

Add a node of the given type to the game.

category: Gameplay Functions

If a dict is provided for 'attributes', the node's initial attributes
will be set based on them.

'name', if provided, will be stored with the node purely for debugging
purposes. If no name is provided, an automatic one will be generated
such as 'terrain@foo.py:30'.

If 'delegate' is provided, Python messages sent to the node will go to
that object's handlemessage() method. Note that the delegate is stored
as a weak-ref, so the node itself will not keep the object alive.

if 'owner' is provided, the node will be automatically killed when that
object dies. 'owner' can be another node or a bs.Actor


bs.normalized_color()

normalized_color(color)

Scale a color so its largest value is 1; useful for coloring lights.

category: General Utility Functions


bs.open_url()

open_url(address) -> None

Open a provided URL.

category: General Utility Functions

Open the provided url in a web-browser, or display the URL
string in a window if that isn't possible.


bs.playsound()

playsound(sound, volume=1.0, position=None, host_only=False) -> None

Play a bs.Sound a single time.

category: Gameplay Functions

If position is not provided, the sound will be at a constant volume
everywhere. Position should be a float tuple of size 3.


bs.print_error()

print_error(*args, **keywds)

Print info about an error along with pertinant context state.

category: General Utility Functions

Prints all positional arguments provided along with various info about the
current context.
Pass the keyword 'once' as True if you want the call to only happen
one time from an exact calling location.


bs.print_exception()

print_exception(*args, **keywds)

Print info about an exception along with pertinant context state.

category: General Utility Functions

Prints all arguments provided along with various info about the
current context and the outstanding exception.
Pass the keyword 'once' as True if you want the call to only happen
one time from an exact calling location.


bs.printnodes()

printnodes() -> None

Print various info about existing nodes; useful for debugging.

category: Gameplay Functions


bs.printobjects()

printobjects() -> None

Print debugging info about game objects.

category: General Utility Functions

This call only functions in debug builds of the game.
It prints various info about the current object count, etc.


bs.pushcall()

pushcall(call, from_other_thread=False) -> None

Pushes a call onto the event loop to be run during the next cycle.

category: General Utility Functions

This can be handy for calls that are disllowed from within other
callbacks, etc.

This call expects to be used in the game thread, and will automatically
save and restore the bs.Context to behave seamlessly.

If you want to push a call from outside of the game thread,
however, you can pass 'from_other_thread' as True. In this case
the call will always run in the UI context on the game thread.


bs.quit()

quit(soft=False, back=False) -> None

Quit the game.

category: General Utility Functions

On systems like android, 'soft' will end the activity but keep the
app running.


bs.rowwidget()

rowwidget(edit=None, parent=None, size=None, position=None,
background=None, selected_child=None, visible_child=None)
-> bs.Widget

Create or edit a row widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.safecolor()

safecolor(color, target_intensity=0.6) -> tuple

Given a color tuple, return a color safe to display as text.

category: General Utility Functions

Accepts tuples of length 3 or 4. This will slightly brighten very
dark colors, etc.


bs.screenmessage()

screenmessage(message, color=(1,1,1), top=False, image=None, log=False, clients=None, transient=False) -> None

Print a message to the local client's screen, in a given color.

category: General Utility Functions

If 'top' is True, the message will go to the top message area.
For 'top' messages, 'image' can be a texture to display alongside the
message.
If 'log' is True, the message will also be printed to the output log
'clients' can be a list of client-ids the message should be sent to,
or None to specify that everyone should receive it.
If 'transient' is True, the message will not be included in the
game-stream and thus will not show up when viewing replays.
Currently the 'clients' option only works for transient messages.


bs.scrollwidget()

scrollwidget(edit=None, parent=None, size=None, position=None,
background=None, selected_child=None, capture_arrows=False,
on_select_call=None, center_small_content=None, color=None,
highlight=None, border_opacity=None, simple_culling_v=None)
-> bs.Widget

Create or edit a scroll widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.set_analytics_screen()

set_analytics_screen(screen) -> None

Used for analytics to see where in the app players spend their time.

category: General Utility Functions

Generally called when opening a new window or entering some UI.
'screen' should be a string description of an app location
('Main Menu', etc.)


bs.setmusic()

setmusic(musictype, continuous=False)

Set or stop the current music based on a string musictype.

category: Gameplay Functions

Current valid values for 'musictype': 'Menu', 'Victory', 'CharSelect',
'RunAway', 'Onslaught', 'Keep Away', 'Race', 'Epic Race', 'Scores',
'GrandRomp', 'ToTheDeath', 'Chosen One', 'ForwardMarch', 'FlagCatcher',
'Survival', 'Epic', 'Sports', 'Hockey', 'Football', 'Flying', 'Scary',
'Marching'.

This function will handle loading and playing sound media as necessary,
and also supports custom user soundtracks on specific platforms so the
user can override particular game music with their own.

Pass None to stop music.

if 'continuous' is True the musictype passed is the same as what is already
playing, the playing track will not be restarted.


bs.sharedobj()

sharedobj(name)

Return a predefined object for the current Activity, creating if needed.

category: Gameplay Functions

Available values for 'name':

'globals': returns the 'globals' bs.Node, containing various global
controls & values.

'object_material': a bs.Material that should be applied to any small,
normal, physical objects such as bombs, boxes, players, etc. Other
materials often check for the presence of this material as a
prerequisite for performing certain actions (such as disabling collisions
between initially-overlapping objects)

'player_material': a bs.Material to be applied to player parts. Generally,
materials related to the process of scoring when reaching a goal, etc
will look for the presence of this material on things that hit them.

'pickup_material': a bs.Material; collision shapes used for picking things
up will have this material applied. To prevent an object from being
picked up, you can add a material that disables collisions against things
containing this material.

'footing_material': anything that can be 'walked on' should have this
bs.Material applied; generally just terrain and whatnot. A character will
snap upright whenever touching something with this material so it should
not be applied to props, etc.

'attack_material': a bs.Material applied to explosion shapes, punch
shapes, etc. An object not wanting to recieve impulse/etc messages can
disable collisions against this material.

'death_material': a bs.Material that sends a bs.DieMessage() to anything
that touches it; handy for terrain below a cliff, etc.

'region_material': a bs.Material used for non-physical collision shapes
(regions); collisions can generally be allowed with this material even
when initially overlapping since it is not physical.

'railing_material': a bs.Material with a very low friction/stiffness/etc
that can be applied to invisible 'railings' useful for gently keeping
characters from falling off of cliffs.


bs.show_damage_count()

show_damage_count(damage, position, direction)

Pop up a damage count at a position in space.


bs.specialchar()

specialchar(name) -> str

Given a name, return a game-specific unicode character.

category: General Utility Functions

Note that these utilize the private-use block of unicode characters
(U+E000-U+F8FF) and are specific to the game; exporting or rendering
them elsewhere will be meaningless.

Available values:

'down_arrow', 'up_arrow', 'left_arrow', 'right_arrow':
directional arrows.

'top_button', 'left_button', 'right_button', 'bottom_button':
generic gamepad button icons.

'rewind_button', 'play_pause_button', 'fast_forward_button',
'dpad_center_button': tv remote buttons.


bs.textwidget()

textwidget(edit=None, parent=None, size=None, position=None, text=None,
v_align=None, h_align=None, editable=None, padding=None,
on_return_press_call=None, on_activate_call=None, selectable=None,
query=None, max_chars=None, color=None, click_activate=None,
on_select_call=None, always_highlight=None, draw_controller=None,
scale=None, corner_scale=None, description=None,
transition_delay=None, maxwidth=None, max_height=None,
flatness=None, shadow=None, autoselect=None, rotate=None,
enabled=None, force_internal_editing=None, always_show_carat=None,
big=None, extra_touch_border_scale=None, res_scale=None) -> bs.Widget

Create or edit a text widget.

category: User Interface Functions

Pass a valid existing bs.Widget as 'edit' to modify it; otherwise
a new one is created and returned. Arguments that are not set to None
are applied to the Widget.


bs.time()

time(timetype='sim', timeformat='s') -> float

Return the current time.

category: General Utility Functions

The time returned depends on the current bs.Context and timetype.

timetype can be either 'sim', 'base', or 'real'. It defaults to
'sim'. Types are explained below:

'sim' time maps to local simulation time in bs.Activity or bs.Session
Contexts. This means that it may progress slower in slow-motion play
modes, stop when the game is paused, etc. This time type is not
available in UI contexts.

'base' time is also linked to gameplay in bs.Activity or bs.Session
Contexts, but it progresses at a constant rate regardless of
slow-motion states or pausing. It can, however, slow down or stop
in certain cases such as network outages or game slowdowns due to
cpu load. Like 'sim' time, this is unavailable in UI contexts.

'real' time always maps to actual clock time with a bit of filtering
added, regardless of Context. (the filtering prevents it from going
backwards or jumping forward by large amounts due to the app being
backgrounded, system time changing, etc.)

the 'timeformat' arg defaults to 's' which returns float seconds, but
it can also be 'ms' which returns int milliseconds

Note: If you need pure unfiltered clock time, just use the standard
Python functions such as time.time().


bs.timer()

timer(time, call, repeat=False, timetype='sim', timeformat='s')
-> None

Schedule a call to run at a later point in time.

category: General Utility Functions

This function adds a timer to the current bs.Context.
This timer cannot be canceled or modified once created. If you
require the ability to do so, use the bs.Timer class instead.

time: length of time (in seconds by default) that the timer will wait
before firing. Note that the actual delay experienced may vary
depending on the timetype. (see below)

call: A callable Python object. Note that the timer will retain a
strong reference to the callable for as long as it exists, so you
may want to look into concepts such as bs.WeakCall if that is not
desired.

repeat: if True, the timer will fire repeatedly, with each successive
firing having the same delay as the first.

timetype can be either 'sim', 'base', or 'real'. It defaults to
'sim'. Types are explained below:

'sim' time maps to local simulation time in bs.Activity or bs.Session
Contexts. This means that it may progress slower in slow-motion play
modes, stop when the game is paused, etc. This time type is not
available in UI contexts.

'base' time is also linked to gameplay in bs.Activity or bs.Session
Contexts, but it progresses at a constant rate regardless of
slow-motion states or pausing. It can, however, slow down or stop
in certain cases such as network outages or game slowdowns due to
cpu load. Like 'sim' time, this is unavailable in UI contexts.

'real' time always maps to actual clock time with a bit of filtering
added, regardless of Context. (the filtering prevents it from going
backwards or jumping forward by large amounts due to the app being
backgrounded, system time changing, etc.)
Real time timers are currently only available in the UI context.

the 'timeformat' arg defaults to 's' for seconds but can also be 'ms'
if you want to pass time as milliseconds.

# timer example: print some stuff through time:
bs.screenmessage('hello from now!')
bs.timer(1.0, bs.Call(bs.screenmessage, 'hello from the future!'))
bs.timer(2.0, bs.Call(bs.screenmessage, 'hello from the future 2!'))

bs.timestring()

timestring(timeval, centi=True, timeformat='s')

Generate a string for displaying a time value.

category: General Utility Functions

Given a time value, returns a bs.Lstr with:
(hours if > 0 ) : minutes : seconds : (centiseconds if centi=True).

Time 't' is specified in seconds by default, or 'timeformat' can
be set to 'ms' to accept millisecond values.

WARNING: the underlying Lstr value is somewhat large so don't use this
to rapidly update Node text values for an onscreen timer or you may
waste significant network bandwidth. For that purpose you should
use a 'timedisplay' Node and attribute connections.


bs.uicleanupcheck()

uicleanupcheck(obj, widget)

Add a check to ensure a widget-owning object gets cleaned up properly.

category: User Interface Functions

This adds a check which will print an error message if the provided
object still exists ~5 seconds after the provided bs.Widget dies.

This is a good sanity check for any sort of object that wraps or
controls a bs.Widget. For instance, a 'Window' class instance has
no reason to still exist once its root container bs.Widget has fully
transitioned out and been destroyed. Circular references or careless
strong referencing can lead to such objects never getting destroyed,
however, and this helps detect such cases to avoid memory leaks.


bs.widget()

widget(edit=None, up_widget=None, down_widget=None,
left_widget=None, right_widget=None, show_buffer_top=None,
show_buffer_bottom=None, show_buffer_left=None,
show_buffer_right=None, autoselect=None) -> None

Edit common attributes of any widget.

category: User Interface Functions

Unlike other UI calls, this can only be used to edit, not to create.

The stuff of Eric Froemling