earwax.game module

Provides the Game class.

class earwax.game.Game(name: str = 'earwax.game', audio_context: Optional[object] = NOTHING, buffer_cache: earwax.sound.BufferCache = NOTHING, interface_sound_manager: earwax.sound.SoundManager = NOTHING, music_sound_manager: Optional[earwax.sound.SoundManager] = NOTHING, ambiance_sound_manager: Optional[earwax.sound.SoundManager] = NOTHING, thread_pool: concurrent.futures._base.Executor = NOTHING, credits: List[earwax.credit.Credit] = NOTHING, logger: logging.Logger = NOTHING)

Bases: earwax.mixins.RegisterEventMixin

The main game object.

This object holds a reference to the game window, as well as a list of Level instances.

In addition, references to various parts of the audio subsystem reside on this object, namely audio_context.

Instances of the Level class can be pushed, popped, and replaced. The entire stack can also be cleared.

Although it doesn’t matter in what order you create objects, a Game instance is necessary for Level instances - and subclasses thereof - to be useful.

Variables:
  • window – The pyglet window used to display the game.
  • config – The configuration object used by this game.
  • name – The name of this game. Used by get_settings_path().
  • audio_context – The Synthizer context to route audio through.
  • interface_sound_manager – A sound manager for playing interface sounds.
  • music_sound_manager – A sound manager for playing music.
  • ambiance_sound_manager – A sound manager for playing ambiances.
  • levels – All the pushed earwax.Level instances.
  • triggered_actions – The currently triggered earwax.Action instances.
  • key_release_generators – The earwax.Action instances which returned generators, and need to do something on key release.
  • mouse_release_generators – The earwax.Action instances which returned generators, and need to do something on mouse release.
  • joybutton_release_generators – The earwax.Action instances which returned generators, and need to do something on joystick button release.
  • event_matchers

    The earwax.EventMatcher instances used by this object.

    To take advantage of the pyglet events system, subclass earwax.Game, or earwax.Level, and include events from pyglet.window.Window.

  • joysticks – The list of joysticks that have been opened by this instance.
  • thread_pool – An instance of ThreadPoolExecutor to use for threaded operations.
  • tasks

    A list of earwax.Task instances.

    You can add tasks with the register_task() decorator, and remove them again with the remove_task() method.

adjust_volume(amount: float) → float

Adjust the master volume.

Parameters:amount – The amount to add to the current volume.
after_run() → None

Run code before the game exits.

This event is dispatched after the main game loop has ended.

By this point, synthizer has been shutdown, and there is nothing else to be done.

before_run() → None

Do stuff before starting the main event loop.

This event is used by the run method, before any initial level is pushed, or any of the sound managers are created.

This is the event to use if you’re planning to load configuration.

By this point, default events have been decorated, such as on_key_press and on_text. Also, we are inside a synthizer.initialized context manager, so feel free to play sounds, and use self.audio_context.

cancel(message: str = 'Cancelled', level: Optional[earwax.level.Level] = None) → None

Cancel with an optional message.

All this method does is output the given message, and either pop the most recent level, or reveal the given level.

Parameters:
  • message – The message to output.
  • level

    The level to reveal.

    If this value is None, then the most recent level will be popped.

change_volume(amount: float) → Callable[[], None]

Return a callable that can be used to change the master volume.

Parameters:amount – The amount to change the volume by.
clear_levels() → None

Pop all levels.

The earwax.Level.on_pop() method will be called on every level that is popped.

click_mouse(button: int, modifiers: int) → None

Simulate a mouse click.

This method is used for testing, to simulate first pressing, then releasing a mouse button.

Parameters:
finalise_run() → None

Perform the final steps of running the game.

  • Dispatch the before_run() event.
  • Call pyglet.app.run().
  • Unload Cytolk.
  • Dispatch the after_run() event.
get_default_buffer_cache() → earwax.sound.BufferCache

Return the default buffer cache.

Parameters:instance – The game to return the buffer cache for.
get_default_logger() → logging.Logger

Return a logger.

get_settings_path() → pathlib.Path

Get a path to store game settings.

Uses pyglet.resource.get_settings_path to get an appropriate settings path for this game.

init_sdl() → None

Initialise SDL.

level

Get the most recently added earwax.Level instance.

If the stack is empty, None will be returned.

on_close() → None

