BombSquadCore Python API

last updated on 2019-08-22 for BombSquad version 1.5.0 build 20001

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

Asset Classes

Asset Functions

Message Classes

User Interface Classes

User Interface Functions

Dependency Classes

Enums

Exception Classes

Misc

Misc


bs.Achievement

<top level class>

Represents attributes and state for an individual achievement.

Attributes:

complete, description, description_complete, description_full, description_full_complete, display_name, hard_mode_only, level_name, name, power_ranking_value

complete

bool

Whether this Achievement is currently complete.

description

bs.Lstr

Get a bs.Lstr for the Achievement's brief description.

description_complete

bs.Lstr

Get a bs.Lstr for the Achievement's description when completed.

description_full

bs.Lstr

Get a bs.Lstr for the Achievement's full description.

description_full_complete

bs.Lstr

Get a bs.Lstr for the Achievement's full desc. when completed.

display_name

bs.Lstr

Return a bs.Lstr for this Achievement's name.

hard_mode_only

bool

Whether this Achievement is only unlockable in hard-mode.

level_name

str

The name of the level this achievement applies to.

name

str

The name of this achievement.

power_ranking_value

int

Get the power-ranking award value for this achievement.

Methods:

<constructor>, announce_completion(), create_display(), get_award_ticket_value(), get_icon_color(), get_icon_texture(), set_complete(), show_completion_banner()

<constructor>

bs.Achievement(name: str, icon_name: str, icon_color: Sequence[float], level_name: str, award: int, hard_mode_only: bool = False)

announce_completion()

announce_completion(self, sound: bool = True) -> None

Kick off an announcement for this achievement's completion.

create_display()

create_display(self, x: 'float', y: 'float', delay: 'float', outdelay: 'float' = None, color: 'Sequence[float]' = None, style: 'str' = 'post_game') -> 'List[bs.Actor]'

Create a display for the Achievement.

Shows the Achievement icon, name, and description.

get_award_ticket_value()

get_award_ticket_value(self, include_pro_bonus: bool = False) -> int

Get the ticket award value for this achievement.

get_icon_color()

get_icon_color(self, complete: bool) -> Sequence[float]

Return the color tint for this Achievement's icon.

get_icon_texture()

get_icon_texture(self, complete: bool) -> bs.Texture

Return the icon texture to display for this achievement

set_complete()

set_complete(self, complete: bool = True) -> None

Set an achievement's completed state.

note this only sets local state; use a transaction to actually award achievements.

show_completion_banner()

show_completion_banner(self, sound: bool = True) -> None

Create the banner/sound for an acquired achievement announcement.


bs.Activity

inherits from: bs._dep.InstancedDepComponent, bs.DepComponent

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, session, settings, stats, teams

players

List[_bs.Player]

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.

session

bs.Session

The bs.Session this bs.Activity belongs go.

Raises a bs.SessionNotFoundError if the Session no longer exists.

settings

Dict[str, Any]

The settings dict passed in when the activity was made.

stats

bs.Stats

The stats instance accessible while the activity is running.

If access is attempted before or after, raises a bs.NotFoundError.

teams

List[bs.Team]

The list of bs.Teams in the Activity. This gets populated just before 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 Inherited:

dep_get_payload(), get_dynamic_deps(), is_present()

Methods Defined or Overridden:

<constructor>, add_actor_weak_ref(), create_player_node(), end(), 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: Dict[str, Any])

Creates an activity in the current bs.Session.

The activity will not be actually run until bs.Session.set_activity() 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: bs.Actor) -> None

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: bs.Player) -> bs.Node

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

end()

end(self, results: Any = None, delay: float = 0.0, force: bool = False) -> None

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.

handlemessage()

handlemessage(self, msg: Any) -> Any

General message handling; can be passed any message object.

has_begun()

has_begun(self) -> bool

Return whether on_begin() has been called.

has_ended()

has_ended(self) -> bool

Return whether the activity has commenced ending.

has_transitioned_in()

has_transitioned_in(self) -> bool

Return whether on_transition_in() has been called.

is_expired()

is_expired(self) -> bool

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) -> bool

Return whether on_transition_out() has been called.

on_begin()

on_begin(self) -> None

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) -> None

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: bs.Player) -> None

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

(including the initial set of Players)

on_player_leave()

on_player_leave(self, player: bs.Player) -> None

Called when a bs.Player is leaving the Activity.

on_team_join()

on_team_join(self, team: bs.Team) -> None

Called when a new bs.Team joins the Activity.

(including the initial set of Teams)

on_team_leave()

on_team_leave(self, team: bs.Team) -> None

Called when a bs.Team leaves the Activity.

on_transition_in()

on_transition_in(self) -> None

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) -> None

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: bs.Actor) -> None

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

The reference 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.ActivityNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Activity does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


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())

Attributes:

activity

bs.Activity

The Activity this Actor was created in.

Raises a bs.ActivityNotFoundError if the Activity no longer exists.

Methods:

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

<constructor>

bs.Actor(node: bs.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: T) -> T

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) -> bool

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: bool = True) -> Optional[bs.Activity]

Return the bs.Activity this Actor is associated with.

If the Activity no longer exists, raises a bs.ActivityNotFoundError or returns None depending on whether 'doraise' is set.

handlemessage()

handlemessage(self, msg: Any) -> Any

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) -> bool

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) -> bool

Returns whether the Actor is expired.

(see bs.Actor.on_expire())

on_expire()

on_expire(self) -> None

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.ActorNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Actor does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


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

int

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

bs.AppConfig

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

config_file_path

str

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

debug_build

bool

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

str

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

str

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

str

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

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

platform

str

Name of the current platform.

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

subplatform

str

String for subplatform.

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

system_scripts_directory

str

Path where the game is looking for its bundled scripts.

test_build

bool

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

Tuple[float, float, float, float]

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

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

user_agent_string

str

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

user_scripts_directory

str

Path where the game is looking for custom user scripts.

version

str

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

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) -> None

Called when the app goes to a suspended state.

handle_app_resume()

handle_app_resume(self) -> None

Run when the app resumes from a suspended state.

handle_deep_link()

handle_deep_link(self, url: str) -> None

Handle a deep link URL.

launch_coop_game()

launch_coop_game(self, game: str, force: bool = False, args: Dict = None) -> bool

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

pause()

pause(self) -> None

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) -> None

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) -> None

Attempt to cleanly get back to the main menu.


bs.AppConfig

inherits from: dict

A special dict that holds the game's persistent 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) -> None

Apply config values to the running app.

apply_and_commit()

apply_and_commit(self) -> None

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

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

builtin_keys()

builtin_keys(self) -> List[str]

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

This set of keys can be used 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) -> None

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: str) -> Any

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: str) -> Any

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.AppDelegate

<top level class>

Defines handlers for high level app functionality.

Methods:

create_default_game_config_ui()

create_default_game_config_ui(self, gameclass: Type[bs.GameActivity], sessionclass: Type[bs.Session], config: Optional[Dict[str, Any]], completion_call: Callable[[Optional[Dict[str, Any]]], None]) -> None

Launch a UI to configure the given game config.

It should manipulate the contents of config and call completion_call when done.


bs.AssetPackage

inherits from: bs._dep.StaticDepComponent, bs.DepComponent

DepComponent representing a bundled package of game assets.

Methods Inherited:

