Scenes
Scenes are a fundamental part of your game. They keep everything neatly organized.
Why Scenes?
As an example, picture a game with a title screen and a settings menu. Without scenes, the game loop would contain code for both of those screens.
After a while, you might add a game screen, a pause menu, etc. At this point your game loop would be very busy from all the different code needed to handle all those different screens.
So as a good developer, you'd think to shorten and simplify your code by making functions or classes that encapsulate the logic of each scene to keep the game loop neat and clean. That's basically what scenes do!
Basics
Layers (world and hud)
Each default Scene creates two SceneLayers:
world— gameplay entities (player, enemies, tiles, …)hud— interface entities; also hostsscene.root(the GUI tree)
Each layer has its own camera and entity list. World is processed/drawn before HUD by default.
class MyScene(bf.Scene):
def do_when_added(self):
self.add("world", player, enemy)
self.root.add(score_label) # GUI on the hud layer
# or: self.add("hud", some_entity)
You can add custom layers with add_layer(SceneLayer(...)), reorder them, or use BaseScene if you want an empty scene with no default layers.
How to use a Scene
To customize a scene, inherit the Scene class:
class MyScene(bf.Scene):...
Important methods:
do_when_added(self)— called once when linked with the Managerdo_update(self, dt: float)— every frame (dtin seconds)do_on_enter(self)/do_on_exit(self)— stack enter/exitadd(self, layer: str, *entities)— queue entities onto a named layerremove(self, layer: str, *entities)— queue removal from a layerget_layer(self, name: str)— access aSceneLayer(and its.camera)set_clear_color(self, color)— scene background before layers drawget_by_tags(self, *tags)— entities matching tags across all layersget_by_uid(self, uid)— lookup by unique id
Draw customization hooks:
do_early_draw(surface)do_between_layer_draw(surface, layer)do_final_draw(surface)
Check the source code on GitHub (master branch) for the full API.