Async State Manager

class game_state.AsyncStateManager(*, bound_state_type=<class 'game_state.async_machine.state.AsyncState'>, **kwargs)

The State Manager used for managing multiple State(s).

Parameters:
  • bound_state_type (Type[TypeVar(S, bound= AsyncState[Any])]) –

    The base state class which all states inherit from.

  • **kwargs (Any) –

    The keyword arguments to bind to bound_state_type.

Variables:

is_running (bool) –

Added in version 2.4.

A bool for controlling the game loop. True by default.

property current_state: S | None

The current state if applied. Will be None otherwise.

Type:

AsyncState | None

Added in version 2.4.

Note

This is a read-only attribute. To change states use change_state() instead.

property last_state: S | None

The last state object if any. Will be None otherwise.

Type:

AsyncState | None

Added in version 2.4.

Note

This is a read-only attribute.

property lazy_state_map: Dict[str, Tuple[Type[S], List[StateArgs] | None]]

A dictionary copy of all the added lazy state names mapped to their respective type and state args.

Type:

dict[str, tuple[type[AsyncState], None | list[StateArgs]]]

Added in version 2.4.

Note

This is a read-only attribute.

Note

Once the lazy state has been fully initialized, it will be removed from the lazy state map.

property state_map: Dict[str, S]

A dictionary copy of all the state names mapped to their respective instance.

Type:

dict[str, AsyncState]

Added in version 2.4.

Note

This is a read-only attribute.

property global_on_enter: Callable[[S, S | None], Awaitable[None]] | None

The global on_enter listener called right before a state’s on_enter listener.

Type:

None | Callable[[AsyncState, Optional[AsyncState]], None]

Added in version 2.4.

Note

This has to be assigned before changing the states.

The first argument passed to the function is the current state and the second is the previous state which may be None.

Example for a global_on_enter function-

async def global_on_enter(
    current_state: AsyncState, previous_state: None | AsyncState
) -> None:
    if previous_state:
        print(
            f"GLOBAL ENTER - Entering {current_state.state_name} from {previous_state.state_name}"
        )


your_manager_instance.global_on_enter = global_on_enter
property global_on_leave: Callable[[S | None, S], Awaitable[None]] | None

The global on_leave listener called right before a state’s on_leave listener.

Type:

None | Callable[[Optional[AsyncState], AsyncState], None]

Added in version 2.4.

Note

This has to be assigned before changing the states.

The first argument passed to the function is the current state which may be None and the second is the next state to take place.

Example for a global_on_leave function-

async def global_on_leave(
    current_state: None | AsyncState, next_state: AsyncState
) -> None:
    if current_state:
        print(
            f"GLOBAL LEAVE - Leaving {current_state.state_name} to {next_state.state_name}"
        )


your_manager_instance.global_on_leave = global_on_leave
property global_on_load: Callable[[S, bool], Awaitable[None]] | None

The global AsyncState.on_load() function for all states.

Type:

None | Callable[[AsyncState, bool], None]

Added in version 2.4.

Note

This has to be assigned before loading the states into the manager.

The first argument passed to the function is the current state which has been set up.

Example for a global_on_load function-

async def global_on_load(state: AsyncState, reload: bool) -> None:
    print(f"GLOBAL LOAD - Loading up state: {state.state_name}")
    if reload:
        print("The state is being reloaded.")
    else:
        print("The state is not being reloaded.")


your_manager_instance.global_on_load = global_on_load
property global_on_unload: Callable[[S, bool], Awaitable[None]] | None

The global AsyncState.on_unload() function for all states.

Type:

None | Callable[[AsyncState, bool], None]

Added in version 2.4.

Note

This has to be assigned before loading the states into the manager.

The first argument passed to the function is the current state which has been set up.

Example for a global_on_unload function-

def global_on_unload(state: AsyncState, reload: bool) -> None:
    print(f"GLOBAL UNLOAD - Loading up state: {state.state_name}")
    if reload:
        print("The state is being reloaded.")
    else:
        print("The state is not being reloaded.")


your_manager_instance.global_on_unload = global_on_unload
async change_state(state_name, clear_overlays=False)

Changes the current state and updates the last state. This method executes the AsyncState.on_leave() & AsyncState.on_enter() state & global listeners (global_on_leave() & global_on_enter()).

Changed in version 2.5.

Added in version 2.4.

Parameters:
  • state_name (str) –

    The name of the state you want to switch to.

  • clear_overlays (bool) –

    Whether to clear all the overlays before switching states or not.

Raises:
game_state.errors.StateError
Raised when the state name doesn’t exist in the manager.
Return type:

None

async connect_state_hook(path, **kwargs)

Calls the hook function of the state file.

Added in version 2.4.

Parameters:
  • path (str) –

    The path to the state file containing the hook function to be called.

  • **kwargs (Any) –

    The keyword arguments to be passed to the hook function.

Raises:
game_state.errors.StateError
Raised when the hook function was not found in the state file to be loaded.
Return type:

None

add_lazy_states(*lazy_states, force=False, state_args=None)