dep_get_payload(), get_dynamic_deps()

Methods Defined or Overridden:

<constructor>, getcollidemodel(), getdata(), getmodel(), getsound(), gettexture(), is_present()

<constructor>

bs.AssetPackage()

Instantiate a DepComponent.

getcollidemodel()

getcollidemodel(self, name: str) -> bs.CollideModel

Load a named bs.CollideModel from the AssetPackage.

Behavior is similar to bs.getcollideModel()

getdata()

getdata(self, name: str) -> bs.Data

Load a named bs.Data from the AssetPackage.

Behavior is similar to bs.getdata()

getmodel()

getmodel(self, name: str) -> bs.Model

Load a named bs.Model from the AssetPackage.

Behavior is similar to bs.getmodel()

getsound()

getsound(self, name: str) -> bs.Sound

Load a named bs.Sound from the AssetPackage.

Behavior is similar to bs.getsound()

gettexture()

gettexture(self, name: str) -> bs.Texture

Load a named bs.Texture from the AssetPackage.

Behavior is similar to bs.gettexture()

is_present()

<class method>

is_present(config: Any = None) -> bool

Return whether this component/config is present on this device.


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: Any, **keywds: Any)

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.Campaign

<top level class>

Represents a unique set or series of bs.Levels.

Attributes:

name, sequential

name

str

The name of the Campaign.

sequential

bool

Whether this Campaign's levels must be played in sequence.

Methods:

<constructor>, add_level(), get_config_dict(), get_level(), get_levels(), get_selected_level(), reset(), set_selected_level()

<constructor>

bs.Campaign(name: str, sequential: bool = True)

add_level()

add_level(self, level: bs.Level) -> None

Adds a bs.Level to the Campaign.

get_config_dict()

get_config_dict(self) -> Dict[str, Any]

Return the live config dict for this campaign.

get_level()

get_level(self, name: str) -> bs.Level

Return a contained bs.Level by name.

get_levels()

get_levels(self) -> List[bs.Level]

Return the set of bs.Levels in the Campaign.

get_selected_level()

get_selected_level(self) -> str

Return the name of the Level currently selected in the UI.

reset()

reset(self) -> None

Reset state for the Campaign.

set_selected_level()

set_selected_level(self, levelname: str) -> None

Set the Level currently selected in the UI (by name).


bs.Chooser

<top level class>

A character/team selector for a single player.

Attributes:

lobby, player, ready

lobby

bs.Lobby

The chooser's bs.Lobby.

player

bs.Player

The bs.Player associated with this chooser.

ready

bool

Whether this chooser is checked in as ready.

Methods:

<constructor>, get_character_name(), get_color(), get_highlight(), get_lobby(), get_team(), getplayer(), handlemessage(), reload_profiles(), update_from_player_profiles(), update_position()

<constructor>

bs.Chooser(vpos: float, player: _bs.Player, lobby: "Lobby")

get_character_name()

get_character_name(self) -> str

Return the selected character name.

get_color()

get_color(self) -> Sequence[float]

Return the currently selected color.

get_highlight()

get_highlight(self) -> Sequence[float]

Return the currently selected highlight.

get_lobby()

get_lobby(self) -> Optional[bs.Lobby]

Return this chooser's lobby if it still exists; otherwise None.

get_team()

get_team(self) -> bs.Team

Return this chooser's selected bs.Team.

getplayer()

getplayer(self) -> bs.Player

Return the player associated with this chooser.

handlemessage()

handlemessage(self, msg: Any) -> Any

Standard generic message handler.

reload_profiles()

reload_profiles(self) -> None

Reload all player profiles.

update_from_player_profiles()

update_from_player_profiles(self) -> None

Set character based on profile; otherwise use pre-picked random.

update_position()

update_position(self) -> None

Update this chooser's position.


bs.CollideModel

<top level class>

A reference to a collide-model.

Category: Asset Classes

Use bs.getcollidemodel() to instantiate one.


bs.Context

<top level class>

Context(source: Any)

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: Callable)

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 inadvertently 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 inadvertently 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, bs._dep.InstancedDepComponent, bs.DepComponent

Base class for cooperative-mode games.

Category: Gameplay Classes

Attributes Inherited:

players, settings, teams

Attributes Defined Here:

map, session, stats

map

bs.Map

The map being used for this game.

Raises a bs.NotFoundError if the map does not currently exist.

session

bs.Session

The bs.Session this bs.Activity belongs go.

Raises a bs.SessionNotFoundError if the Session no longer exists.

stats

bs.Stats

The stats instance accessible while the activity is running.

If access is attempted before or after, raises a bs.NotFoundError.

Methods Inherited:

add_actor_weak_ref(), begin(), continue_or_end_game(), create_config_ui(), create_player_node(), dep_get_payload(), end(), end_game(), get_config_display_string(), get_description(), get_description_display_string(), get_display_string(), get_dynamic_deps(), get_instance_description(), get_instance_display_string(), get_instance_scoreboard_description(), get_instance_scoreboard_display_string(), get_name(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_present(), 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: Dict[str, Any])

Instantiate the Activity.

celebrate()

celebrate(self, duration: float) -> None

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) -> None

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

get_score_type()

get_score_type(self) -> str

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

on_begin()

on_begin(self) -> None

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) -> None

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

spawn_player_spaz()

spawn_player_spaz(self, player: bs.Player, position: Sequence[float] = (0.0, 0.0, 0.0), angle: float = None) -> PlayerSpaz

Spawn and wire up a standard player spaz.

supports_session_type()

<class method>

supports_session_type(sessiontype: Type[bs.Session]) -> bool

Return whether this game supports the provided Session type.


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(), set_activity()

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) -> bs.GameActivity

Get the game instance currently being played.

get_custom_menu_entries()

get_custom_menu_entries(self) -> List[Dict[str, Any]]

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: bs.Activity, results: Any) -> None

Method override for co-op sessions.

Jumps between co-op games and score screens.

on_player_leave()

on_player_leave(self, player: bs.Player) -> None

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

restart()

restart(self) -> None

Restart the current game activity.


bs.Data

<top level class>

A reference to a data object.

Category: Asset Classes

Use bs.getdata() to instantiate one.

Methods:

getvalue()

getvalue() -> Any

Return the data object's value.

This can consist of anything representable by json (dicts, lists, numbers, bools, None, etc). Note that this call will block if the data has not yet been loaded, so it can be beneficial to plan a short bit of time between when the data object is requested and when it's value is accessed.


bs.DepComponent

<top level class>

Base class for all classes that can act as dependencies.

Category: Dependency Classes

Methods:

<constructor>, dep_get_payload(), get_dynamic_deps(), is_present()

<constructor>

bs.DepComponent()

Instantiate a DepComponent.

dep_get_payload()

<class method>

dep_get_payload(depdata: DepData) -> Any

Return user-facing data for a loaded dep.

If this dep does not yet have a 'payload' value, it should be generated and cached. Otherwise the existing value should be returned. This is the value given for a DepComponent when accessed through a Dependency instance on a live object, etc.

get_dynamic_deps()

<class method>

get_dynamic_deps(config: Any = None) -> List[Dependency]

Return any dynamically-calculated deps for this component/config.

Deps declared statically as part of the class do not need to be included here; this is only for additional deps that may vary based on the dep config value. (for instance a map required by a game type)