Run code when closing the window.

Called when the window is closing.

This is the default event that is used by pyglet.window.Window.

By default, this method calls self.clear_levels(), to ensure any clean up code is called.

on_joybutton_press(joystick: pyglet.input.base.Joystick, button: int) → bool

Handle the press of a joystick button.

This is the default handler that fires when a joystick button is pressed.

Parameters:joystick – The joystick that emitted the event.

: param button: The button that was pressed.

on_joybutton_release(joystick: pyglet.input.base.Joystick, button: int) → bool

Handle the release of a joystick button.

This is the default handler that fires when a joystick button is released.

Parameters:joystick – The joystick that emitted the event.

: param button: The button that was pressed.

on_joyhat_motion(joystick: pyglet.input.base.Joystick, x: int, y: int) → bool

Handle joyhat motions.

This is the default handler that fires when a hat is moved.

If the given position is the default position (0, 0), then any actions started by hat motions are stopped.

Parameters:joystick – The joystick that emitted the event.

: param x: The left / right position of the hat.

: param y: The up / down position of the hat.

on_key_press(symbol: int, modifiers: int) → bool

Handle a pressed key.

This is the default event that is used by pyglet.window.Window.

By default it iterates through self.level.actions, and searches for events that match the given symbol and modifiers.

Parameters:
on_key_release(symbol: int, modifiers: int) → bool

Handle a released key.

This is the default event that is used by pyglet.window.Window.

Parameters:
on_mouse_press(x: int, y: int, button: int, modifiers: int) → bool

Handle a mouse button press.

This is the default event that is used by pyglet.window.Window.

By default, this method pretty much acts the same as on_key_press(), except it checks the discovered actions for mouse buttons, rather than symbols.

Parameters:
  • x – The x coordinate of the mouse.
  • y – The y coordinate of the mouse.
  • button – One of the mouse button constants from pyglet.window.mouse.
  • modifiers – One of the modifier constants from pyglet.window.key.
on_mouse_release(x: int, y: int, button: int, modifiers: int) → bool

Handle a mouse button release.

This is the default event that is used by pyglet.window.Window.

By default, this method is pretty much the same as on_key_release(), except that it uses the discovered actions mouse button information.

Parameters:
  • x – The x coordinate of the mouse.
  • y – The y coordinate of the mouse.
  • button – One of the mouse button constants from pyglet.window.mouse.
  • modifiers – One of the modifier constants from pyglet.window.key.
open_joysticks() → None

Open and attach events to all attached joysticks.

output(text: str, interrupt: bool = False) → None

Output braille and / or speech.

The earwax configuration is used to determine what should be outputted.

Parameters:
  • text – The text to be spoken or output to a braille display.
  • interrupt – If Whether or not to silence speech before outputting anything else.
poll_synthizer_events(dt: float) → None

Poll the audio context for new synthizer events.

Parameters:dt – The delta provided by Pyglet.
pop_level() → None

Pop the most recent earwax.Level instance from the stack.

If there is a level underneath the current one, then events will be passed to it. Otherwise there will be an empty stack, and events won’t get handled.

This method calls on_pop() on the popped level, and on_reveal() on the one below it.

pop_levels(n: int) → None

Pop the given number of levels.

Parameters:n – The number of times to call pop_level().
press_key(symbol: int, modifiers: int, string: Optional[str] = None, motion: Optional[int] = None) → None

Simulate a key press.

This method is used in tests.

First presses the given key combination, then releases it.

If string and motion are not None, then on_text, and on_text_motion events will also be fired.

Parameters:
  • symbol – One of the key constants from pyglet.window.key.
  • modifiers – One of the modifier constants from pyglet.window.key.
  • string – A string to be picked up by an on_text event handler..
  • motion – A key to be picked up by an on_text_motion event handler.
push_action_menu(title: str = 'Actions', **kwargs) → earwax.menus.action_menu.ActionMenu

Push and return an action menu.

This method reduces the amount of code required to create a help menu:

@level.action(
    'Help Menu', symbol=key.SLASH, modifiers=key.MOD_SHIFT
)
def help_menu() -> None:
    game.push_action_menu()
Parameters:
  • title – The title of the new menu.
  • kwargs – The extra keyword arguments to pass to the ActionMenu constructor.
push_credits_menu(title='Game Credits') → earwax.menus.menu.Menu