Lazily adds the States into the StateManager. Unlike load_states(), it only initializes the state when required i.e. when change_state() switches to the lazy state.

Added in version 2.4.

Parameters:
  • lazy_states (Type[S]) –

    The states to be loaded into the manager as lazy states.

  • force (bool) –

    Default False.

    Loads the state regardless of whether the state has already been loaded or not
    without raising any internal error.

    Warning

    If set to True it may lead to unexpected behavior.

  • state_args (Optional[Iterable[StateArgs]]) –

    The data to be passed to the subclassed states upon their initialization in the manager.

Raises:
game_state.errors.StateLoadError
Raised when the state has already been loaded.
Only raised when force is set to False.
Return type:

None

async load_states(*states, force=False, state_args=None)

Loads the States into the StateManager.

Added in version 2.4.

Parameters:
  • states (Type[S]) –

    The States to be loaded into the manager.

  • force (bool) –

    Default False.

    Loads the state regardless of whether the state has already been loaded or not
    without raising any internal error.

    Warning

    If set to True it may lead to unexpected behavior.

  • state_args (Optional[Iterable[StateArgs]]) –

    The data to be passed to the subclassed states upon their initialization in the manager.

Raises:
game_state.errors.StateLoadError
Raised when the state has already been loaded.
Only raised when force is set to False.
Return type:

None

async reload_state(state_name, force=False, **kwargs)

Reloads the specified state. A shorthand to unload_state() & load_states().

Added in version 2.4.

Parameters:
  • state_name (str) –

    The state name to be reloaded.

  • force (bool) –

    Default False.

    Reloads the state even if it’s an actively running state without
    raising any internal error.

    Warning

    If set to True it may lead to unexpected behavior.

  • **kwargs (Any) –

    The keyword arguments to be passed to the unload_state() & load_states().

Return type:

TypeVar(S, bound= AsyncState[Any])

Returns:

Returns the newly made AsyncState instance.

Raises:
game_state.errors.StateLoadError
Raised when the state has already been loaded.
Only raised when force is set to False.
remove_lazy_state(state_name)

Removes the specified lazy state from the StateManager. This will silently fail if the lazy state has been loaded to the manager, which in case you will have to unload via unload_state().

Added in version 2.4.

Parameters:

state_name (str) –

The state to be removed from the manager.

Return type:

Optional[Tuple[Type[S], Optional[List[StateArgs]]]]

Returns:

Either returns None if the lazy state was not found, or it returns a
tuple with the first element being the lazy state and the second being
the StateArgs if any were passed.

async unload_state(state_name, force=False, **kwargs)

Unloads the specified state from the StateManager.

Added in version 2.4.

Parameters:
  • state_name (str) –

    The state name to be unloaded from the manager.

  • force (bool) –

    Default False.

    Unloads the state even if it’s an actively running state without raising any internal error.

    Warning

    If set to True it may lead to unexpected behavior.

  • **kwargs (Any) –

    The keyword arguments to be passed on to the raised errors.

Return type:

Type[TypeVar(S, bound= AsyncState[Any])]

Returns:

The AsyncState class of the deleted state name.

Raises:
game_state.errors.StateLoadError
Raised when the state doesn’t exist in the manager to be unloaded.
game_state.errors.StateError
Raised when trying to unload an actively running state.
Only raised when force is set to False.
async close_overlay(state_id, **kwargs)

Closes an overlay state. You can close any of the opened overlay state and not just the active overlay state.

Added in version 2.5.

Parameters:
  • state_id (int | str) –

    The state ID with which it was opened with. This is not the state name.

    Note

    Only the following state listener will execute upon calling this method:

    No other global or state listeners are called.

  • **kwargs (Any) –

    The keyword arguments to be passed on to the raised errors.

Raises:
game_state.errors.OverlayError
Raised when no state of state_id was found to close.
Return type:

None

async close_all_overlays()

Closes all opened overlay states.

Added in version 2.5.

Note

Only the following state listener executes upon calling this method:

For all overlay states, this is called in order from most recently opened to first opened.

No other global or state listeners are called.

Parameters:

**kwargs

The keyword arguments to be passed on to the raised errors.

Return type:

None

async open_overlay(state_name, state_id=None)
Overloads:
  • self, state_name (str), state_id (int) → int

  • self, state_name (str), state_id (str) → str

  • self, state_name (str), state_id (None) → int

Return type:

int | str

Opens a new overlay state without losing the context of the original state.

Added in version 2.5.

Note

Only the following state listener executes upon calling this method:

Warning

Although it is possible to use this method as a replacement to AsyncStateManager.change_state(), it is discouraged to do so as it progressively uses more memory if the overlay states are never cleared.

Parameters:
  • state_name (str) –

    The name of the state to use as an overlay.

  • state_id (Union[int, str, None]) –

    The ID bound to this overlay. As the overlay system allows you to open
    multiple overlay states of the same type, the manager needs to differentiate
    between them by using a unique ID.

    Note

    It’s recommended to use a string rather than an integer when assigning a custom ID. When no ID is supplied, the manager defaults to an incremental integer counter for its overlay elements, which can conflict with custom integer IDs.

Return type:

int | str