is_present()

<class method>

is_present(config: Any = None) -> bool

Return whether this component/config is present on this device.


bs.Dependency

inherits from: typing.Generic

A dependency on a DepComponent (with an optional config).

Category: Dependency Classes

This class is used to request and access functionality provided by other DepComponent classes from a DepComponent class. The class functions as a descriptor, allowing dependencies to be added at a class level much the same as properties or methods and then used with class instances to access those dependencies. For instance, if you do 'floofcls = bs.Dependency(FloofClass)' you would then be able to instantiate a FloofClass in your class's methods via self.floofcls().

Methods:

<constructor>, get_hash()

<constructor>

bs.Dependency(cls: Type[T], config: Any = None)

Instantiate a Dependency given a bs.DepComponent subtype.

Optionally, an arbitrary object can be passed as 'config' to influence dependency calculation for the target class.

get_hash()

get_hash(self) -> int

Return the dependency's hash, calculating it if necessary.


bs.DependencyError

inherits from: Exception, BaseException

Exception raised when one or more bs.Dependency items are missing.

Category: Exception Classes

(this will generally be missing assets).

Attributes:

deps

List[bs.Dependency]

The list of missing dependencies causing this error.

Methods Inherited:

with_traceback()

Methods Defined or Overridden:

<constructor>

bs.DependencyError(deps: List[bs.Dependency])


bs.DepSet

inherits from: typing.Generic

Set of resolved dependencies and their associated data.

Methods:

<constructor>, get_asset_package_ids(), load(), resolve()

<constructor>

bs.DepSet(root: Dependency[TI])

get_asset_package_ids()

get_asset_package_ids(self) -> Set[str]

Return the set of asset-package-ids required by this dep-set.

Must be called on a resolved dep-set.

load()

load(self) -> Type[TI]

Attach the resolved set to the current context.

Returns a wrapper which can be used to instantiate the root dep.

resolve()

resolve(self) -> None

Resolve the total set of required dependencies for the set.

Raises a bs.DependencyError if dependencies are missing (or other Exception types on other errors).


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

str

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

immediate

bool

If this is set to True, the actor should disappear immediately. This is for 'removing' stuff from the game more so 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: 'bool' = False, how: 'str' = 'generic')


bs.DropMessage

<top level class>

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

Category: Message Classes

Methods:

<constructor>

bs.DropMessage()


bs.DroppedMessage

<top level class>

Tells an object that it has been dropped.

Category: Message Classes

Attributes:

node

bs.Node

The bs.Node doing the dropping.

Methods:

<constructor>

bs.DroppedMessage(node: 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(), set_activity()

Methods Defined or Overridden:

<constructor>, get_ffa_point_awards()

<constructor>

bs.FreeForAllSession()

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

get_ffa_point_awards()

get_ffa_point_awards(self) -> Dict[int, int]

Return the number of points awarded for different rankings.

This is based on the current number of players.


bs.FreezeMessage

<top level class>

Tells an object to become frozen.

Category: Message Classes

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

Methods:

<constructor>

bs.FreezeMessage()


bs.GameActivity

inherits from: bs.Activity, bs._dep.InstancedDepComponent, bs.DepComponent

Common base class for all game bs.Activities.

Category: Gameplay Classes

Attributes Inherited:

players, settings, teams

Attributes Defined Here:

map, session, stats

map

bs.Map

The map being used for this game.

Raises a bs.NotFoundError if the map does not currently exist.

session

bs.Session

The bs.Session this bs.Activity belongs go.

Raises a bs.SessionNotFoundError if the Session no longer exists.

stats

bs.Stats

The stats instance accessible while the activity is running.

If access is attempted before or after, raises a bs.NotFoundError.

Methods Inherited:

add_actor_weak_ref(), begin(), create_player_node(), dep_get_payload(), get_dynamic_deps(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_present(), 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>, 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_name(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), 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: Dict[str, Any])

Instantiate the Activity.

continue_or_end_game()

continue_or_end_game(self) -> None

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: Type[bs.Session], config: Optional[Dict[str, Any]], completion_call: Callable[[Optional[Dict[str, Any]]], None]) -> None

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: Any = None, delay: float = 0.0, force: bool = False) -> None

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) -> None

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: Dict[str, Any]) -> bs.Lstr

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: Type[bs.Session]) -> str

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: Type[bs.Session]) -> bs.Lstr

Return a translated version of get_description().

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

get_display_string()

<class method>

get_display_string(settings: Optional[Dict] = None) -> bs.Lstr

Return a descriptive name for this game/settings combo.

Subclasses should override get_name(); not this.

get_instance_description()

get_instance_description(self) -> Union[str, Sequence]

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) -> bs.Lstr

Return a name for this particular game instance.

get_instance_scoreboard_description()

get_instance_scoreboard_description(self) -> Union[str, Sequence]

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) -> bs.Lstr

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_name()

<class method>

get_name() -> str

Return a str name for this game type.

get_resolved_score_info()

<class method>

get_resolved_score_info() -> Dict[str, Any]

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() -> Dict[str, Any]

Return info about game scoring setup; should be overridden 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: Type[bs.Session]) -> List[Tuple[str, Dict[str, Any]]]

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: Type[bs.Session]) -> List[str]

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: str) -> bs.Lstr

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

handlemessage()

handlemessage(self, msg: Any) -> Any

General message handling; can be passed any message object.

is_waiting_for_continue()

is_waiting_for_continue(self) -> bool

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

on_begin()

on_begin(self) -> None

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) -> None

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: bs.Player) -> None

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

(including the initial set of Players)

on_player_leave()

on_player_leave(self, player: bs.Player) -> None

Called when a bs.Player is leaving the Activity.

on_transition_in()

on_transition_in(self, music: str = None) -> 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: Sequence[float]) -> None

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: bs.Player, respawn_time: Optional[float] = None) -> 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 seconds).

setup_standard_powerup_drops()

setup_standard_powerup_drops(self, enable_tnt: bool = True) -> None

Create standard powerup drops for the current map.

setup_standard_time_limit()

setup_standard_time_limit(self, duration: float) -> None

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) -> None

Show the game description.

show_scoreboard_info()

show_scoreboard_info(self) -> None

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: bs.Lstr, color: Sequence[float] = (0.9, 0.4, 0.0), scale: float = 0.8, duration: float = 2.0, trail: bool = False) -> None

Zooming text used to announce game names and winners.

spawn_player()

spawn_player(self, player: bs.Player) -> bs.Actor

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: bs.Player) -> None

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: bs.Player, position: Sequence[float] = (0, 0, 0), angle: float = None) -> PlayerSpaz

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

supports_session_type()

<class method>

supports_session_type(sessiontype: Type[bs.Session]) -> bool

Return whether this game supports the provided Session type.


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: 'bs.Node' = None, pos: 'Sequence[float]' = None, velocity: 'Sequence[float]' = None, magnitude: 'float' = 1.0, velocity_magnitude: 'float' = 0.0, radius: 'float' = 1.0, source_player: 'bs.Player' = None, kick_back: 'float' = 1.0, flat_damage: 'float' = None, hit_type: 'str' = 'generic', force_direction: 'Sequence[float]' = None, hit_subtype: 'str' = '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

float

The intensity of the impact.

Methods:

<constructor>

bs.ImpactDamageMessage(intensity: float)


bs.InputDevice

