317 KiB
last updated on 2020-06-11 for Ballistica version 1.5.3 build 20067
This page documents the Python classes and functions in the 'ba' module, which are the ones most relevant to modding in Ballistica. 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
- ba.Activity
- ba.Actor
- ba.Chooser
- ba.GameResults
- ba.GameTip
- ba.InputDevice
- ba.Level
- ba.Lobby
- ba.Material
- ba.Node
- ba.Player
- ba.PlayerInfo
- ba.PlayerRecord
- ba.ScoreConfig
- ba.Session
- ba.SessionPlayer
- ba.SessionTeam
- ba.Setting
- ba.StandLocation
- ba.Stats
- ba.Team
Gameplay Functions
- ba.animate()
- ba.animate_array()
- ba.cameraflash()
- ba.camerashake()
- ba.emitfx()
- ba.existing()
- ba.getactivity()
- ba.getnodes()
- ba.getsession()
- ba.newnode()
- ba.playsound()
- ba.printnodes()
- ba.setmusic()
- ba.show_damage_count()
General Utility Classes
General Utility Functions
- ba.charstr()
- ba.do_once()
- ba.get_valid_languages()
- ba.is_browser_likely_available()
- ba.is_point_in_box()
- ba.log()
- ba.newactivity()
- ba.normalized_color()
- ba.open_url()
- ba.print_error()
- ba.print_exception()
- ba.printobjects()
- ba.pushcall()
- ba.quit()
- ba.safecolor()
- ba.screenmessage()
- ba.set_analytics_screen()
- ba.setlanguage()
- ba.storagename()
- ba.time()
- ba.timer()
- ba.timestring()
- ba.vec3validate()
- ba.verify_object_death()
Asset Classes
Asset Functions
Message Classes
- ba.CelebrateMessage
- ba.DieMessage
- ba.DropMessage
- ba.DroppedMessage
- ba.FreezeMessage
- ba.HitMessage
- ba.ImpactDamageMessage
- ba.OutOfBoundsMessage
- ba.PickedUpMessage
- ba.PickUpMessage
- ba.PlayerDiedMessage
- ba.PlayerScoredMessage
- ba.PowerupAcceptMessage
- ba.PowerupMessage
- ba.ShouldShatterMessage
- ba.StandMessage
- ba.ThawMessage
App Classes
User Interface Classes
User Interface Functions
- ba.buttonwidget()
- ba.checkboxwidget()
- ba.columnwidget()
- ba.containerwidget()
- ba.hscrollwidget()
- ba.imagewidget()
- ba.rowwidget()
- ba.scrollwidget()
- ba.textwidget()
- ba.uicleanupcheck()
- ba.widget()
Dependency Classes
Enums
- ba.DeathType
- ba.InputType
- ba.MusicPlayMode
- ba.MusicType
- ba.Permission
- ba.ScoreType
- ba.SpecialChar
- ba.TimeFormat
- ba.TimeType
Exception Classes
Misc Classes
Misc Functions
Protocols
Settings Classes
ba.Achievement
<top level class>
Represents attributes and state for an individual achievement.
Category: App Classes
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
-
Get a ba.Lstr for the Achievement's brief description.
description_complete
-
Get a ba.Lstr for the Achievement's description when completed.
description_full
-
Get a ba.Lstr for the Achievement's full description.
description_full_complete
-
Get a ba.Lstr for the Achievement's full desc. when completed.
display_name
-
Return a ba.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>
-
ba.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[ba.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) -> ba.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.
ba.Activity
Inherits from: ba.DependencyComponent, typing.Generic
Units of execution wrangled by a ba.Session.
Category: Gameplay Classes
Examples of Activities include games, score-screens, cutscenes, etc. A ba.Session has one 'current' Activity at any time, though their existence can overlap during transitions.
Attributes:
customdata, expired, globalsnode, players, playertype, session, settings_raw, stats, teams, teamtype
customdata
-
dict
Entities needing to store simple data with an activity can put it here. This dict will be deleted when the activity expires, so contained objects generally do not need to worry about handling expired activities.
expired
-
bool
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'.
globalsnode
-
The 'globals' ba.Node for the activity. This contains various global controls and values.
players
-
List[PlayerType]
The list of ba.Players in the Activity. This gets populated just before on_begin() is called and is updated automatically as players join or leave the game.
playertype
-
Type[PlayerType]
The type of ba.Player this Activity is using.
session
-
The ba.Session this ba.Activity belongs go.
Raises a ba.SessionNotFoundError if the Session no longer exists.
settings_raw
-
Dict[str, Any]
The settings dict passed in when the activity was made. This attribute is deprecated and should be avoided when possible; activities should pull all values they need from the 'settings' arg passed to the Activity __init__ call.
stats
-
The stats instance accessible while the activity is running.
If access is attempted before or after, raises a ba.NotFoundError.
teams
-
List[TeamType]
The list of ba.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).
teamtype
-
Type[TeamType]
The type of ba.Team this Activity is using.
Methods Inherited:
dep_is_present(), get_dynamic_deps()
Methods Defined or Overridden:
<constructor>, add_actor_weak_ref(), create_player(), create_team(), end(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), 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(), transition_out()
<constructor>
-
ba.Activity(settings: dict)
Creates an Activity in the current ba.Session.
The activity will not be actually run until ba.Session.setactivity() is called. 'settings' should be a dict of key/value pairs specific to the activity.
Activities should preload as much of their media/etc as possible in their constructor, but none of it should actually be used until they are transitioned in.
add_actor_weak_ref()
-
add_actor_weak_ref(self, actor: ba.Actor) -> None
Add a weak-reference to a ba.Actor to the ba.Activity.
(called by the ba.Actor base class)
create_player()
-
create_player(self, sessionplayer: ba.SessionPlayer) -> PlayerType
Create the Player instance for this Activity.
Subclasses can override this if the activity's player class requires a custom constructor; otherwise it will be called with no args. Note that the player object should not be used at this point as it is not yet fully wired up; wait for on_player_join() for that.
create_team()
-
create_team(self, sessionteam: ba.SessionTeam) -> TeamType
Create the Team instance for this Activity.
Subclasses can override this if the activity's team class requires a custom constructor; otherwise it will be called with no args. Note that the team object should not be used at this point as it is not yet fully wired up; wait for on_team_join() for that.
end()
-
end(self, results: Any = None, delay: float = 0.0, force: bool = False) -> None
Commences Activity shutdown and delivers results to the ba.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_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 ba.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: PlayerType) -> None
Called when a new ba.Player has joined the Activity.
(including the initial set of Players)
on_player_leave()
-
on_player_leave(self, player: PlayerType) -> None
Called when a ba.Player is leaving the Activity.
on_team_join()
-
on_team_join(self, team: TeamType) -> None
Called when a new ba.Team joins the Activity.
(including the initial set of Teams)
on_team_leave()
-
on_team_leave(self, team: TeamType) -> None
Called when a ba.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 players or teams, however. They remain owned by the previous Activity up until ba.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 end() has not been called.
retain_actor()
-
retain_actor(self, actor: ba.Actor) -> None
Add a strong-reference to a ba.Actor to this Activity.
The reference will be lazily released once ba.Actor.exists() returns False for the Actor. The ba.Actor.autoretain() method is a convenient way to access this same functionality.
transition_out()
-
transition_out(self) -> None
Called by the Session to start us transitioning out.
ba.ActivityNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Activity does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.Actor
<top level class>
High level logical entities in a ba.Activity.
Category: Gameplay Classes
Actors act as controllers, combining some number of ba.Nodes, ba.Textures, ba.Sounds, etc. into a high-level cohesive unit.
Some example actors include the Bomb, Flag, and Spaz classes that live in the bastd.actor.* modules.
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:
from bastd.actor.flag import Flag
self.flag = 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 ba.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 ba.Actor.autoretain() method if you want an Actor to stick around until explicitly killed regardless of references.
Another key feature of ba.Actor is its handlemessage() method, which takes a single arbitrary object as an argument. This provides a safe way to communicate between ba.Actor, ba.Activity, ba.Session, and any other class providing a handlemessage() method. The most universally handled message type for Actors is the ba.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(ba.DieMessage())
Attributes:
activity, expired
activity
-
The Activity this Actor was created in.
Raises a ba.ActivityNotFoundError if the Activity no longer exists.
expired
-
bool
Whether the Actor is expired.
(see ba.Actor.on_expire())
Methods:
<constructor>, autoretain(), exists(), getactivity(), handlemessage(), is_alive(), on_expire()
<constructor>
-
ba.Actor()
Instantiates an Actor in the current ba.Activity.
autoretain()
-
autoretain(self: T) -> T
Keep this Actor alive without needing to hold a reference to it.
This keeps the ba.Actor in existence by storing a reference to it with the ba.Activity it was created in. The reference is lazily released once ba.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 ba.Actor from dying. For convenience, this method returns the ba.Actor it is called with, enabling chained statements such as: myflag = ba.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 ba.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 ba.Actor.autoretain()
The default implementation of this method always return 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[ba.Activity]
Return the ba.Activity this Actor is associated with.
If the Activity no longer exists, raises a ba.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.
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.
on_expire()
-
on_expire(self) -> None
Called for remaining ba.Actors when their ba.Activity shuts down.
Actors can use this opportunity to clear callbacks or other references which have the potential of keeping the ba.Activity alive inadvertently (Activities can not exit cleanly while any Python references to them remain.)
Once an actor is expired (see ba.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.
ba.ActorNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Actor does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.App
<top level class>
A class for high level app functionality and state.
Category: App Classes
Use ba.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:
api_version, build_number, config, config_file_path, debug_build, interface_type, language, locale, on_tv, platform, python_directory_app, python_directory_app_site, python_directory_user, subplatform, test_build, ui_bounds, user_agent_string, version, vr_mode
api_version
-
int
The game's api version.
Only python modules and packages associated with the current api version will be detected by the game (see the ba_meta tag). This value will change whenever backward-incompatible changes are introduced to game apis; when that happens, scripts should be updated accordingly and set to target the new api.
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 ba.App.version string.
config
-
The ba.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 ba.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 ba.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'.
python_directory_app
-
str
Path where the app looks for its bundled scripts.
python_directory_app_site
-
str
Path containing pip packages bundled with the app.
python_directory_user
-
str
Path where the app looks for custom user scripts.
subplatform
-
str
String for subplatform.
Can be empty. For the 'android' platform, subplatform may be 'google', 'amazon', etc.
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.
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 'ba.App.build_number'.
vr_mode
-
bool
Bool value for if the game is running in VR.
Methods:
handle_deep_link(), launch_coop_game(), on_app_pause(), on_app_resume(), pause(), resume(), return_to_main_menu_session_gracefully()
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 local co-op session.
on_app_pause()
-
on_app_pause(self) -> None
Called when the app goes to a suspended state.
on_app_resume()
-
on_app_resume(self) -> None
Run when the app resumes from a suspended state.
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.
ba.AppConfig
Inherits from: dict
A special dict that holds the game's persistent configuration values.
Category: App 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 ba.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 ba.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 ba.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 ba.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 ba.App to access actual live state.
Raises an Exception for unrecognized key names. To get the list of keys supported by this method, use ba.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.
ba.AppDelegate
<top level class>
Defines handlers for high level app functionality.
Category: App Classes
Methods:
create_default_game_settings_ui()
-
create_default_game_settings_ui(self, gameclass: Type[ba.GameActivity], sessiontype: Type[ba.Session], settings: Optional[dict], completion_call: CallableOptional[dict, None]) -> None
Launch a UI to configure the given game config.
It should manipulate the contents of config and call completion_call when done.
ba.AssetPackage
Inherits from: ba.DependencyComponent
ba.DependencyComponent representing a bundled package of game assets.
Category: Asset Classes
Methods Inherited:
get_dynamic_deps()
Methods Defined or Overridden:
<constructor>, dep_is_present(), getcollidemodel(), getdata(), getmodel(), getsound(), gettexture()
<constructor>
-
ba.AssetPackage()
Instantiate a DependencyComponent.
dep_is_present()
-
<class method>
dep_is_present(config: Any = None) -> bool
Return whether this component/config is present on this device.
getcollidemodel()
-
getcollidemodel(self, name: str) -> ba.CollideModel
Load a named ba.CollideModel from the AssetPackage.
Behavior is similar to ba.getcollideModel()
getdata()
-
getdata(self, name: str) -> ba.Data
Load a named ba.Data from the AssetPackage.
Behavior is similar to ba.getdata()
getmodel()
-
getmodel(self, name: str) -> ba.Model
Load a named ba.Model from the AssetPackage.
Behavior is similar to ba.getmodel()
getsound()
-
getsound(self, name: str) -> ba.Sound
Load a named ba.Sound from the AssetPackage.
Behavior is similar to ba.getsound()
gettexture()
-
gettexture(self, name: str) -> ba.Texture
Load a named ba.Texture from the AssetPackage.
Behavior is similar to ba.gettexture()
ba.BoolSetting
Inherits from: ba.Setting
A boolean game setting.
Category: Settings Classes
Methods:
<constructor>
-
ba.BoolSetting(name: str, default: bool)
ba.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 ba.WeakCall if you want to pass a method to callback without keeping its object alive.
Methods:
<constructor>
-
ba.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 = ba.Call(myobj.dostuff, argval1, namedarg=argval2)# Now we have a single callable to run that whole mess. # ..the same as calling myobj.dostuff(argval1, namedarg=argval2) mycall()
ba.Campaign
<top level class>
Represents a unique set or series of ba.Levels.
Category: App Classes
Attributes:
configdict, levels, name, sequential
configdict
-
Dict[str, Any]
Return the live config dict for this campaign.
levels
-
List[ba.Level]
The list of ba.Levels in the Campaign.
name
-
str
The name of the Campaign.
sequential
-
bool
Whether this Campaign's levels must be played in sequence.
Methods:
<constructor>, addlevel(), get_selected_level(), getlevel(), reset(), set_selected_level()
<constructor>
-
ba.Campaign(name: str, sequential: bool = True)
addlevel()
-
addlevel(self, level: ba.Level) -> None
Adds a ba.Level to the Campaign.
get_selected_level()
-
get_selected_level(self) -> str
Return the name of the Level currently selected in the UI.
getlevel()
-
getlevel(self, name: str) -> ba.Level
Return a contained ba.Level by name.
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).
ba.CelebrateMessage
<top level class>
Tells an object to celebrate.
Category: Message Classes
Attributes:
duration
-
float
Amount of time to celebrate in seconds.
Methods:
<constructor>
-
ba.CelebrateMessage(duration: float = 10.0)
ba.ChoiceSetting
Inherits from: ba.Setting
A setting with multiple choices.
Category: Settings Classes
Methods:
<constructor>
-
ba.ChoiceSetting(name: str, default: Any, choices: List[Tuple[str, Any]])
ba.Chooser
<top level class>
A character/team selector for a ba.Player.
Category: Gameplay Classes
Attributes:
lobby, ready, sessionplayer, sessionteam
lobby
-
The chooser's ba.Lobby.
ready
-
bool
Whether this chooser is checked in as ready.
sessionplayer
-
The ba.SessionPlayer associated with this chooser.
sessionteam
-
Return this chooser's currently selected ba.SessionTeam.
Methods:
<constructor>, get_character_name(), get_color(), get_highlight(), get_lobby(), getplayer(), handlemessage(), reload_profiles(), update_from_profile(), update_position()
<constructor>
-
ba.Chooser(vpos: float, sessionplayer: _ba.SessionPlayer, 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[ba.Lobby]
Return this chooser's lobby if it still exists; otherwise None.
getplayer()
-
getplayer(self) -> ba.SessionPlayer
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_profile()
-
update_from_profile(self) -> None
Set character/colors based on the current profile.
update_position()
-
update_position(self) -> None
Update this chooser's position.
ba.CollideModel
<top level class>
A reference to a collide-model.
Category: Asset Classes
Use ba.getcollidemodel() to instantiate one.
ba.Collision
<top level class>
A class providing info about occurring collisions.
Attributes:
opposingbody, opposingnode, position, sourcenode
opposingbody
-
int
The body index on the opposing node in the current collision.
opposingnode
-
The node the current callback material node is hitting.
Throws a ba.NodeNotFoundError if the node does not exist. This can be expected in some cases such as in 'disconnect' callbacks triggered by deleting a currently-colliding node.
position
-
The position of the current collision.
sourcenode
-
The node containing the material triggering the current callback.
Throws a ba.NodeNotFoundError if the node does not exist, though the node should always exist (at least at the start of the collision callback).
ba.Context
<top level class>
Context(source: Any)
A game context state.
Category: General Utility Classes
Many operations such as ba.newnode() or ba.gettexture() operate implicitly on the current context. Each ba.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 ba.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 ba.Activity instance: Gives the context for the provided ba.Activity. Most all code run during a game happens in an Activity's Context.
a ba.Session instance: Gives the context for the provided ba.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 ba.Context('ui'): tex1 = ba.gettexture('foo_tex_1') tex2 = ba.gettexture('foo_tex_2')
ba.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 ba.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 Ballistica 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 ba.WeakCall for similar functionality, but ContextCall has the added bonus that it will not run during context shutdown, whereas ba.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=ba.ContextCall(self.mycallback))
ba.ContextError
Inherits from: Exception, BaseException
Exception raised when a call is made in an invalid context.
Category: Exception Classes
Examples of this include calling UI functions within an Activity context or calling scene manipulation functions outside of a game context.
Methods:
<all methods inherited from builtins.Exception>
ba.CoopGameActivity
Inherits from: ba.GameActivity, ba.Activity, ba.DependencyComponent, typing.Generic
Base class for cooperative-mode games.
Category: Gameplay Classes
Attributes Inherited:
players, settings_raw, teams
Attributes Defined Here:
customdata, expired, globalsnode, map, playertype, session, stats, teamtype
customdata
-
dict
Entities needing to store simple data with an activity can put it here. This dict will be deleted when the activity expires, so contained objects generally do not need to worry about handling expired activities.
expired
-
bool
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'.
globalsnode
-
The 'globals' ba.Node for the activity. This contains various global controls and values.
map
-
The map being used for this game.
Raises a ba.NotFoundError if the map does not currently exist.
playertype
-
Type[PlayerType]
The type of ba.Player this Activity is using.
session
-
The ba.Session this ba.Activity belongs go.
Raises a ba.SessionNotFoundError if the Session no longer exists.
stats
-
The stats instance accessible while the activity is running.
If access is attempted before or after, raises a ba.NotFoundError.
teamtype
-
Type[TeamType]
The type of ba.Team this Activity is using.
Methods Inherited:
add_actor_weak_ref(), add_player(), add_team(), begin(), continue_or_end_game(), create_player(), create_settings_ui(), create_team(), dep_is_present(), end(), end_game(), expire(), get_available_settings(), get_description(), get_description_display_string(), get_display_string(), get_dynamic_deps(), get_instance_description(), get_instance_description_short(), get_instance_display_string(), get_instance_scoreboard_display_string(), get_settings_display_string(), get_supported_maps(), get_team_display_string(), getname(), getscoreconfig(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), 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(), remove_player(), remove_team(), respawn_player(), retain_actor(), set_has_ended(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), transition_in(), transition_out()
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>
-
ba.CoopGameActivity(settings: dict)
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 ba.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: PlayerType, 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[ba.Session]) -> bool
Return whether this game supports the provided Session type.
ba.CoopSession
Inherits from: ba.Session
A ba.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:
allow_mid_activity_joins, customdata, lobby, max_players, min_players, players, teams, use_team_colors, use_teams
Attributes Defined Here:
campaign, sessionglobalsnode
campaign
-
Optional[ba.Campaign]
The ba.Campaign instance this Session represents, or None if there is no associated Campaign.
sessionglobalsnode
-
The sessionglobals ba.Node for the session.
Methods Inherited:
begin_next_activity(), end(), end_activity(), getactivity(), handlemessage(), on_player_request(), on_team_join(), on_team_leave(), setactivity(), transitioning_out_activity_was_freed()
Methods Defined or Overridden:
<constructor>, get_current_game_instance(), get_custom_menu_entries(), on_activity_end(), on_player_leave(), restart()
<constructor>
-
ba.CoopSession()
Instantiate a co-op mode session.
get_current_game_instance()
-
get_current_game_instance(self) -> ba.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: ba.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, sessionplayer: ba.SessionPlayer) -> None
Called when a previously-accepted ba.SessionPlayer leaves.
restart()
-
restart(self) -> None
Restart the current game activity.
ba.Data
<top level class>
A reference to a data object.
Category: Asset Classes
Use ba.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.
ba.DeathType
Inherits from: enum.Enum
A reason for a death.
Category: Enums
Values:
- GENERIC
- OUT_OF_BOUNDS
- IMPACT
- FALL
- REACHED_GOAL
- LEFT_GAME
ba.DelegateNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected delegate object does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.Dependency
Inherits from: typing.Generic
A dependency on a DependencyComponent (with an optional config).
Category: Dependency Classes
This class is used to request and access functionality provided by other DependencyComponent classes from a DependencyComponent 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 = ba.Dependency(FloofClass)' you would then be able to instantiate a FloofClass in your class's methods via self.floofcls().
Methods:
<constructor>, get_hash()
<constructor>
-
ba.Dependency(cls: Type[T], config: Any = None)
Instantiate a Dependency given a ba.DependencyComponent type.
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.
ba.DependencyComponent
<top level class>
Base class for all classes that can act as or use dependencies.
Category: Dependency Classes
Methods:
<constructor>, dep_is_present(), get_dynamic_deps()
<constructor>
-
ba.DependencyComponent()
Instantiate a DependencyComponent.
dep_is_present()
-
<class method>
dep_is_present(config: Any = None) -> bool
Return whether this component/config is present on this device.
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)
ba.DependencyError
Inherits from: Exception, BaseException
Exception raised when one or more ba.Dependency items are missing.
Category: Exception Classes
(this will generally be missing assets).
Attributes:
deps
-
List[ba.Dependency]
The list of missing dependencies causing this error.
Methods Inherited:
with_traceback()
Methods Defined or Overridden:
<constructor>
-
ba.DependencyError(deps: List[ba.Dependency])
ba.DependencySet
Inherits from: typing.Generic
Set of resolved dependencies and their associated data.
Category: Dependency Classes
To use DependencyComponents, a set must be created, resolved, and then loaded. The DependencyComponents are only valid while the set remains in existence.
Attributes:
resolved, root
resolved
-
bool
Whether this set has been successfully resolved.
root
-
T
The instantiated root DependencyComponent instance for the set.
Methods:
<constructor>, get_asset_package_ids(), load(), resolve()
<constructor>
-
ba.DependencySet(root_dependency: Dependency[T])
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) -> None
Instantiate all DependencyComponents in the set.
Returns a wrapper which can be used to instantiate the root dep.
resolve()
-
resolve(self) -> None
Resolve the complete set of required dependencies for this set.
Raises a ba.DependencyError if dependencies are missing (or other Exception types on other errors).
ba.DieMessage
<top level class>
A message telling an object to die.
Category: Message Classes
Most ba.Actors respond to this.
Attributes:
how, immediate
how
-
DeathType
The particular reason for death.
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>
-
ba.DieMessage(immediate: bool = False, how: DeathType = <DeathType.GENERIC: generic>)
ba.DropMessage
<top level class>
Tells an object that it has dropped what it was holding.
Category: Message Classes
Methods:
<constructor>
-
ba.DropMessage()
ba.DroppedMessage
<top level class>
Tells an object that it has been dropped.
Category: Message Classes
Attributes:
Methods:
<constructor>
-
ba.DroppedMessage(node: ba.Node)
ba.DualTeamSession
Inherits from: ba.MultiTeamSession, ba.Session
ba.Session type for teams mode games.
Category: Gameplay Classes
Attributes Inherited:
allow_mid_activity_joins, customdata, lobby, max_players, min_players, players, teams, use_team_colors, use_teams
Attributes Defined Here:
sessionglobalsnode
-
The sessionglobals ba.Node for the session.
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(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity(), transitioning_out_activity_was_freed()
Methods Defined or Overridden:
<constructor>
-
ba.DualTeamSession()
Set up playlists and launches a ba.Activity to accept joiners.
ba.EmptyPlayer
Inherits from: ba.Player, typing.Generic
An empty player for use by Activities that don't need to define one.
Category: Gameplay Classes
ba.Player and ba.Team are 'Generic' types, and so passing them as type arguments when defining a ba.Activity reduces type safety. For example, activity.teams[0].player will have type 'Any' in that case. For that reason, it is better to pass EmptyPlayer and EmptyTeam when defining a ba.Activity that does not need custom types of its own.
Note that EmptyPlayer defines its team type as EmptyTeam and vice versa, so if you want to define your own class for one of them you must do so for both.
Attributes Inherited:
actor
Attributes Defined Here:
customdata, node, position, sessionplayer, team
customdata
-
dict
Arbitrary values associated with the player. Though it is encouraged that most player values be properly defined on the ba.Player subclass, it may be useful for player-agnostic objects to store values here. This dict is cleared when the player leaves or expires so objects stored here will be disposed of at the expected time, unlike the Player instance itself which may continue to be referenced after it is no longer part of the game.
node
-
A ba.Node of type 'player' associated with this Player.
This node can be used to get a generic player position/etc.
position
-
The position of the player, as defined by its current ba.Actor.
If the player currently has no actor, raises a ba.ActorNotFoundError.
sessionplayer
-
Return the ba.SessionPlayer corresponding to this Player.
Throws a ba.SessionPlayerNotFoundError if it does not exist.
team
-
TeamType
The ba.Team for this player.
Methods:
<all methods inherited from ba.Player>
ba.EmptyTeam
Inherits from: ba.Team, typing.Generic
An empty player for use by Activities that don't need to define one.
Category: Gameplay Classes
ba.Player and ba.Team are 'Generic' types, and so passing them as type arguments when defining a ba.Activity reduces type safety. For example, activity.teams[0].player will have type 'Any' in that case. For that reason, it is better to pass EmptyPlayer and EmptyTeam when defining a ba.Activity that does not need custom types of its own.
Note that EmptyPlayer defines its team type as EmptyTeam and vice versa, so if you want to define your own class for one of them you must do so for both.
Attributes:
customdata, sessionteam
customdata
-
dict
Arbitrary values associated with the team. Though it is encouraged that most player values be properly defined on the ba.Team subclass, it may be useful for player-agnostic objects to store values here. This dict is cleared when the team leaves or expires so objects stored here will be disposed of at the expected time, unlike the Team instance itself which may continue to be referenced after it is no longer part of the game.
sessionteam
-
SessionTeam
Return the ba.SessionTeam corresponding to this Team.
Throws a ba.SessionTeamNotFoundError if there is none.
Methods:
<all methods inherited from ba.Team>
ba.Existable
Inherits from: typing_extensions.Protocol
A Protocol for objects supporting an exists() method.
Category: Protocols
Methods:
exists()
-
exists(self) -> bool
Whether this object exists.
ba.FloatChoiceSetting
Inherits from: ba.ChoiceSetting, ba.Setting
A float setting with multiple choices.
Category: Settings Classes
Methods:
<constructor>
-
ba.FloatChoiceSetting(name: str, default: float, choices: List[Tuple[str, float]])
ba.FloatSetting
Inherits from: ba.Setting
A floating point game setting.
Category: Settings Classes
Methods:
<constructor>
-
ba.FloatSetting(name: str, default: float, min_value: float = 0.0, max_value: float = 9999.0, increment: float = 1.0)
ba.FreeForAllSession
Inherits from: ba.MultiTeamSession, ba.Session
ba.Session type for free-for-all mode games.
Category: Gameplay Classes
Attributes Inherited:
allow_mid_activity_joins, customdata, lobby, max_players, min_players, players, teams, use_team_colors, use_teams
Attributes Defined Here:
sessionglobalsnode
-
The sessionglobals ba.Node for the session.
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(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity(), transitioning_out_activity_was_freed()
Methods Defined or Overridden:
<constructor>, get_ffa_point_awards()
<constructor>
-
ba.FreeForAllSession()
Set up playlists and launches a ba.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.
ba.FreezeMessage
<top level class>
Tells an object to become frozen.
Category: Message Classes
As seen in the effects of an ice ba.Bomb.
Methods:
<constructor>
-
ba.FreezeMessage()
ba.GameActivity
Inherits from: ba.Activity, ba.DependencyComponent, typing.Generic
Common base class for all game ba.Activities.
Category: Gameplay Classes
Attributes Inherited:
players, settings_raw, teams
Attributes Defined Here:
customdata, expired, globalsnode, map, playertype, session, stats, teamtype
customdata
-
dict
Entities needing to store simple data with an activity can put it here. This dict will be deleted when the activity expires, so contained objects generally do not need to worry about handling expired activities.
expired
-
bool
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'.
globalsnode
-
The 'globals' ba.Node for the activity. This contains various global controls and values.
map
-
The map being used for this game.
Raises a ba.NotFoundError if the map does not currently exist.
playertype
-
Type[PlayerType]
The type of ba.Player this Activity is using.
session
-
The ba.Session this ba.Activity belongs go.
Raises a ba.SessionNotFoundError if the Session no longer exists.
stats
-
The stats instance accessible while the activity is running.
If access is attempted before or after, raises a ba.NotFoundError.
teamtype
-
Type[TeamType]
The type of ba.Team this Activity is using.
Methods Inherited:
add_actor_weak_ref(), add_player(), add_team(), begin(), create_player(), create_team(), dep_is_present(), expire(), get_dynamic_deps(), has_begun(), has_ended(), has_transitioned_in(), is_transitioning_out(), on_expire(), on_player_leave(), on_team_join(), on_team_leave(), on_transition_out(), remove_player(), remove_team(), retain_actor(), set_has_ended(), transition_in(), transition_out()
Methods Defined or Overridden:
<constructor>, continue_or_end_game(), create_settings_ui(), end(), end_game(), get_available_settings(), get_description(), get_description_display_string(), get_display_string(), get_instance_description(), get_instance_description_short(), get_instance_display_string(), get_instance_scoreboard_display_string(), get_settings_display_string(), get_supported_maps(), get_team_display_string(), getname(), getscoreconfig(), handlemessage(), is_waiting_for_continue(), on_begin(), on_continue(), on_player_join(), on_transition_in(), respawn_player(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), spawn_player_spaz(), supports_session_type()
<constructor>
-
ba.GameActivity(settings: dict)
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_settings_ui()
-
<class method>
create_settings_ui(sessiontype: Type[ba.Session], settings: Optional[dict], completion_call: CallableOptional[dict, None]) -> None
Launch an in-game UI to configure settings for a game type.
'sessiontype' should be the ba.Session class the game will be used in.
'settings' should be an existing settings dict (implies 'edit' ui mode) or None (implies 'add' ui mode).
'completion_call' will be called with a filled-out settings dict on success or None on cancel.
Generally subclasses don't need to override this; if they override ba.GameActivity.get_available_settings() and ba.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 ba.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
Tell the game to wrap up and call ba.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 (ba.GameActivity.setup_standard_time_limit()) will work with the game.
get_available_settings()
-
<class method>
get_available_settings(sessiontype: Type[ba.Session]) -> List[ba.Setting]
Return a list of settings relevant to this game type when running under the provided session type.
get_description()
-
<class method>
get_description(sessiontype: Type[ba.Session]) -> str
Get a str description of this game type.
The default implementation simply returns the 'description' class var. Classes which want to change their description depending on the session can override this method.
get_description_display_string()
-
<class method>
get_description_display_string(sessiontype: Type[ba.Session]) -> ba.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) -> ba.Lstr
Return a descriptive name for this game/settings combo.
Subclasses should override getname(); 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_description_short().
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_raw['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_description_short()
-
get_instance_description_short(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_raw['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) -> ba.Lstr
Return a name for this particular game instance.
get_instance_scoreboard_display_string()
-
get_instance_scoreboard_display_string(self) -> ba.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_settings_display_string()
-
<class method>
get_settings_display_string(config: Dict[str, Any]) -> ba.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_supported_maps()
-
<class method>
get_supported_maps(sessiontype: Type[ba.Session]) -> List[str]
Called by the default ba.GameActivity.create_settings_ui() implementation; should return a list of map names valid for this game-type for the given ba.Session type.
get_team_display_string()
-
<class method>
get_team_display_string(name: str) -> ba.Lstr
Given a team name, returns a localized version of it.
getname()
-
<class method>
getname() -> str
Return a str name for this game type.
This default implementation simply returns the 'name' class attr.
getscoreconfig()
-
<class method>
getscoreconfig() -> ba.ScoreConfig
Return info about game scoring setup; can be overridden by games.
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 ba.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: PlayerType) -> None
Called when a new ba.Player has joined the Activity.
(including the initial set of Players)
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 players or teams, however. They remain owned by the previous Activity up until ba.Activity.on_begin() is called.
respawn_player()
-
respawn_player(self, player: PlayerType, respawn_time: Optional[float] = None) -> None
Given a ba.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_zoom_message()
-
show_zoom_message(self, message: ba.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: PlayerType) -> ba.Actor
Spawn *something* for the provided ba.Player.
The default implementation simply calls spawn_player_spaz().
spawn_player_if_exists()
-
spawn_player_if_exists(self, player: PlayerType) -> None
A utility method which calls self.spawn_player() *only* if the ba.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: PlayerType, position: Sequence[float] = (0, 0, 0), angle: float = None) -> PlayerSpaz
Create and wire up a ba.PlayerSpaz for the provided ba.Player.
supports_session_type()
-
<class method>
supports_session_type(sessiontype: Type[ba.Session]) -> bool
Return whether this game supports the provided Session type.
ba.GameResults
<top level class>
Results for a completed game.
Category: Gameplay Classes
Upon completion, a game should fill one of these out and pass it to its ba.Activity.end() call.
Attributes:
lower_is_better, playerinfos, score_label, scoretype, sessionteams, winnergroups, winning_sessionteam
lower_is_better
-
bool
Whether lower scores are better.
playerinfos
-
List[ba.PlayerInfo]
Get info about the players represented by the results.
score_label
-
str
The label associated with scores ('points', etc).
scoretype
-
The type of score.
sessionteams
-
List[ba.SessionTeam]
Return all ba.SessionTeams in the results.
winnergroups
-
List[WinnerGroup]
Get an ordered list of winner groups.
winning_sessionteam
-
Optional[ba.SessionTeam]
The winning ba.SessionTeam if there is exactly one, or else None.
Methods:
<constructor>, get_sessionteam_score(), get_sessionteam_score_str(), has_score_for_sessionteam(), set_game(), set_team_score()
<constructor>
-
ba.GameResults()
get_sessionteam_score()
-
get_sessionteam_score(self, sessionteam: ba.SessionTeam) -> Optional[int]
Return the score for a given ba.SessionTeam.
get_sessionteam_score_str()
-
get_sessionteam_score_str(self, sessionteam: ba.SessionTeam) -> ba.Lstr
Return the score for the given session-team as an Lstr.
(properly formatted for the score type.)
has_score_for_sessionteam()
-
has_score_for_sessionteam(self, sessionteam: ba.SessionTeam) -> bool
Return whether there is a score for a given session-team.
set_game()
-
set_game(self, game: ba.GameActivity) -> None
Set the game instance these results are applying to.
set_team_score()
-
set_team_score(self, team: ba.Team, score: Optional[int]) -> None
Set the score for a given team.
This can be a number or None. (see the none_is_winner arg in the constructor)
ba.GameTip
<top level class>
Defines a tip presentable to the user at the start of a game.
Category: Gameplay Classes
Methods:
<constructor>
-
ba.GameTip(text: str, icon: Optional[ba.Texture] = None, sound: Optional[ba.Sound] = None)
ba.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>, get_source_player()
<constructor>
-
ba.HitMessage(srcnode: 'ba.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: 'ba.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.
get_source_player()
-
get_source_player(self, playertype: Type[PlayerType]) -> Optional[PlayerType]
Return the source-player if one exists and is the provided type.
ba.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>
-
ba.ImpactDamageMessage(intensity: float)
ba.InputDevice
<top level class>
An input-device such as a gamepad, touchscreen, or keyboard.
Category: Gameplay Classes
Attributes:
allows_configuring, client_id, 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.
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.
is_remote_client
-
bool
Whether this input-device represents a remotely-connected client.
name
-
str
The name of the device.
player
-
Optional[ba.SessionPlayer]
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:
exists(), get_account_name(), get_axis_name(), get_button_name()
exists()
-
exists() -> bool
Return whether the underlying device for this object is still present.
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.
ba.InputDeviceNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.InputDevice does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.InputType
Inherits from: enum.Enum
Types of input a controller can send to the game.
Category: Enums
Values:
- UP_DOWN
- LEFT_RIGHT
- JUMP_PRESS
- JUMP_RELEASE
- PUNCH_PRESS
- PUNCH_RELEASE
- BOMB_PRESS
- BOMB_RELEASE
- PICK_UP_PRESS
- PICK_UP_RELEASE
- RUN
- FLY_PRESS
- FLY_RELEASE
- START_PRESS
- START_RELEASE
- HOLD_POSITION_PRESS
- HOLD_POSITION_RELEASE
- LEFT_PRESS
- LEFT_RELEASE
- RIGHT_PRESS
- RIGHT_RELEASE
- UP_PRESS
- UP_RELEASE
- DOWN_PRESS
- DOWN_RELEASE
ba.IntChoiceSetting
Inherits from: ba.ChoiceSetting, ba.Setting
An int setting with multiple choices.
Category: Settings Classes
Methods:
<constructor>
-
ba.IntChoiceSetting(name: str, default: int, choices: List[Tuple[str, int]])
ba.IntSetting
Inherits from: ba.Setting
An integer game setting.
Category: Settings Classes
Methods:
<constructor>
-
ba.IntSetting(name: str, default: int, min_value: int = 0, max_value: int = 9999, increment: int = 1)
ba.Level
<top level class>
An entry in a ba.Campaign consisting of a name, game type, and settings.
Category: Gameplay Classes
Attributes:
campaign, complete, displayname, gametype, index, name, preview_texture_name, rating
campaign
-
Optional[ba.Campaign]
The ba.Campaign this Level is associated with, or None.
complete
-
bool
Whether this Level has been completed.
displayname
-
The localized name for this Level.
gametype
-
Type[ba.GameActivity]
The type of game used for this Level.
index
-
int
The zero-based index of this Level in its ba.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_high_scores(), get_preview_texture(), get_score_version_string(), get_settings(), set_complete(), set_high_scores(), set_rating()
<constructor>
-
ba.Level(name: str, gametype: Type[ba.GameActivity], settings: dict, preview_texture_name: str, displayname: str = None)
get_high_scores()
-
get_high_scores(self) -> dict
Return the current high scores for this Level.
get_preview_texture()
-
get_preview_texture(self) -> ba.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.
ba.Lobby
<top level class>
Container for ba.Choosers.
Category: Gameplay Classes
Attributes:
sessionteams, use_team_colors
sessionteams
-
List[ba.SessionTeam]
ba.SessionTeams 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>
-
ba.Lobby()
add_chooser()
-
add_chooser(self, sessionplayer: ba.SessionPlayer) -> 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: ba.SessionPlayer) -> None
Remove a single player's chooser; does not kick them.
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.
ba.Lstr
<top level class>
Used to define 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 = ba.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 = ba.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 = ba.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 = ba.Lstr(resource='res_a', subs=[('${NAME}', ba.Lstr(resource='res_b'))])
Methods:
<constructor>, evaluate(), is_flat_value()
<constructor>
-
ba.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.
ba.Map
Inherits from: ba.Actor
A game map.
Category: Gameplay Classes
Consists of a collection of terrain nodes, metadata, and other functionality comprising a game map.
Attributes:
activity, expired
activity
-
The Activity this Actor was created in.
Raises a ba.ActivityNotFoundError if the Activity no longer exists.
expired
-
bool
Whether the Actor is expired.
(see ba.Actor.on_expire())
Methods Inherited:
autoretain(), getactivity(), is_alive(), on_expire()
Methods Defined or Overridden:
<constructor>, exists(), get_def_bound_box(), get_def_point(), get_def_points(), get_ffa_start_position(), get_flag_position(), get_music_type(), get_play_types(), get_preview_texture_name(), get_start_position(), getname(), handlemessage(), is_point_near_edge(), on_preload(), preload()
<constructor>
-
ba.Map(vr_overlay_offset: Optional[Sequence[float]] = None)
Instantiate a map.
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 ba.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 ba.Actor.autoretain()
The default implementation of this method always return 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.
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[ba.Player]) -> Sequence[float]
Return a random starting position in one of the FFA spawn areas.
If a list of ba.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[ba.MusicType]
Return a music-type string that should be played on this map.
If None is returned, default music will be used.
get_play_types()
-
<class method>
get_play_types() -> 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.
getname()
-
<class method>
getname() -> str
Return the unique name of this map, in English.
handlemessage()
-
handlemessage(self, msg: Any) -> Any
General message handling; can be passed any message object.
is_point_near_edge()
-
is_point_near_edge(self, point: ba.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 ba.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
ba.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 ba.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 ba.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 ba.Material?
('they_dont_have_material', material) - does the part we're hitting not have a given ba.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 ba.Node as us?
('they_are_different_node_than_us') - does the part we're hitting belong to a different ba.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 each other 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 ba.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 ba.Sound, a target-impulse, and a volume.
('skid_sound', sound, targetImpulse, volume) - plays a sound during a collision when parts are 'scraping' against each other. Provide a ba.Sound, a target-impulse, and a volume.
('roll_sound', sound, targetImpulse, volume) - plays a sound during a collision when parts are 'rolling' against each other. Provide a ba.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 = ba.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 ba.Actor to drop dead: m = ba.Material() m.add_actions(actions=(('modify_part_collision', 'physical', False), ('message', 'their_node', 'at_connect', ba.DieMessage())))
# example 3: play some sounds when we're contacting the ground: m = ba.Material() m.add_actions(conditions=('they_have_material', shared.footing_material), actions=(('impact_sound', ba.getsound('metalHit'), 2, 5), ('skid_sound', ba.getsound('metalSkid'), 2, 5)))
ba.Model
<top level class>
A reference to a model.
Category: Asset Classes
Models are used for drawing. Use ba.getmodel() to instantiate one.
ba.MultiTeamSession
Inherits from: ba.Session
Common base class for ba.DualTeamSession and ba.FreeForAllSession.
Category: Gameplay Classes
Free-for-all-mode is essentially just teams-mode with each ba.Player having their own ba.Team, so there is much overlap in functionality.
Attributes Inherited:
allow_mid_activity_joins, customdata, lobby, max_players, min_players, players, teams, use_team_colors, use_teams
Attributes Defined Here:
sessionglobalsnode
-
The sessionglobals ba.Node for the session.
Methods Inherited:
begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), getactivity(), handlemessage(), on_player_leave(), on_player_request(), on_team_leave(), setactivity(), transitioning_out_activity_was_freed()
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>
-
ba.MultiTeamSession()
Set up playlists and launches a ba.Activity to accept joiners.
announce_game_results()
-
announce_game_results(self, activity: ba.GameActivity, results: ba.GameResults, 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 ba.Players allowed to join the game at once.
get_next_game_description()
-
get_next_game_description(self) -> ba.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: ba.Activity, results: Any) -> None
Called when the current ba.Activity has ended.
The ba.Session should look at the results and start another ba.Activity.
on_team_join()
-
on_team_join(self, team: ba.SessionTeam) -> None
Called when a new ba.Team joins the session.
ba.MusicPlayer
<top level class>
Wrangles soundtrack music playback.
Category: App Classes
Music can be played either through the game itself or via a platform-specific external player.
Methods:
<constructor>, on_app_shutdown(), on_play(), on_select_entry(), on_set_volume(), on_stop(), play(), select_entry(), set_volume(), shutdown(), stop()
<constructor>
-
ba.MusicPlayer()
on_app_shutdown()
-
on_app_shutdown(self) -> None
Called on final app shutdown.
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_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.
ba.MusicPlayMode
Inherits from: enum.Enum
Influences behavior when playing music.
Category: Enums
Values:
- REGULAR
- TEST
ba.MusicType
Inherits from: enum.Enum
Types of music available to play in-game.
Category: Enums
These do not correspond to specific pieces of music, but rather to 'situations'. The actual music played for each type can be overridden by the game or by the user.
Values:
- MENU
- VICTORY
- CHAR_SELECT
- RUN_AWAY
- ONSLAUGHT
- KEEP_AWAY
- RACE
- EPIC_RACE
- SCORES
- GRAND_ROMP
- TO_THE_DEATH
- CHOSEN_ONE
- FORWARD_MARCH
- FLAG_CATCHER
- SURVIVAL
- EPIC
- SPORTS
- HOCKEY
- FOOTBALL
- FLYING
- SCARY
- MARCHING
ba.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 ba.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 ba.newnode(), and to explicitly delete one, use ba.Node.delete(). ba.Node.exists() can be used to determine if a Node still points to a live node in the game.
You can use ba.Node(None) to instantiate an invalid Node reference (sometimes used as attr values/etc).
Methods:
add_death_action(), connectattr(), delete(), exists(), getdelegate(), getname(), getnodetype(), handlemessage()
add_death_action()
-
add_death_action(action: 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 = ba.newnode('light') loc = ba.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 if ignore_missing is True; otherwise a ba.NodeNotFoundError 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.
getdelegate()
-
getdelegate(type: Type, doraise: bool = False) -> <varies>
Return the node's current delegate object if it matches a certain type.
If the node has no delegate or it is not an instance of the passed type, then None will be returned. If 'doraise' is True, then an ba.DelegateNotFoundError will be raised instead.
getname()
-
getname() -> str
Return the name assigned to a Node; used mainly for debugging
getnodetype()
-
getnodetype() -> str
Return the type of Node referenced by this object as a string. (Note this is different from the Python type which is always ba.Node)
handlemessage()
-
handlemessage(*args: Any) -> None
General message handling; can be passed any message object.
All standard message objects are forwarded along to the ba.Node's delegate for handling (generally the ba.Actor that made the node).
ba.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.
ba.NodeActor
Inherits from: ba.Actor
A simple ba.Actor type that wraps a single ba.Node.
Category: Gameplay Classes
This Actor will delete its Node when told to die, and it's exists() call will return whether the Node still exists or not.
Attributes:
activity, expired
activity
-
The Activity this Actor was created in.
Raises a ba.ActivityNotFoundError if the Activity no longer exists.
expired
-
bool
Whether the Actor is expired.
(see ba.Actor.on_expire())
Methods Inherited:
autoretain(), getactivity(), is_alive(), on_expire()
Methods Defined or Overridden:
<constructor>, exists(), handlemessage()
<constructor>
-
ba.NodeActor(node: ba.Node)
Instantiates an Actor in the current ba.Activity.
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 ba.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 ba.Actor.autoretain()
The default implementation of this method always return 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.
handlemessage()
-
handlemessage(self, msg: Any) -> Any
General message handling; can be passed any message object.
ba.NodeNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Node does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.NotFoundError
Inherits from: Exception, BaseException
Exception raised when a referenced object does not exist.
Category: Exception Classes
Methods:
<all methods inherited from builtins.Exception>
ba.OutOfBoundsMessage
<top level class>
A message telling an object that it is out of bounds.
Category: Message Classes
Methods:
<constructor>
-
ba.OutOfBoundsMessage()
ba.Permission
Inherits from: enum.Enum
Permissions that can be requested from the OS.
Category: Enums
Values:
- STORAGE
ba.PickedUpMessage
<top level class>
Tells an object that it has been picked up by something.
Category: Message Classes
Attributes:
Methods:
<constructor>
-
ba.PickedUpMessage(node: ba.Node)
ba.PickUpMessage
<top level class>
Tells an object that it has picked something up.
Category: Message Classes
Attributes:
Methods:
<constructor>
-
ba.PickUpMessage(node: ba.Node)
ba.Player
Inherits from: typing.Generic
A player in a specific ba.Activity.
Category: Gameplay Classes
These correspond to ba.SessionPlayer objects, but are associated with a single ba.Activity instance. This allows activities to specify their own custom ba.Player types.
Attributes:
actor, customdata, node, position, sessionplayer, team
actor
-
Optional[ba.Actor]
The ba.Actor associated with the player.
customdata
-
dict
Arbitrary values associated with the player. Though it is encouraged that most player values be properly defined on the ba.Player subclass, it may be useful for player-agnostic objects to store values here. This dict is cleared when the player leaves or expires so objects stored here will be disposed of at the expected time, unlike the Player instance itself which may continue to be referenced after it is no longer part of the game.
node
-
A ba.Node of type 'player' associated with this Player.
This node can be used to get a generic player position/etc.
position
-
The position of the player, as defined by its current ba.Actor.
If the player currently has no actor, raises a ba.ActorNotFoundError.
sessionplayer
-
Return the ba.SessionPlayer corresponding to this Player.
Throws a ba.SessionPlayerNotFoundError if it does not exist.
team
-
TeamType
The ba.Team for this player.
Methods:
assigninput(), exists(), get_icon(), getname(), is_alive(), on_expire(), resetinput()
assigninput()
-
assigninput(self, inputtype: Union[ba.InputType, Tuple[ba.InputType, ...]], call: Callable) -> None
assigninput(type: Union[ba.InputType, Tuple[ba.InputType, ...]], call: Callable) -> None
Set the python callable to be run for one or more types of input.
exists()
-
exists(self) -> bool
Whether the underlying player still exists.
This will return False if the underlying ba.SessionPlayer has left the game or if the ba.Activity this player was associated with has ended. 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.
get_icon()
-
get_icon(self) -> Dict[str, Any]
get_icon() -> Dict[str, Any]
Returns the character's icon (images, colors, etc contained in a dict)
getname()
-
getname(self, full: bool = False, icon: bool = True) -> str
getname(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(self) -> bool
is_alive() -> bool
Returns True if the player has a ba.Actor assigned and its is_alive() method return True. False is returned otherwise.
on_expire()
-
on_expire(self) -> None
Can be overridden to handle player expiration.
The player expires when the Activity it is a part of expires. Expired players should no longer run any game logic (which will likely error). They should, however, remove any references to players/teams/games/etc. which could prevent them from being freed.
resetinput()
-
resetinput(self) -> None
resetinput() -> None
Clears out the player's assigned input actions.
ba.PlayerDiedMessage
<top level class>
A message saying a ba.Player has died.
Category: Message Classes
Attributes:
how, killed
how
-
The particular type of death.
killed
-
bool
If True, the player was killed; If False, they left the game or the round ended.
Methods:
<constructor>, getkillerplayer(), getplayer()
<constructor>
-
ba.PlayerDiedMessage(player: ba.Player, was_killed: bool, killerplayer: Optional[ba.Player], how: ba.DeathType)
Instantiate a message with the given values.
getkillerplayer()
-
getkillerplayer(self, playertype: Type[PlayerType]) -> Optional[PlayerType]
Return the ba.Player responsible for the killing, if any.
Pass the Player type being used by the current game.
getplayer()
-
getplayer(self, playertype: Type[PlayerType]) -> PlayerType
Return the ba.Player that died.
The type of player for the current activity should be passed so that the type-checker properly identifies the returned value as one.
ba.PlayerInfo
<top level class>
Holds basic info about a player.
Category: Gameplay Classes
Methods:
<constructor>
-
ba.PlayerInfo(name: str, character: str)
ba.PlayerNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Player does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.PlayerRecord
<top level class>
Stats for an individual player in a ba.Stats object.
Category: Gameplay Classes
This does not necessarily correspond to a ba.Player that is still present (stats may be retained for players that leave mid-game)
Attributes:
player, team
player
-
Return the instance's associated ba.SessionPlayer.
Raises a ba.SessionPlayerNotFoundError if the player no longer exists.
team
-
The ba.SessionTeam the last associated player was last on.
This can still return a valid result even if the player is gone. Raises a ba.SessionTeamNotFoundError if the team no longer exists.
Methods:
<constructor>, associate_with_sessionplayer(), cancel_multi_kill_timer(), get_icon(), get_last_sessionplayer(), getactivity(), getname(), submit_kill()
<constructor>
-
ba.PlayerRecord(name: str, name_full: str, sessionplayer: ba.SessionPlayer, stats: ba.Stats)
associate_with_sessionplayer()
-
associate_with_sessionplayer(self, sessionplayer: ba.SessionPlayer) -> None
Associate this entry with a ba.SessionPlayer.
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_sessionplayer()
-
get_last_sessionplayer(self) -> ba.SessionPlayer
Return the last ba.Player we were associated with.
getactivity()
-
getactivity(self) -> Optional[ba.Activity]
Return the ba.Activity this instance is currently associated with.
Returns None if the activity no longer exists.
getname()
-
getname(self, full: bool = False) -> str
Return the player entry's name.
submit_kill()
-
submit_kill(self, showpoints: bool = True) -> None
Submit a kill for this player entry.
ba.PlayerScoredMessage
<top level class>
Informs something that a ba.Player scored.
Category: Message Classes
Attributes:
score
-
int
The score value.
Methods:
<constructor>
-
ba.PlayerScoredMessage(score: int)
ba.PowerupAcceptMessage
<top level class>
A message informing a ba.Powerup that it was accepted.
Category: Message Classes
This is generally sent in response to a ba.PowerupMessage to inform the box (or whoever granted it) that it can go away.
Methods:
<constructor>
-
ba.PowerupAcceptMessage()
ba.PowerupMessage
<top level class>
A message telling an object to accept a powerup.
Category: Message Classes
This message is normally received by touching a ba.PowerupBox.
Attributes:
poweruptype, sourcenode
poweruptype
-
str
The type of powerup to be granted (a string). See ba.Powerup.poweruptype for available type values.
sourcenode
-
Optional[ba.Node]
The node the powerup game from, or None otherwise. If a powerup is accepted, a ba.PowerupAcceptMessage should be sent back to the sourcenode to inform it of the fact. This will generally cause the powerup box to make a sound and disappear or whatnot.
Methods:
<constructor>
-
ba.PowerupMessage(poweruptype: str, sourcenode: Optional[ba.Node] = None)
ba.ScoreConfig
<top level class>
Settings for how a game handles scores.
Category: Gameplay Classes
Attributes:
label, lower_is_better, none_is_winner, scoretype, version
label
-
str
A label show to the user for scores; 'Score', 'Time Survived', etc.
lower_is_better
-
bool
Whether lower scores are preferable. Higher scores are by default.
none_is_winner
-
bool
Whether a value of None is considered better than other scores. By default it is not.
scoretype
-
How the score value should be displayed.
version
-
str
To change high-score lists used by a game without renaming the game, change this. Defaults to an empty string.
Methods:
<constructor>
-
ba.ScoreConfig(label: 'str' = 'Score', scoretype: 'ba.ScoreType' = <ScoreType.POINTS: 'p'>, lower_is_better: 'bool' = False, none_is_winner: 'bool' = False, version: 'str' = '')
ba.ScoreType
Inherits from: enum.Enum
Type of scores.
Category: Enums
Values:
- SECONDS
- MILLISECONDS
- POINTS
ba.ServerController
<top level class>
Overall controller for the app in server mode.
Category: App Classes
Methods:
<constructor>, handle_transition(), kick(), print_client_list(), shutdown()
<constructor>
-
ba.ServerController(config: ServerConfig)
handle_transition()
-
handle_transition(self) -> bool
Handle transitioning to a new ba.Session or quitting the app.
Will be called once at the end of an activity that is marked as a good 'end-point' (such as a final score screen). Should return True if action will be handled by us; False if the session should just continue on it's merry way.
kick()
-
kick(self, client_id: int, ban_time: Optional[int]) -> None
Kick the provided client id.
ban_time is provided in seconds. If ban_time is None, ban duration will be determined automatically. Pass 0 or a negative number for no ban time.
print_client_list()
-
print_client_list(self) -> None
Print info about all connected clients.
shutdown()
-
shutdown(self, reason: ShutdownReason, immediate: bool) -> None
Set the app to quit either now or at the next clean opportunity.
ba.Session
<top level class>
Defines a high level series of activities with a common purpose.
Category: Gameplay Classes
Examples of sessions are ba.FreeForAllSession, ba.DualTeamSession, and ba.CoopSession.
A Session is responsible for wrangling and transitioning between various ba.Activity instances such as mini-games and score-screens, and for maintaining state between them (players, teams, score tallies, etc).
Attributes:
allow_mid_activity_joins, customdata, lobby, max_players, min_players, players, sessionglobalsnode, teams, use_team_colors, use_teams
allow_mid_activity_joins
-
bool
Whether players should be allowed to join in the middle of activities.
customdata
-
dict
A shared dictionary for objects to use as storage on this session. Ensure that keys here are unique to avoid collisions.
lobby
-
The ba.Lobby instance where new ba.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[ba.SessionPlayer]
All ba.Players in the Session. Most things should use the player list in ba.Activity; not this. Some players, such as those who have not yet selected a character, will only appear on this list.
sessionglobalsnode
-
The sessionglobals ba.Node for the session.
teams
-
List[ba.SessionTeam]
All the ba.Teams in the Session. Most things should use the team list in ba.Activity; not this.
use_team_colors
-
bool
Whether players on a team should all adopt the colors of that team instead of their own profile colors. This only applies if use_teams is enabled.
use_teams
-
bool
Whether this session groups players into an explicit set of teams. If this is off, a unique team is generated for each player that joins.
Methods:
<constructor>, begin_next_activity(), end(), end_activity(), get_custom_menu_entries(), getactivity(), handlemessage(), on_activity_end(), on_player_leave(), on_player_request(), on_team_join(), on_team_leave(), setactivity()
<constructor>
-
ba.Session(depsets: Sequence[ba.DependencySet], team_names: Sequence[str] = None, team_colors: Sequence[Sequence[float]] = None, min_players: int = 1, max_players: int = 8)
Instantiate a session.
depsets should be a sequence of successfully resolved ba.DependencySet instances; one for each ba.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: ba.Activity, results: Any, delay: float, force: bool) -> None
Commence shutdown of a ba.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[ba.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: ba.Activity, results: Any) -> None
Called when the current ba.Activity has ended.
The ba.Session should look at the results and start another ba.Activity.
on_player_leave()
-
on_player_leave(self, sessionplayer: ba.SessionPlayer) -> None
Called when a previously-accepted ba.SessionPlayer leaves.
on_player_request()
-
on_player_request(self, player: ba.SessionPlayer) -> bool
Called when a new ba.Player wants to join the Session.
This should return True or False to accept/reject.
on_team_join()
-
on_team_join(self, team: ba.SessionTeam) -> None
Called when a new ba.Team joins the session.
on_team_leave()
-
on_team_leave(self, team: ba.SessionTeam) -> None
Called when a ba.Team is leaving the session.
setactivity()
-
setactivity(self, activity: ba.Activity) -> None
Assign a new current ba.Activity for the session.
Note that this will not change the current context to the new Activity's. Code must be run in the new activity's methods (on_transition_in, etc) to get it. (so you can't do session.setactivity(foo) and then ba.newnode() to add a node to foo)
ba.SessionNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Session does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.SessionPlayer
<top level class>
A reference to a player in the ba.Session.
Category: Gameplay Classes
These are created and managed internally and provided to your Session/Activity instances. Be aware that, like ba.Nodes, ba.SessionPlayer 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 ba.SessionPlayer.exists() method (or boolean operator) to ensure that a SessionPlayer is still present if retaining references to one for any length of time.
Attributes:
activityplayer, character, color, highlight, id, in_game, inputdevice, sessionteam
activityplayer
-
Optional[ba.Player]
The current game-specific instance for this player.
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 ba.SessionTeam's color.
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.
id
-
int
The unique numeric ID of the 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.
in_game
-
bool
This bool value will be True once the Player has completed any lobby character/team selection.
inputdevice
-
The input device associated with the player.
sessionteam
-
The ba.SessionTeam this Player is on. If the SessionPlayer is still in its lobby selecting a team/etc. then a ba.SessionTeamNotFoundError will be raised.
Methods:
assigninput(), exists(), get_account_id(), get_icon(), getname(), remove_from_game(), resetinput(), setname()
assigninput()
-
assigninput(type: Union[ba.InputType, Tuple[ba.InputType, ...]], call: Callable) -> None
Set the python callable to be run for one or more types of input.
exists()
-
exists() -> bool
Return whether the underlying player is still in the game.
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)
getname()
-
getname(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.
remove_from_game()
-
remove_from_game() -> None
Removes the player from the game.
resetinput()
-
resetinput() -> None
Clears out the player's assigned input actions.
setname()
-
setname(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.
ba.SessionPlayerNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.SessionPlayer does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.SessionTeam
<top level class>
A team of one or more ba.SessionPlayers.
Category: Gameplay Classes
Note that a SessionPlayer *always* has a SessionTeam; in some cases, such as free-for-all ba.Sessions, each SessionTeam consists of just one SessionPlayer.
Attributes:
color, customdata, id, name, players
color
-
Tuple[float, ...]
The team's color.
customdata
-
dict
A dict for use by the current ba.Session for storing data associated with this team. Unlike customdata, this persists for the duration of the session.
id
-
int
The unique numeric id of the team.
name
-
Union[ba.Lstr, str]
The team's name.
players
-
List[ba.SessionPlayer]
The list of ba.SessionPlayers on the team.
Methods:
<constructor>
-
ba.SessionTeam(team_id: 'int' = 0, name: 'Union[ba.Lstr, str]' = '', color: 'Sequence[float]' = (1.0, 1.0, 1.0))
Instantiate a ba.SessionTeam.
In most cases, all teams are provided to you by the ba.Session, ba.Session, so calling this shouldn't be necessary.
ba.SessionTeamNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.SessionTeam does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.Setting
<top level class>
Defines a user-controllable setting for a game or other entity.
Category: Gameplay Classes
Methods:
<constructor>
-
ba.Setting(name: str, default: Any)
ba.ShouldShatterMessage
<top level class>
Tells an object that it should shatter.
Category: Message Classes
Methods:
<constructor>
-
ba.ShouldShatterMessage()
ba.Sound
<top level class>
A reference to a sound.
Category: Asset Classes
Use ba.getsound() to instantiate one.
ba.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
ba.StandLocation
<top level class>
Describes a point in space and an angle to face.
Category: Gameplay Classes
Methods:
<constructor>
-
ba.StandLocation(position: ba.Vec3, angle: Optional[float] = None)
ba.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
Methods:
<constructor>
-
ba.StandMessage(position: Sequence[float] = (0.0, 0.0, 0.0), angle: float = 0.0)
ba.Stats
<top level class>
Manages scores and statistics for a ba.Session.
Category: Gameplay Classes
Methods:
<constructor>, get_records(), getactivity(), player_scored(), player_was_killed(), register_sessionplayer(), reset(), reset_accum(), setactivity()
<constructor>
-
ba.Stats()
get_records()
-
get_records(self) -> Dict[str, ba.PlayerRecord]
Get PlayerRecord corresponding to still-existing players.
getactivity()
-
getactivity(self) -> Optional[ba.Activity]
Get the activity associated with this instance.
May return None.
player_scored()
-
player_scored(self, player: ba.Player, base_points: int = 1, target: Sequence[float] = None, kill: bool = False, victim_player: ba.Player = None, scale: float = 1.0, color: Sequence[float] = None, title: Union[str, ba.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.
player_was_killed()
-
player_was_killed(self, player: ba.Player, killed: bool = False, killer: ba.Player = None) -> None
Should be called when a player is killed.
register_sessionplayer()
-
register_sessionplayer(self, player: ba.SessionPlayer) -> None
Register a ba.SessionPlayer with this score-set.
reset()
-
reset(self) -> None
Reset the stats instance completely.
reset_accum()
-
reset_accum(self) -> None
Reset per-sound sub-scores.
setactivity()
-
setactivity(self, activity: Optional[ba.Activity]) -> None
Set the current activity for this instance.
ba.Team
Inherits from: typing.Generic
A team in a specific ba.Activity.
Category: Gameplay Classes
These correspond to ba.SessionTeam objects, but are created per activity so that the activity can use its own custom team subclass.
Attributes:
customdata, sessionteam
customdata
-
dict
Arbitrary values associated with the team. Though it is encouraged that most player values be properly defined on the ba.Team subclass, it may be useful for player-agnostic objects to store values here. This dict is cleared when the team leaves or expires so objects stored here will be disposed of at the expected time, unlike the Team instance itself which may continue to be referenced after it is no longer part of the game.
sessionteam
-
SessionTeam
Return the ba.SessionTeam corresponding to this Team.
Throws a ba.SessionTeamNotFoundError if there is none.
Methods:
manual_init(), on_expire()
manual_init()
-
manual_init(self, team_id: int, name: Union[ba.Lstr, str], color: Tuple[float, ...]) -> None
Manually init a team for uses such as bots.
on_expire()
-
on_expire(self) -> None
Can be overridden to handle team expiration.
ba.TeamGameActivity
Inherits from: ba.GameActivity, ba.Activity, ba.DependencyComponent, typing.Generic
Base class for teams and free-for-all mode games.
Category: Gameplay Classes
(Free-for-all is essentially just a special case where every ba.Player has their own ba.Team)
Attributes Inherited:
players, settings_raw, teams
Attributes Defined Here:
customdata, expired, globalsnode, map, playertype, session, stats, teamtype
customdata
-
dict
Entities needing to store simple data with an activity can put it here. This dict will be deleted when the activity expires, so contained objects generally do not need to worry about handling expired activities.
expired
-
bool
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'.
globalsnode
-
The 'globals' ba.Node for the activity. This contains various global controls and values.
map
-
The map being used for this game.
Raises a ba.NotFoundError if the map does not currently exist.
playertype
-
Type[PlayerType]
The type of ba.Player this Activity is using.
session
-
The ba.Session this ba.Activity belongs go.
Raises a ba.SessionNotFoundError if the Session no longer exists.
stats
-
The stats instance accessible while the activity is running.
If access is attempted before or after, raises a ba.NotFoundError.
teamtype
-
Type[TeamType]
The type of ba.Team this Activity is using.
Methods Inherited:
add_actor_weak_ref(), add_player(), add_team(), begin(), continue_or_end_game(), create_player(), create_settings_ui(), create_team(), dep_is_present(), end_game(), expire(), get_available_settings(), get_description(), get_description_display_string(), get_display_string(), get_dynamic_deps(), get_instance_description(), get_instance_description_short(), get_instance_display_string(), get_instance_scoreboard_display_string(), get_settings_display_string(), get_supported_maps(), get_team_display_string(), getname(), getscoreconfig(), handlemessage(), has_begun(), has_ended(), has_transitioned_in(), 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(), remove_player(), remove_team(), respawn_player(), retain_actor(), set_has_ended(), setup_standard_powerup_drops(), setup_standard_time_limit(), show_zoom_message(), spawn_player(), spawn_player_if_exists(), transition_in(), transition_out()
Methods Defined or Overridden:
<constructor>, end(), on_begin(), on_transition_in(), spawn_player_spaz(), supports_session_type()
<constructor>
-
ba.TeamGameActivity(settings: dict)
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 ba.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) -> 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 players or teams, however. They remain owned by the previous Activity up until ba.Activity.on_begin() is called.
spawn_player_spaz()
-
spawn_player_spaz(self, player: PlayerType, position: Sequence[float] = None, angle: float = None) -> PlayerSpaz
Method override; spawns and wires up a standard ba.PlayerSpaz for a ba.Player.
If position or angle is not supplied, a default will be chosen based on the ba.Player and their ba.Team.
supports_session_type()
-
<class method>
supports_session_type(sessiontype: Type[ba.Session]) -> bool
Class method override; returns True for ba.DualTeamSessions and ba.FreeForAllSessions; False otherwise.
ba.TeamNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Team does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.Texture
<top level class>
A reference to a texture.
Category: Asset Classes
Use ba.gettexture() to instantiate one.
ba.ThawMessage
<top level class>
Tells an object to stop being frozen.
Category: Message Classes
Methods:
<constructor>
-
ba.ThawMessage()
ba.TimeFormat
Inherits from: enum.Enum
Specifies the format time values are provided in.
Category: Enums
Values:
- SECONDS
- MILLISECONDS
ba.Timer
<top level class>
Timer(time: float, call: Callable[[], Any], repeat: bool = False, timetype: ba.TimeType = TimeType.SIM, timeformat: ba.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 ba.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 ba.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 ba.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 ba.Activity or ba.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 ba.Activity or ba.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(): ba.screenmessage('BADGER!') def stop_saying_it(): self.t = None ba.screenmessage('MUSHROOM MUSHROOM!') # create our timer; it will run as long as we hold self.t self.t = ba.Timer(0.3, say_it, repeat=True) # now fire off a one-shot timer to kill it ba.timer(3.89, stop_saying_it)
ba.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 occurrences 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
ba.UIController
<top level class>
Wrangles UILocations.
Category: User Interface Classes
Methods:
<constructor>, show_main_menu()
<constructor>
-
ba.UIController()
show_main_menu()
-
show_main_menu(self, in_game: bool = True) -> None
Show the main menu, clearing other UIs from location stacks.
ba.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.
ba.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() ba.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() ba.timer(5.0, ba.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>
-
ba.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 = ba.WeakCall(myobj.dostuff, argval1, namedarg=argval2)
# Now we have a single callable to run that whole mess. # The same as calling myobj.dostuff(argval1, namedarg=argval2) # (provided my_obj still exists; this will do nothing otherwise) myweakcall()
ba.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 ba.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[ba.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[ba.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 ba.Widget type, which is the same for all widgets.
ba.WidgetNotFoundError
Inherits from: ba.NotFoundError, Exception, BaseException
Exception raised when an expected ba.Widget does not exist.
Category: Exception Classes
Methods:
<all methods inherited from ba.NotFoundError>
ba.Window
<top level class>
A basic window.
Category: User Interface Classes
Methods:
<constructor>, get_root_widget()
<constructor>
-
ba.Window(root_widget: ba.Widget)
get_root_widget()
-
get_root_widget(self) -> ba.Widget
Return the root widget.
ba.animate()
animate(node: ba.Node, attr: str, keys: Dict[float, float], loop: bool = False, offset: float = 0, timetype: ba.TimeType = <TimeType.SIM: 0>, timeformat: ba.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> ba.Node
Animate values on a target ba.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 ba 1.5) of taking milliseconds. Returns the animcurve node.
ba.animate_array()
animate_array(node: ba.Node, attr: str, size: int, keys: Dict[float, Sequence[float]], loop: bool = False, offset: float = 0, timetype: ba.TimeType = <TimeType.SIM: 0>, timeformat: ba.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> None
Animate an array of values on a target ba.Node.
Category: Gameplay Functions
Like ba.animate(), but operates on array attributes.
ba.buttonwidget()
buttonwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, on_activate_call: Callable = None, label: Union[str, ba.Lstr] = None, color: Sequence[float] = None, down_widget: ba.Widget = None, up_widget: ba.Widget = None, left_widget: ba.Widget = None, right_widget: ba.Widget = None, texture: ba.Texture = None, text_scale: float = None, textcolor: Sequence[float] = None, enable_sound: bool = None, model_transparent: ba.Model = None, model_opaque: ba.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: ba.Texture = None, iconscale: float = None, icon_tint: float = None, icon_color: Sequence[float] = None, autoselect: bool = None, mask_texture: ba.Texture = None, tint_texture: ba.Texture = None, tint_color: Sequence[float] = None, tint2_color: Sequence[float] = None, text_flatness: float = None, text_res_scale: float = None, enabled: bool = None) -> ba.Widget
Create or edit a button widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.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.
ba.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.
ba.charstr()
charstr(char_id: ba.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 ba.SpecialChar for the list of available characters.
ba.checkboxwidget()
checkboxwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, text: Union[ba.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) -> ba.Widget
Create or edit a check-box widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.columnwidget()
columnwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: ba.Widget = None, visible_child: ba.Widget = None, single_depth: bool = None, print_list_exit_instructions: bool = None, left_border: float = None, top_border: float = None, bottom_border: float = None) -> ba.Widget
Create or edit a column widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.containerwidget()
containerwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: ba.Widget = None, transition: str = None, cancel_button: ba.Widget = None, start_button: ba.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: ba.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) -> ba.Widget
Create or edit a container widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.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.
# Example: this print will only fire for the first loop iteration: for i in range(10): if ba.do_once(): print('Hello once from loop!')
ba.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.
ba.existing()
existing(obj: Optional[ExistableType]) -> Optional[ExistableType]
Convert invalid references to None for any ba.Existable type.
Category: Gameplay Functions
To best support type checking, it is important that invalid references not be passed around and instead get converted to values of None. That way the type checker can properly flag attempts to pass dead objects into functions expecting only live ones, etc. This call can be used on any 'existable' object (one with an exists() method) and will convert it to a None value if it does not exist. For more info, see notes on 'existables' here: https://ballistica.net/wiki/Coding-Style-Guide
ba.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.
ba.getactivity()
getactivity(doraise: bool = True) -> <varies>
Return the current ba.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, raises a ba.ActivityNotFoundError. If doraise is False, None will be returned instead in that case.
ba.getcollidemodel()
getcollidemodel(name: str) -> ba.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.
ba.getcollision()
getcollision() -> Collision
Return the in-progress collision.
ba.getmaps()
getmaps(playtype: str) -> List[str]
Return a list of ba.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.
ba.getmodel()
getmodel(name: str) -> ba.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.
ba.getnodes()
getnodes() -> list
Return all nodes in the current ba.Context. Category: Gameplay Functions
ba.getsession()
getsession(doraise: bool = True) -> <varies>
Category: Gameplay Functions
Returns the current ba.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.
ba.getsound()
getsound(name: str) -> ba.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.
ba.gettexture()
gettexture(name: str) -> ba.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.
ba.hscrollwidget()
hscrollwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: ba.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) -> ba.Widget
Create or edit a horizontal scroll widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.imagewidget()
imagewidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, color: Sequence[float] = None, texture: ba.Texture = None, opacity: float = None, model_transparent: ba.Model = None, model_opaque: ba.Model = None, has_alpha_channel: bool = True, tint_texture: ba.Texture = None, tint_color: Sequence[float] = None, transition_delay: float = None, draw_controller: ba.Widget = None, tint2_color: Sequence[float] = None, tilt_scale: float = None, mask_texture: ba.Texture = None, radial_amount: float = None) -> ba.Widget
Create or edit an image widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.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 ba.show_url() with any lengthy addresses. (ba.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.)
ba.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).
ba.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.
ba.newactivity()
newactivity(activity_type: Type[ba.Activity], settings: dict = None) -> ba.Activity
Instantiates a ba.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.
ba.newnode()
newnode(type: str, owner: ba.Node = 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 ba.Actor
ba.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
ba.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.
ba.playsound()
playsound(sound: Sound, volume: float = 1.0, position: Sequence[float] = None, host_only: bool = False) -> None
Play a ba.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.
ba.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.
ba.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.
ba.printnodes()
printnodes() -> None
Print various info about existing nodes; useful for debugging.
Category: Gameplay Functions
ba.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.
ba.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 disallowed from within other callbacks, etc.
This call expects to be used in the game thread, and will automatically save and restore the ba.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.
ba.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.
ba.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 ba.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.
ba.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.
ba.screenmessage()
screenmessage(message: Union[str, ba.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.
ba.scrollwidget()
scrollwidget(edit: ba.Widget = None, parent: ba.Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, background: bool = None, selected_child: ba.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) -> ba.Widget
Create or edit a scroll widget.
Category: User Interface Functions
Pass a valid existing ba.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.
ba.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.)
ba.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.
ba.setmusic()
setmusic(musictype: Optional[MusicType], continuous: bool = False) -> None
Tell the game to play (or stop playing) a certain type of music.
Category: Gameplay Functions
This function will handle loading and playing sound assets 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 and musictype is the same as what is already playing, the playing track will not be restarted.
ba.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.
Category: Gameplay Functions
ba.storagename()
storagename(basename: str) -> str
Generate a (hopefully) unique name for storing things in public places.
Category: General Utility Functions
This consists of a leading underscore, the module path at the call site with dots replaced by underscores, the class name, and the provided suffix. When storing data in public places such as 'customdata' dicts, this minimizes the chance of collisions if a module or class is duplicated or renamed.
# Example: generate a unique name for storage purposes:
class MyThingie:
# This will give something like '_mymodule_submodule_mythingie_data'. _STORENAME = ba.storagename('data')
def __init__(self, activity): # Store some data in the Activity we were passed activity.customdata[self._STORENAME] = {}
ba.textwidget()
textwidget(edit: Widget = None, parent: Widget = None, size: Sequence[float] = None, position: Sequence[float] = None, text: Union[str, ba.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, ba.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 ba.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.
ba.time()
time(timetype: ba.TimeType = TimeType.SIM, timeformat: ba.TimeFormat = TimeFormat.SECONDS) -> <varies>
Return the current time.
Category: General Utility Functions
The time returned depends on the current ba.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 ba.Activity or ba.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 ba.Activity or ba.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().
ba.timer()
timer(time: float, call: Callable[[], Any], repeat: bool = False, timetype: ba.TimeType = TimeType.SIM, timeformat: ba.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 ba.Context. This timer cannot be canceled or modified once created. If you require the ability to do so, use the ba.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 ba.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 ba.Activity or ba.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 ba.Activity or ba.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: ba.screenmessage('hello from now!') ba.timer(1.0, ba.Call(ba.screenmessage, 'hello from the future!')) ba.timer(2.0, ba.Call(ba.screenmessage, 'hello from the future 2!'))
ba.timestring()
timestring(timeval: float, centi: bool = True, timeformat: ba.TimeFormat = <TimeFormat.SECONDS: 0>, suppress_format_warning: bool = False) -> ba.Lstr
Generate a ba.Lstr for displaying a time value.
Category: General Utility Functions
Given a time value, returns a ba.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 ba.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.
ba.uicleanupcheck()
uicleanupcheck(obj: Any, widget: ba.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 ba.Widget dies.
This is a good sanity check for any sort of object that wraps or controls a ba.Widget. For instance, a 'Window' class instance has no reason to still exist once its root container ba.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.
ba.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.
ba.verify_object_death()
verify_object_death(obj: object) -> None
Warn if an object does not get freed within a short period.
Category: General Utility Functions
This can be handy to detect and prevent memory/resource leaks.
ba.widget()
widget(edit: ba.Widget = None, up_widget: ba.Widget = None, down_widget: ba.Widget = None, left_widget: ba.Widget = None, right_widget: ba.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.