Push a credits menu onto the stack.

This method reduces the amount of code needed to push a credits menu:

@level.action('Show credits', symbol=key.F1)
def show_credits() -> None:
    game.push_credits_menu()
Parameters:title – The title of the new menu.
push_level(level: earwax.level.Level) → None

Push a level onto self.levels.

This ensures that all events will be handled by the provided level until another level is pushed on top, or the current one is popped.

This method also dispatches the on_push() event on the provided level.

If the old level is not None, then the on_cover event is dispatched on the old level, with the new level as the only argument.

Parameters:level – The earwax.Level instance to push onto the stack.
register_task(interval: Callable[[], float]) → Callable[[Callable[[float], None]], earwax.task.Task]

Decorate a function to use as a task.

This function allows you to convert a function into a Task instance, so you can add tasks by decoration:

@game.register_task(lambda: uniform(1.0, 5.0))
def task(dt: float) -> None:
    '''A task.'''
    print('Working: %.2f.' % dt)
task.start()
Parameters:interval – The function to use for the interval.
remove_task(task: earwax.task.Task) → None

Stop and remove a task.

Parameters:task

The task to be stopped.

The task will first have its stop() method called, then it will be removed from the tasks list.

replace_level(level: earwax.level.Level) → None

Pop the current level, then push the new one.

This method uses pop_level(), and push_level(), so make sure you familiarise yourself with what events will be called on each level.

Parameters:level – The earwax.Level instance to push onto the stack.
reveal_level(Level: earwax.level.Level) → int

Pop levels until level is revealed.

This method returned the number of levels which were popped.

Parameters:level – The level to reveal.
run(window: pyglet.window.BaseWindow, mouse_exclusive: bool = True, initial_level: Optional[earwax.level.Level] = None) → None

Run the game.

By default, this method will perform the following actions in order:

  • Iterate over all the found event types on pyglet.window.Window,
    and decorate them with EventMatcher instances. This means Game and Level subclasses can take full advantage of all event types by simply adding methods with the correct names to their classes.
  • Load cytolk.
  • Initialise SDL2.
  • Set the requested mouse exclusive mode on the provided window.
  • call open_joysticks().
  • If no audio_context is present, enter a
    synthizer.initialized contextmanager.
  • Call the setup_run() method.
  • Call the finalise_run() method.
Parameters:
  • window – The pyglet window that will form the game’s interface.
  • mouse_exclusive – The mouse exclusive setting for the window.
  • initial_level – A level to push onto the stack.
set_volume(value: float) → None

Set the master volume to a specific value.

Parameters:value – The new volume.
setup() → None

Set up things needed for the game.

This event is dispatched just inside the synthizer context manager, before the various sound managers have been created.

This event is perfect for loading configurations ETC.

setup_run(initial_level: Optional[earwax.level.Level]) → None

Get ready to run the game.

This method dispatches the setup() event, and sets up sound managers.

Finally, it pushes the initial level, if necessary.

Parameters:initial_level – The initial level to be pushed.
start_action(a: earwax.action.Action) → Optional[Generator[None, None, None]]

Start an action.

If the action has no interval, it will be ran straight away. Otherwise, it will be added to self.triggered_actions, and only ran if enough time has elapsed since the last run.

This method is used when a trigger fires - such as a mouse button or key sequence being pressed - that triggers an action.

Parameters:a – The earwax.Action instance that should be started.
start_rumble(joystick: pyglet.input.base.Joystick, value: float, duration: int) → None

Start a simple rumble.

Parameters:
  • joystick – The joystick to rumble.
  • value – A value from 0.0 to 1.0, which is the power of the rumble.
  • duration – The duration of the rumble in milliseconds.
stop() → None

Close self.window.

If self.window is None, then :class:earwax.GameNotRunning` will be raised.

stop_action(a: earwax.action.Action) → None

Unschedule an action.

The provided action will be removed from triggered_actions.

This method is called when the user stops doing something that previously triggered an action, such as releasing a key or a mouse button

Parameters:a – The earwax.Action instance that should be stopped.
stop_rumble(joystick: pyglet.input.base.Joystick) → None

Cancel a rumble.

Parameters:joystick – The joystick you want to rumble.
exception earwax.game.GameNotRunning

Bases: Exception

This game is not running.