<top level class>

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

Category: Gameplay Classes

Attributes:

allows_configuring, client_id, exists, id, instance_number, is_controller_app, is_remote_client, name, player, unique_identifier

allows_configuring

bool

Whether the input-device can be configured.

client_id

int

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

exists

bool

Whether the underlying device for this object is still present.

id

int

The unique numeric id of this device.

instance_number

int

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

is_controller_app

bool

Whether this input-device represents a locally-connected controller-app (BombSquad Remote).

is_remote_client

bool

Whether this input-device represents a remotely-connected client.

name

str

The name of the device.

player

Optional[bs.Player]

The player associated with this input device.

unique_identifier

str

A string that can be used to persistently identify the device, even among other devices of the same type. Used for saving prefs, etc.

Methods:

get_account_name(), get_axis_name(), get_button_name()

get_account_name()

get_account_name(full: bool) -> str

Returns the account name associated with this device.

(can be used to get account names for remote players)

get_axis_name()

get_axis_name(axis_id: int) -> str

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

get_button_name()

get_button_name(button_id: int) -> str

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


bs.InputDeviceNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.InputDevice does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


bs.Level

<top level class>

An entry in a bs.Campaign consisting of a name, game type, and settings.

Category: Gameplay Classes

Attributes:

complete, displayname, gametype, index, name, preview_texture_name, rating

complete

bool

Whether this Level has been completed.

displayname

bs.Lstr

The localized name for this Level.

gametype

Type[bs.GameActivity]

The type of game used for this Level.

index

int

The zero-based index of this Level in its bs.Campaign.

Access results in a RuntimeError if the Level is not assigned to a Campaign.

name

str

The unique name for this Level.

preview_texture_name

str

The preview texture name for this Level.

rating

float

The current rating for this Level.

Methods:

<constructor>, get_campaign(), get_high_scores(), get_preview_texture(), get_score_version_string(), get_settings(), set_complete(), set_high_scores(), set_rating()

<constructor>

bs.Level(name: str, gametype: Type[bs.GameActivity], settings: Dict[str, Any], preview_texture_name: str, displayname: str = None)

Initializes a Level object with the provided values.

get_campaign()

get_campaign(self) -> Optional[bs.Campaign]

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

get_high_scores()

get_high_scores(self) -> Dict

Return the current high scores for this Level.

get_preview_texture()

get_preview_texture(self) -> bs.Texture

Load/return the preview Texture for this Level.

get_score_version_string()

get_score_version_string(self) -> str

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) -> Dict[str, Any]

Returns the settings for this Level.

set_complete()

set_complete(self, val: bool) -> None

Set whether or not this level is complete.

set_high_scores()

set_high_scores(self, high_scores: Dict) -> None

Set high scores for this level.

set_rating()

set_rating(self, rating: float) -> None

Set a rating for this Level, replacing the old ONLY IF higher.


bs.Lobby

<top level class>

Container for choosers.

Attributes:

teams, use_team_colors

teams

List[bs.Team]

Teams available in this lobby.

use_team_colors

bool

A bool for whether this lobby is using team colors.

If False, inidividual player colors are used instead.

Methods:

<constructor>, add_chooser(), check_all_ready(), create_join_info(), get_choosers(), reload_profiles(), remove_all_choosers(), remove_all_choosers_and_kick_players(), remove_chooser(), update_positions()

<constructor>

bs.Lobby()

add_chooser()

add_chooser(self, player: bs.Player) -> None

Add a chooser to the lobby for the provided player.

check_all_ready()

check_all_ready(self) -> bool

Return whether all choosers are marked ready.

create_join_info()

create_join_info(self) -> JoinInfo

Create a display of on-screen information for joiners.

(how to switch teams, players, etc.) Intended for use in initial joining-screens.

get_choosers()

get_choosers(self) -> List[Chooser]

Return the lobby's current choosers.

reload_profiles()

reload_profiles(self) -> None

Reload available player profiles.

remove_all_choosers()

remove_all_choosers(self) -> None

Remove all choosers without kicking players.

This is called after all players check in and enter a game.

remove_all_choosers_and_kick_players()

remove_all_choosers_and_kick_players(self) -> None

Remove all player choosers and kick attached players.

remove_chooser()

remove_chooser(self, player: bs.Player) -> None

Remove a single player's chooser; does not kick him.

This is used when a player enters the game and no longer needs a chooser.

update_positions()

update_positions(self) -> None

Update positions for all choosers.


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: Any, **keywds: Any)

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) -> str

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) -> bool

Return whether 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.

Attributes:

activity

bs.Activity

The Activity this Actor was created in.

Raises a bs.ActivityNotFoundError if the Activity no longer exists.

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_name(), get_play_types(), get_preview_texture_name(), get_start_position(), handlemessage(), is_point_near_edge(), on_preload(), preload()

<constructor>

bs.Map(vr_overlay_offset: Optional[Sequence[float]] = None)

Instantiate a map.

get_def_bound_box()

get_def_bound_box(self, name: str) -> Optional[Tuple[float, float, float, float, float, float]]

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

get_def_point()

get_def_point(self, name: str) -> Optional[Sequence[float]]

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

get_def_points()

get_def_points(self, name: str) -> List[Sequence[float]]

Return a list of named points.

Return as many sequential ones are defined (flag1, flag2, flag3), etc. If none are defined, returns an empty list.

get_ffa_start_position()

get_ffa_start_position(self, players: Sequence[bs.Player]) -> Sequence[float]

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: int = None) -> Sequence[float]

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() -> Optional[str]

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

If None is returned, default music will be used.

get_name()

<class method>

get_name() -> str

Return the unique name of this map, in English.

get_play_types()

<class method>

get_play_types() -> List[str]

Return valid play types for this map.

get_preview_texture_name()

<class method>

get_preview_texture_name() -> Optional[str]

Return the name of the preview texture for this map.

get_start_position()

get_start_position(self, team_index: int) -> Sequence[float]

Return a random starting position for the given team index.

handlemessage()

handlemessage(self, msg: Any) -> Any

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: bs.Vec3, running: bool = False) -> bool

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() -> Any

Called when the map is being preloaded.

It should return any media/data it requires to operate

preload()

<class method>

preload() -> None

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(label: str = 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.

Attributes:

label

str

A label for the material; only used for debugging.

Methods:

add_actions()

add_actions(actions: Tuple, conditions: Optional[Tuple] = 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)))

bs.Model

<top level class>

A reference to a model.

Category: Asset Classes

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


bs.MusicPlayer

<top level class>

Wrangles soundtrack music playback.

Music can be played either through the game itself or via a platform-specific external player.

Methods:

<constructor>, on_play(), on_select_entry(), on_set_volume(), on_shutdown(), on_stop(), play(), select_entry(), set_volume(), shutdown(), stop()

<constructor>

bs.MusicPlayer()

on_play()

on_play(self, entry: Any) -> None

Called when a new song/playlist/etc should be played.

on_select_entry()

on_select_entry(self, callback: Callable[[Any], None], current_entry: Any, selection_target_name: str) -> Any

Present a GUI to select an entry.

The callback should be called with a valid entry or None to signify that the default soundtrack should be used..

on_set_volume()

on_set_volume(self, volume: float) -> None

Called when the volume should be changed.

on_shutdown()

on_shutdown(self) -> None

Called on final app shutdown.

on_stop()

on_stop(self) -> None

Called when the music should stop.

play()

play(self, entry: Any) -> None

Play provided entry.

select_entry()

select_entry(self, callback: Callable[[Any], None], current_entry: Any, selection_target_name: str) -> Any

Summons a UI to select a new soundtrack entry.

set_volume()

set_volume(self, volume: float) -> None

Set player volume (value should be between 0 and 1).

shutdown()

shutdown(self) -> None

Shutdown music playback completely.

stop()

stop(self) -> None

Stop any playback that is occurring.


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 Python references 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(), get_name(), getdelegate(), getnodetype(), handlemessage()

add_death_action()

add_death_action(action: Callable[[], None]) -> 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: str, dstnode: Node, dstattr: str) -> 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: bool = 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 nonexistent 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.

get_name()

get_name() -> str

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

getdelegate()

getdelegate() -> Any

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

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: Any) -> 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.NodeNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Node does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


bs.NotFoundError

inherits from: Exception, BaseException

Exception raised when a referenced object does not exist.

Category: Exception Classes

Methods:

<all methods inherited from builtins.Exception>


bs.OldWindow

<top level class>

Temp for transitioning windows over to UILocationWindows.

Methods:

<constructor>, get_root_widget()

<constructor>

bs.OldWindow(root_widget: bs.Widget)

get_root_widget()

get_root_widget(self) -> bs.Widget

Return the root widget.


bs.OutOfBoundsMessage

<top level class>

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

Category: Message Classes

Methods:

<constructor>

bs.OutOfBoundsMessage()


bs.PickedUpMessage

<top level class>

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

Category: Message Classes

Attributes:

node

bs.Node

The bs.Node doing the picking up.

Methods:

<constructor>

bs.PickedUpMessage(node: bs.Node)


bs.PickUpMessage

<top level class>

Tells an object that it has picked something up.

Category: Message Classes

Attributes:

node

bs.Node

The bs.Node that is getting picked up.

Methods:

<constructor>

bs.PickUpMessage(node: 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. 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 attribute (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, exists, gamedata, highlight, in_game, node, sessiondata, team

actor

Optional[bs.Actor]

The current bs.Actor associated with this Player. This may be None

character

str

The character this player has selected in their profile.

color

Sequence[float]

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

exists

bool

Whether the player still exists. Most functionality will fail on a nonexistent 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.

gamedata

Dict

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

Sequence[float]

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.

in_game

bool

This bool value will be True once the Player has completed any lobby character/team selection.

node

Optional[bs.Node]

A bs.Node of type 'player' associated with this Player. This Node exists in the currently active game and can be used to get a generic player position/etc. This will be None if the Player is not in a game.

sessiondata

Dict

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

team

bs.Team

The bs.Team this Player is on. If the Player is still in its lobby selecting a team/etc. then a bs.TeamNotFoundError will be raised.

Methods:

assign_input_call(), get_account_id(), get_icon(), get_id(), get_input_device(), get_name(), is_alive(), remove_from_game(), reset_input(), set_actor(), set_name()

assign_input_call()

assign_input_call(type: Union[str, Tuple[str, ...]], call: Callable) -> 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'

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[str, Any]

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

get_id()

get_id() -> int

Returns the unique numeric player ID for this player.

get_input_device()

get_input_device() -> bs.InputDevice

Returns the player's input device.

get_name()

get_name(full: bool = False, icon: bool = 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: Optional[bs.Actor]) -> None

Set the player's associated bs.Actor.

set_name()

set_name(name: str, full_name: str = None, real: bool = True) -> 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.PlayerNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Player does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


bs.PlayerRecord

<top level class>

Stats for an individual player in a bs.Stats object.

Category: Gameplay Classes

This does not necessarily correspond to a bs.Player that is still present (stats may be retained for players that leave mid-game)

Attributes:

player, team

player

bs.Player

Return the instance's associated bs.Player.

Raises a bs.PlayerNotFoundError if the player no longer exists.

team

bs.Team

The bs.Team the last associated player was last on.

This can still return a valid result even if the player is gone. Raises a bs.TeamNotFoundError if the team no longer exists.

Methods:

<constructor>, associate_with_player(), cancel_multi_kill_timer(), get_icon(), get_last_player(), get_name(), get_spaz(), getactivity(), submit_kill()

<constructor>

bs.PlayerRecord(name: str, name_full: str, player: bs.Player, stats: bs.Stats)

associate_with_player()

associate_with_player(self, player: bs.Player) -> None

Associate this entry with a bs.Player.

cancel_multi_kill_timer()

cancel_multi_kill_timer(self) -> None

Cancel any multi-kill timer for this player entry.

get_icon()

get_icon(self) -> Dict[str, Any]

Get the icon for this instance's player.

get_last_player()

get_last_player(self) -> bs.Player

Return the last bs.Player we were associated with.

get_name()

get_name(self, full: bool = False) -> str

Return the player entry's name.

get_spaz()

get_spaz(self) -> Optional[bs.Actor]

Return the player entry's spaz.

getactivity()

getactivity(self) -> Optional[bs.Activity]

Return the bs.Activity this instance is currently associated with.

Returns None if the activity no longer exists.

submit_kill()

submit_kill(self, showpoints: bool = True) -> None

Submit a kill for this player entry.


bs.PlayerScoredMessage

<top level class>

Informs something that a bs.Player scored.

Category: Message Classes

Attributes:

score

int

The score value.

Methods:

<constructor>

bs.PlayerScoredMessage(score: int)


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.

Methods:

<constructor>

bs.PowerupAcceptMessage()


bs.PowerupMessage

<top level class>

A message telling an object to accept a powerup.

Category: Message Classes

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

Attributes:

poweruptype, source_node

poweruptype

str

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

source_node

Optional[bs.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: str, source_node: Optional[bs.Node] = None)


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

Optional[bs.Campaign]

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

lobby

bs.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

int

The maximum number of Players allowed in the Session.

min_players

int

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

players

List[bs.Player]

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

List[bs.Team]

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(), set_activity()

<constructor>

bs.Session(depsets: Sequence[bs.DepSet], team_names: Sequence[str] = None, team_colors: Sequence[Sequence[float]] = None, use_team_colors: bool = True, min_players: int = 1, max_players: int = 8, allow_mid_activity_joins: bool = True)

Instantiate a session.

depsets should be a sequence of successfully resolved bs.DepSet instances; one for each bs.Activity the session may potentially run.

begin_next_activity()

begin_next_activity(self) -> None

Called once the previous activity has been totally torn down.

This means we're ready to begin the next one

end()

end(self) -> None

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: bs.Activity, results: Any, delay: float, force: bool) -> None

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) -> List[Dict[str, Any]]

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) -> Optional[bs.Activity]

Return the current foreground activity for this session.

handlemessage()

handlemessage(self, msg: Any) -> Any

General message handling; can be passed any message object.

on_activity_end()

on_activity_end(self, activity: bs.Activity, results: Any) -> None

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: bs.Player) -> None

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

on_player_request()

on_player_request(self, player: bs.Player) -> bool

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: bs.Team) -> None

Called when a new bs.Team joins the session.

on_team_leave()

on_team_leave(self, team: bs.Team) -> None

Called when a bs.Team is leaving the session.

set_activity()

set_activity(self, activity: bs.Activity) -> None

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.set_activity(foo) and then bs.newnode() to add a node to foo)


bs.SessionNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Session does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


bs.ShouldShatterMessage

<top level class>

Tells an object that it should shatter.

Category: Message Classes

Methods:

<constructor>

bs.ShouldShatterMessage()


bs.Sound

<top level class>

A reference to a sound.

Category: Asset Classes

Use bs.getsound() to instantiate one.


bs.SpecialChar

inherits from: enum.Enum

Special characters the game can print.

Category: Enums

Values:

  • DOWN_ARROW
  • UP_ARROW
  • LEFT_ARROW
  • RIGHT_ARROW
  • TOP_BUTTON
  • LEFT_BUTTON
  • RIGHT_BUTTON
  • BOTTOM_BUTTON
  • DELETE
  • SHIFT
  • BACK
  • LOGO_FLAT
  • REWIND_BUTTON
  • PLAY_PAUSE_BUTTON
  • FAST_FORWARD_BUTTON
  • DPAD_CENTER_BUTTON
  • OUYA_BUTTON_O
  • OUYA_BUTTON_U
  • OUYA_BUTTON_Y
  • OUYA_BUTTON_A
  • OUYA_LOGO
  • LOGO
  • TICKET
  • GOOGLE_PLAY_GAMES_LOGO
  • GAME_CENTER_LOGO
  • DICE_BUTTON1
  • DICE_BUTTON2
  • DICE_BUTTON3
  • DICE_BUTTON4
  • GAME_CIRCLE_LOGO
  • PARTY_ICON
  • TEST_ACCOUNT
  • TICKET_BACKING
  • TROPHY1
  • TROPHY2
  • TROPHY3
  • TROPHY0A
  • TROPHY0B
  • TROPHY4
  • LOCAL_ACCOUNT
  • ALIBABA_LOGO
  • FLAG_UNITED_STATES
  • FLAG_MEXICO
  • FLAG_GERMANY
  • FLAG_BRAZIL
  • FLAG_RUSSIA
  • FLAG_CHINA
  • FLAG_UNITED_KINGDOM
  • FLAG_CANADA
  • FLAG_INDIA
  • FLAG_JAPAN
  • FLAG_FRANCE
  • FLAG_INDONESIA
  • FLAG_ITALY
  • FLAG_SOUTH_KOREA
  • FLAG_NETHERLANDS
  • FEDORA
  • HAL
  • CROWN
  • YIN_YANG
  • EYE_BALL
  • SKULL
  • HEART
  • DRAGON
  • HELMET
  • MUSHROOM
  • NINJA_STAR
  • VIKING_HELMET
  • MOON
  • SPIDER
  • FIREBALL
  • FLAG_UNITED_ARAB_EMIRATES
  • FLAG_QATAR
  • FLAG_EGYPT
  • FLAG_KUWAIT
  • FLAG_ALGERIA
  • FLAG_SAUDI_ARABIA
  • FLAG_MALAYSIA
  • FLAG_CZECH_REPUBLIC
  • FLAG_AUSTRALIA
  • FLAG_SINGAPORE
  • OCULUS_LOGO
  • STEAM_LOGO
  • NVIDIA_LOGO
  • FLAG_IRAN
  • FLAG_POLAND
  • FLAG_ARGENTINA
  • FLAG_PHILIPPINES
  • FLAG_CHILE
  • MIKIROG

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

float

The angle to face (in degrees)

position

Sequence[float]

Where to move to.

Methods:

<constructor>

bs.StandMessage(position: Sequence[float] = (0.0, 0.0, 0.0), angle: float = 0.0)


bs.Stats

<top level class>

Manages scores and statistics for a bs.Session.

Category: Gameplay Classes

Methods:

<constructor>, get_records(), getactivity(), player_got_hit(), player_got_new_spaz(), player_lost_spaz(), player_scored(), register_player(), reset(), reset_accum(), set_activity()

<constructor>

bs.Stats()

get_records()

get_records(self) -> Dict[str, bs.PlayerRecord]

Get PlayerRecord corresponding to still-existing players.

getactivity()

getactivity(self) -> Optional[bs.Activity]

Get the activity associated with this instance.

May return None.

player_got_hit()

player_got_hit(self, player: bs.Player) -> None

Call this when a player got hit.

player_got_new_spaz()

player_got_new_spaz(self, player: bs.Player, spaz: bs.Actor) -> None

Call this when a player gets a new Spaz.

player_lost_spaz()

player_lost_spaz(self, player: bs.Player, killed: bool = False, killer: bs.Player = None) -> None

Should be called when a player loses a spaz.

player_scored()

player_scored(self, player: bs.Player, base_points: int = 1, target: Sequence[float] = None, kill: bool = False, victim_player: bs.Player = None, scale: float = 1.0, color: Sequence[float] = None, title: Union[str, bs.Lstr] = None, screenmessage: bool = True, display: bool = True, importance: int = 1, showpoints: bool = True, big_message: bool = False) -> int

Register a score for the player.

Return value is actual score with multipliers and such factored in.

register_player()

register_player(self, player: bs.Player) -> None

Register a player with this score-set.

reset()

reset(self) -> None

Reset the stats instance completely.

reset_accum()

reset_accum(self) -> None

Reset per-sound sub-scores.

set_activity()

set_activity(self, activity: bs.Activity) -> None

Set the current activity for this instance.


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

Tuple[float, ...]

The team's color.

gamedata

Dict

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

Union[bs.Lstr, str]

The team's name.

players

List[bs.Player]

The list of bs.Players on the team.

sessiondata

Dict

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

Methods:

<constructor>, celebrate(), get_id()

<constructor>

bs.Team(team_id: 'int' = 0, name: 'Union[bs.Lstr, str]' = '', color: 'Sequence[float]' = (1.0, 1.0, 1.0))

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: float = 10.0) -> None

Tells all players on the team to celebrate.

duration is given in seconds.

get_id()

get_id(self) -> int

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(), set_activity()

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: bs.GameActivity, results: bs.TeamGameResults, delay: float, announce_winning_team: bool = True) -> None

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) -> int

Return free-for-all series length.

get_game_number()

get_game_number(self) -> int

Returns which game in the series is currently being played.

get_max_players()

get_max_players(self) -> int

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

get_next_game_description()

get_next_game_description(self) -> bs.Lstr

Returns a description of the next game on deck.

get_series_length()

get_series_length(self) -> int

Return teams series length.

on_activity_end()

on_activity_end(self, activity: bs.Activity, results: Any) -> None

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: bs.Team) -> None

Called when a new bs.Team joins the session.


bs.TeamGameActivity

inherits from: bs.GameActivity, bs.Activity, bs._dep.InstancedDepComponent, bs.DepComponent

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

Attributes Defined Here:

map, session, stats

map

bs.Map

The map being used for this game.

Raises a bs.NotFoundError if the map does not currently exist.

session

bs.Session

The bs.Session this bs.Activity belongs go.

Raises a bs.SessionNotFoundError if the Session no longer exists.

stats

bs.Stats

The stats instance accessible while the activity is running.

If access is attempted before or after, raises a bs.NotFoundError.

Methods Inherited:

add_actor_weak_ref(), begin(), continue_or_end_game(), create_config_ui(), create_player_node(), dep_get_payload(), end_game(), get_config_display_string(), get_description(), get_description_display_string(), get_display_string(), get_dynamic_deps(), get_instance_description(), get_instance_display_string(), get_instance_scoreboard_description(), get_instance_scoreboard_display_string(), get_name(), get_resolved_score_info(), get_score_info(), get_settings(), get_supported_maps(), get_team_display_string(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), is_expired(), is_present(), 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: Dict[str, Any])

Instantiate the Activity.

end()

end(self, results: Any = None, announce_winning_team: bool = True, announce_delay: float = 0.1, force: bool = False) -> None

End the game and announce the single winning team unless 'announce_winning_team' is False. (for results without a single most-important winner).

on_begin()

on_begin(self) -> None

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: str = None) -> 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: bs.Player, position: Sequence[float] = None, angle: float = None) -> PlayerSpaz

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: Type[bs.Session]) -> bool

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) -> bool

Return whether lower scores are better.

get_player_info()

get_player_info(self) -> List[Dict[str, Any]]

Get info about the players represented by the results.

get_score_name()

get_score_name(self) -> str

Get the name associated with scores ('points', etc).

get_score_type()

get_score_type(self) -> str

Get the type of score.

get_team_score()

get_team_score(self, team: bs.Team) -> Optional[int]

Return the score for a given team.

get_team_score_str()

get_team_score_str(self, team: bs.Team) -> bs.Lstr

Return the score for the given bs.Team as an Lstr.

(properly formatted for the score type.)

get_teams()

get_teams(self) -> List[bs.Team]

Return all bs.Teams in the results.

get_winners()

get_winners(self) -> List[WinnerGroup]

Get an ordered list of winner groups.

get_winning_team()

get_winning_team(self) -> Optional[bs.Team]

Get the winning bs.Team if there is exactly one; None otherwise.

has_score_for_team()

has_score_for_team(self, team: bs.Team) -> bool

Return whether there is a score for a given team.

set_game()

set_game(self, game: bs.GameActivity) -> None

Set the game instance these results are applying to.

set_team_score()

set_team_score(self, team: bs.Team, score: int) -> None

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.TeamNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Team does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


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(), set_activity()

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: Asset Classes

Use bs.gettexture() to instantiate one.


bs.ThawMessage

<top level class>

Tells an object to stop being frozen.

Category: Message Classes

Methods:

<constructor>

bs.ThawMessage()


bs.TimeFormat

inherits from: enum.Enum

Specifies the format time values are provided in.

Category: Enums

Values:

  • SECONDS
  • MILLISECONDS

bs.Timer

<top level class>

Timer(time: float, call: Callable[[], Any], repeat: bool = False, timetype: bs.TimeType = TimeType.SIM, timeformat: bs.TimeFormat = TimeFormat.SECONDS, suppress_format_warning: bool = False)

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 SECONDS but can also be MILLISECONDS 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.TimeType

inherits from: enum.Enum

Specifies the type of time for various operations to target/use.

Category: Enums

'sim' time is the local simulation time for an activity or session. It can proceed at different rates depending on game speed, stops for pauses, etc.

'base' is the baseline time for an activity or session. It proceeds consistently regardless of game speed or pausing, but may stop during occurrances such as network outages.

'real' time is mostly based on clock time, with a few exceptions. It may not advance while the app is backgrounded for instance. (the engine attempts to prevent single large time jumps from occurring)

Values:

  • SIM
  • BASE
  • REAL

bs.UIController

<top level class>

Wrangles UILocations.

Methods:

<constructor>, show_main_menu()

<constructor>

bs.UIController()

show_main_menu()

show_main_menu(self, in_game: bool = True) -> None

Show the main menu, clearing other UIs from location stacks.


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()

push_location()

push_location(self, location: str) -> None

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

restore_state()

restore_state(self) -> None

Restore this instance's state from a dict.

save_state()

save_state(self) -> None

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:

push_location(), restore_state(), save_state()

Methods Defined or Overridden:

<constructor>, get_root_widget()

<constructor>

bs.UILocationWindow()

get_root_widget()

get_root_widget(self) -> bs.Widget

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

float

The vector's X component.

y

float

The vector's Y component.

z

float

The vector's Z component.

Methods:

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

cross()

cross(other: Vec3) -> Vec3

Returns the cross product of this vector and another.

dot()

dot(other: Vec3) -> float

Returns the dot product of this vector and another.

length()

length() -> float

Returns the length of the vector.

normalized()

normalized() -> 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: Any, **keywds: Any)

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: Callable) -> None

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

delete()

delete(ignore_missing: bool = 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 nonexistent 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[bs.Widget]

Returns any child Widgets of this Widget.

get_screen_space_center()

get_screen_space_center() -> Tuple[float, float]

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() -> Optional[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.WidgetNotFoundError

inherits from: bs.NotFoundError, Exception, BaseException

Exception raised when an expected bs.Widget does not exist.

Category: Exception Classes

Methods:

<all methods inherited from bs.NotFoundError>


bs.animate()

animate(node: bs.Node, attr: str, keys: Dict[float, float], loop: bool = False, offset: float = 0, timetype: bs.TimeType = <TimeType.SIM: 0>, timeformat: bs.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> bs.Node

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 MILLISECONDS to recreate the old behavior (prior to bs 1.5) of taking milliseconds. Returns the animcurve node.


bs.animate_array()

animate_array(node: bs.Node, attr: str, size: int, keys: Dict[float, Sequence[float]], loop: bool = False, offset: float = 0, timetype: bs.TimeType = <TimeType.SIM: 0>, timeformat: bs.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> None

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

Category: Gameplay Functions

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


bs.buttonwidget()

buttonwidget(edit: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, on_activate_call: Callable = None, label: Union[str, bs.Lstr] = None, color: Sequence[float] = None, down_widget: bs.Widget = None, up_widget: bs.Widget = None, left_widget: bs.Widget = None, right_widget: bs.Widget = None, texture: bs.Texture = None, text_scale: float = None, textcolor: Sequence[float] = None, enable_sound: bool = None, model_transparent: bs.Model = None, model_opaque: bs.Model = None, repeat: bool = None, scale: float = None, transition_delay: float = None, on_select_call: Callable = None, button_type: str = None, extra_touch_border_scale: float = None, selectable: bool = None, show_buffer_top: float = None, icon: bs.Texture = None, iconscale: float = None, icon_tint: float = None, icon_color: Sequence[float] = None, autoselect: bool = None, mask_texture: bs.Texture = None, tint_texture: bs.Texture = None, tint_color: Sequence[float] = None, tint2_color: Sequence[float] = None, text_flatness: float = None, text_res_scale: float = None, enabled: bool = 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.cameraflash()

cameraflash(duration: float = 999.0) -> None

Create a strobing camera flash effect.

Category: Gameplay Functions

(as seen when a team wins a game) Duration is in seconds.


bs.camerashake()

camerashake(intensity: float = 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.charstr()

charstr(char_id: bs.SpecialChar) -> str

Get a unicode string representing a special 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.

see bs.SpecialChar for the list of available characters.


bs.checkboxwidget()

checkboxwidget(edit: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, text: Union[bs.Lstr, str] = None, value: bool = None, on_value_change_call: Callable[[bool], None] = None, on_select_call: Callable[[], None] = None, text_scale: float = None, textcolor: Sequence[float] = None, scale: float = None, is_radio_button: bool = None, maxwidth: float = None, autoselect: bool = None, color: Sequence[float] = 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: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: bs.Widget = None, visible_child: bs.Widget = None, single_depth: bool = None, print_list_exit_instructions: bool = None, left_border: float = None, top_border: float = None, bottom_border: float = 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: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: bs.Widget = None, transition: str = None, cancel_button: bs.Widget = None, start_button: bs.Widget = None, root_selectable: bool = None, on_activate_call: Callable[[], None] = None, claims_left_right: bool = None, claims_tab: bool = None, selection_loops: bool = None, selection_loop_to_parent: bool = None, scale: float = None, on_outside_click_call: Callable[[], None] = None, single_depth: bool = None, visible_child: bs.Widget = None, stack_offset: Sequence[float] = None, color: Sequence[float] = None, on_cancel_call: Callable[[], None] = None, print_list_exit_instructions: bool = None, click_activate: bool = None, always_highlight: bool = None, selectable: bool = None, scale_origin_stack_offset: Sequence[float] = None, toolbar_visibility: str = None, on_select_call: Callable[[], None] = None, claim_outside_clicks: bool = None, claims_up_down: bool = 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: Sequence[float], velocity: Optional[Sequence[float]] = None, count: int = 10, scale: float = 1.0, spread: float = 1.0, chunk_type: str = 'rock', emit_type: str ='chunks', tendril_type: str = '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: Any) -> Any

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.get_valid_languages()

get_valid_languages() -> List[str]

Return a list containing names of all available languages.

Category: General Utility Functions

Languages that may be present but are not displayable on the running version of the game are ignored.


bs.getactivity()

getactivity(doraise: bool = 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: str) -> bs.CollideModel

Return a collide-model, loading it if necessary.

Category: Asset 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: str) -> List[str]

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

Category: Asset Functions

Maps supporting a given playtype 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: str) -> bs.Model

Return a model, loading it if necessary.

Category: Asset 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: bool = 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: str) -> bs.Sound

Return a sound, loading it if necessary.

Category: Asset 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: str) -> bs.Texture

Return a texture, loading it if necessary.

Category: Asset 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: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: bs.Widget = None, capture_arrows: bool = None, on_select_call: Callable[[], None] = None, center_small_content: bool = None, color: Sequence[float] = None, highlight: bool = None, border_opacity: float = None, simple_culling_h: float = 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: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, color: Sequence[float] = None, texture: bs.Texture = None, opacity: float = None, model_transparent: bs.Model = None, model_opaque: bs.Model = None, has_alpha_channel: bool = True, tint_texture: bs.Texture = None, tint_color: Sequence[float] = None, transition_delay: float = None, draw_controller: bs.Widget = None, tint2_color: Sequence[float] = None, tilt_scale: float = None, mask_texture: bs.Texture = None, radial_amount: float = 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() -> bool

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: Sequence[float], box: Sequence[float]) -> bool

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: str, to_console: bool = True, newline: bool = True, to_server: bool = 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: Type[bs.Activity], settings: dict = 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: str, owner: Union[Node, bs.Actor] = None, attrs: dict = None, name: str = None, delegate: Any = None) -> 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: Sequence[float]) -> Tuple[float, ...]

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

Category: General Utility Functions


bs.open_url()

open_url(address: str) -> 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: Sound, volume: float = 1.0, position: Sequence[float] = None, host_only: bool = 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(err_str: str, once: bool = False) -> None

Print info about an error along with pertinent 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: Any, **keywds: Any) -> None

Print info about an exception along with pertinent 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: Callable, from_other_thread: bool = 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: bool = False, back: bool = 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: Widget =None, parent: Widget =None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: Widget = None, visible_child: Widget = None) -> 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: Sequence[float], target_intensity: float = 0.6) -> Tuple[float, ...]

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: Union[str, bs.Lstr], color: Sequence[float] = None, top: bool = False, image: Dict[str, Any] = None, log: bool = False, clients: Sequence[int] = None, transient: bool = 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: bs.Widget = None, parent: bs.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: bs.Widget = None, capture_arrows: bool = False, on_select_call: Callable = None, center_small_content: bool = None, color: Sequence[float] = None, highlight: bool = None, border_opacity: float = None, simple_culling_v: float = 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: str) -> 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.setlanguage()

setlanguage(language: Optional[str], print_change: bool = True, store_to_config: bool = True) -> None

Set the active language used for the game.

Category: General Utility Functions

Pass None to use OS default language.


bs.setmusic()

setmusic(musictype: Optional[str], continuous: bool = False) -> None

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: str) -> Any

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 receive 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: str, position: Sequence[float], direction: Sequence[float]) -> None

Pop up a damage count at a position in space.


bs.textwidget()

textwidget(edit: Widget = None, parent: Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, text: Union[str, bs.Lstr] = None, v_align: str = None, h_align: str = None, editable: bool = None, padding: float = None, on_return_press_call: Callable[[], None] = None, on_activate_call: Callable[[], None] = None, selectable: bool = None, query: Widget = None, max_chars: int = None, color: Sequence[float] = None, click_activate: bool = None, on_select_call: Callable[[], None] = None, always_highlight: bool = None, draw_controller: Widget = None, scale: float = None, corner_scale: float = None, description: Union[str, bs.Lstr] = None, transition_delay: float = None, maxwidth: float = None, max_height: float = None, flatness: float = None, shadow: float = None, autoselect: bool = None, rotate: float = None, enabled: bool = None, force_internal_editing: bool = None, always_show_carat: bool = None, big: bool = None, extra_touch_border_scale: float = None, res_scale: float = None) -> 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: bs.TimeType = TimeType.SIM, timeformat: bs.TimeFormat = TimeFormat.SECONDS) -> Union[float, int]

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 SECONDS which returns float seconds, but it can also be MILLISECONDS to return integer milliseconds.

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


bs.timer()

timer(time: float, call: Callable[[], Any], repeat: bool = False, timetype: bs.TimeType = TimeType.SIM, timeformat: bs.TimeFormat = TimeFormat.SECONDS, suppress_format_warning: bool = False) -> 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 seconds but can also be 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: float, centi: bool = True, timeformat: bs.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> bs.Lstr

Generate a bs.Lstr 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 'timeval' is specified in seconds by default, or 'timeformat' can be set to bs.TimeFormat.MILLISECONDS to accept milliseconds instead.

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 consume significant network bandwidth. For that purpose you should use a 'timedisplay' Node and attribute connections.


bs.uicleanupcheck()

uicleanupcheck(obj: Any, widget: bs.Widget) -> None

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.vec3validate()

vec3validate(value: Sequence[float]) -> Sequence[float]

Ensure a value is valid for use as a Vec3.

Category: General Utility Functions

Raises a TypeError exception if not. Valid values include any type of sequence consisting of 3 numeric values. Returns the same value as passed in (but with a definite type so this can be used to disambiguate 'Any' types). Generally this should be used in 'if __debug__' or assert clauses to keep runtime overhead minimal.


bs.widget()

widget(edit: bs.Widget = None, up_widget: bs.Widget = None, down_widget: bs.Widget = None, left_widget: bs.Widget = None, right_widget: bs.Widget = None, show_buffer_top: float = None, show_buffer_bottom: float = None, show_buffer_left: float = None, show_buffer_right: float = None, autoselect: bool = 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