BaseGame Class

Overview

The BaseGame class is the abstract base class that provides the foundation for all games in the Unipress framework. It implements the core game loop, input handling, asset management, and common functionality that all one-button games share.

Class Definition

Base game class that all Unipress games must inherit from. Provides standardized difficulty system and input handling.

class unipress.core.base_game.GameMeta(name, bases, namespace, /, **kwargs)[source]

Bases: _WindowMetaclass, ABCMeta

Metaclass that combines arcade.Window and ABC metaclasses.

__init__(name: str, bases: tuple, dct: dict) None
__instancecheck__(instance)

Override for isinstance(instance, cls).

__subclasscheck__(subclass)

Override for issubclass(subclass, cls).

_abc_caches_clear()

Clear the caches (for debugging or testing).

_abc_registry_clear()

Clear the registry (for debugging or testing).

_dump_registry(file=None)

Debug helper to print the ABC registry.

mro()

Return a type’s method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

class unipress.core.base_game.BaseGame(game_name: str, width: int = 800, height: int = 600, title: str = 'Unipress Game', difficulty: int = None, input_key: int = 1, fullscreen: bool = None, lives: int = None, language: str = None)[source]

Bases: Window, ABC

Base class for all one-button games in Unipress.

Provides: - Standardized difficulty system (1-10 scale) - Configurable input handling (default: left mouse click) - Consistent game structure

__init__(game_name: str, width: int = 800, height: int = 600, title: str = 'Unipress Game', difficulty: int = None, input_key: int = 1, fullscreen: bool = None, lives: int = None, language: str = None)[source]

Initialize base game.

Parameters:
  • game_name – Name of the game for settings loading

  • width – Window width in pixels (ignored if fullscreen=True)

  • height – Window height in pixels (ignored if fullscreen=True)

  • title – Game window title

  • difficulty – Difficulty level 1-10 (None = use settings)

  • input_key – Input key/button (default: left mouse click)

  • fullscreen – Whether to start in fullscreen mode (None = use settings)

  • lives – Number of lives player starts with (None = use settings)

  • language – Language code for messages (None = use settings)

get_difficulty_settings() dict[str, Any][source]

Get difficulty-specific settings for the game. Override this method to customize difficulty scaling.

Returns:

Dictionary with difficulty-specific game settings

get_message(key: str, **kwargs) str[source]

Get localized message with parameter substitution.

play_sound_event(event_name: str, volume_override: float = None) Sound[source]

Play a standard sound event.

Parameters:
  • event_name – Name of the sound event (from STANDARD_SOUND_EVENTS)

  • volume_override – Optional volume override (0.0-1.0)

Returns:

Playing arcade.Sound or None if sound unavailable

play_custom_sound_event(event: SoundEvent, volume_override: float = None) Sound[source]

Play a custom sound event.

Parameters:
  • event – Custom SoundEvent definition

  • volume_override – Optional volume override (0.0-1.0)

Returns:

Playing arcade.Sound or None if sound unavailable

start_game_sound_timer() None[source]

Start non-blocking game start sound timer.

update_sound_timer(delta_time: float) None[source]

Update non-blocking sound timer.

complete_game_start() None[source]

Complete the game start sequence.

check_and_play_high_score_sound(new_score: int) None[source]

Check if new score beats high score and play sound once per game.

_complete_life_lost_continue() None[source]

Complete the life lost continuation sequence.

update_life_lost_effects(delta_time: float) None[source]

Update visual effects during life lost pause.

should_draw_player() bool[source]

Check if player should be drawn (handles blinking effect).

is_game_paused() bool[source]

Check if game is currently paused (life lost or game over).

on_mouse_press(x: float, y: float, button: int, modifiers: int) None[source]

Handle mouse press events.

on_key_press(key: int, modifiers: int) None[source]

Handle keyboard events (if needed for alternative input).

handle_life_lost_continue() bool[source]

Handle click during life lost pause - continue game only after blinking ends.

abstractmethod on_action_press() None[source]

Handle the main action (button press/click). This is where the core game logic responds to input. Must be implemented by each game.

abstractmethod reset_game() None[source]

Reset game to initial state. Must be implemented by each game.

reset_animations() None[source]

Reset all animations to prevent accumulated time. Override in subclass if needed.

start_game() None[source]

Start the game after user clicks.

lose_life() None[source]

Player loses a life. Pause game and wait for click to continue.

end_game() None[source]

End the game immediately (deprecated - use lose_life instead).

_restart_game() None[source]

Restart the game from end screen.

_exit_game() None[source]

Exit the game from end screen.

draw_heart(x: float, y: float, filled: bool = True) None[source]

Draw a smooth heart shape at the given position.

draw_hearts() None[source]

Draw hearts to represent remaining lives.

draw_ui() None[source]

Draw common UI elements (score, difficulty info, etc.).

CURSOR_CROSSHAIR: str = 'crosshair'

A crosshair mouse cursor.

CURSOR_DEFAULT = None

The default mouse cursor.

CURSOR_HAND: str = 'hand'

A pointing hand mouse cursor.

CURSOR_HELP: str = 'help'

A “help” mouse cursor; typically a question mark and an arrow.

CURSOR_NO: str = 'no'

A mouse cursor indicating that the selected operation is not permitted.

CURSOR_SIZE: str = 'size'

A mouse cursor indicating the element can be resized.

CURSOR_SIZE_DOWN: str = 'size_down'

A mouse cursor indicating the element can be resized from the bottom border.

CURSOR_SIZE_DOWN_LEFT: str = 'size_down_left'

A mouse cursor indicating the element can be resized from the lower-left corner.

CURSOR_SIZE_DOWN_RIGHT: str = 'size_down_right'

A mouse cursor indicating the element can be resized from the lower-right corner.

CURSOR_SIZE_LEFT: str = 'size_left'

A mouse cursor indicating the element can be resized from the left border.

CURSOR_SIZE_LEFT_RIGHT: str = 'size_left_right'

A mouse cursor indicating the element can be resized horizontally.

CURSOR_SIZE_RIGHT: str = 'size_right'

A mouse cursor indicating the element can be resized from the right border.

CURSOR_SIZE_UP: str = 'size_up'

A mouse cursor indicating the element can be resized from the top border.

CURSOR_SIZE_UP_DOWN: str = 'size_up_down'

A mouse cursor indicating the element can be resized vertically.

CURSOR_SIZE_UP_LEFT: str = 'size_up_left'

A mouse cursor indicating the element can be resized from the upper-left corner.

CURSOR_SIZE_UP_RIGHT: str = 'size_up_right'

A mouse cursor indicating the element can be resized from the upper-right corner.

CURSOR_TEXT: str = 'text'

A text input mouse cursor (I-beam).

CURSOR_WAIT: str = 'wait'

A “wait” mouse cursor; typically an hourglass or watch.

CURSOR_WAIT_ARROW: str = 'wait_arrow'

The “wait” mouse cursor combined with an arrow.

WINDOW_STYLE_BORDERLESS: str = 'borderless'

A window style without any decoration.

WINDOW_STYLE_DEFAULT: None = None

The default window style.

WINDOW_STYLE_DIALOG: str = 'dialog'

The window style for pop-up dialogs.

WINDOW_STYLE_OVERLAY: str = 'overlay'

A window style for transparent, topmost, click-through-able overlays

WINDOW_STYLE_TOOL: str = 'tool'

The window style for tool windows.

WINDOW_STYLE_TRANSPARENT: str = 'transparent'

A window style for transparent, interactable windows

_create() None

Internal method to create the window.

_create_cursor_from_image(cursor: ImageMouseCursor) c_ulong

Creates platform cursor from an ImageCursor instance.

_dispatch_frame(delta_time: float) None

To handle the de-syncing of on_draw and on_update that can occur when the events aren’t linked. Dispatch frame keeps them in sync by always ensuring on_draw happens along-side an on_update. This requires that the draw frequencies is less than or equal to the update frequency.

This only works because pyglet will only dispatch events after the call rate, or longer. This means if the update rate and draw rate are equal they will both always be called. The modulus on the accumulated draw time means that when the update rate is greater than the draw rate no time is lost.

Parameters:

delta_time – The amount of time since the last update.

_dispatch_updates(delta_time: float) None

Internal function that is scheduled with Pyglet’s clock, this function gets run by the clock, and dispatches the on_update events.

It also accumulates time and runs fixed updates until the Fixed Clock catches up to the global clock

Parameters:

delta_time – Time interval since the last time the function was called in seconds.

_get_handlers(args: list, kwargs: dict) Generator[tuple[str, Callable], None, None]

Implement handler matching on arguments for set_handlers and remove_handlers.

_on_resize(width: int, height: int) Literal[True] | None

The internal method called when the window is resized.

The purpose of this method is mainly setting the viewport to the new size of the window. Users should override on_resize() instead. This method is called first.

Parameters:
  • width – New width of the window

  • height – New height of the window

_remove_handler(name: str, handler: Callable) None

Used internally to remove all handler instances for the given event name.

This is normally called from a dead WeakMethod to remove itself from the event stack.

static _translate_button(value: int) int

Translate mouse button values to match mouse constants.

Given a Xevent.xbutton.button value, convert it to the mouse contants defined in :py:module:`~pyglet.window.mouse`. This means shifting the value, and also skipping over values of 4~7, which are used for boolean scrolling.

activate() None

Activate this window.

property aspect_ratio: float

The aspect ratio of the window. Read-Only.

property background_color: Color

Get or set the background color for this window. This affects what color the window will contain when clear() is called.

Examples:

# Use Arcade's built in Color values
window.background_color = arcade.color.AMAZON

# Set the background color with a custom Color instance
MY_RED = arcade.types.Color(255, 0, 0)
window.background_color = MY_RED

# Set the background color directly from an RGBA tuple
window.background_color = 255, 0, 0, 255

# Set the background color directly from an RGB tuple
# RGB tuples will assume 255 as the opacity / alpha value
window.background_color = 255, 0, 0
property caption: str

The window caption (title). Read-only.

property center: tuple[float, float]

Returns center coordinates of the window

Equivalent to (self.width / 2, self.height / 2).

center_window() None

Center the window on your desktop.

property center_x: float

Returns the center x-coordinate of the window.

Equivalent to self.width / 2.

property center_y: float

Returns the center y-coordinate of the window.

Equivalent to self.height / 2.

clear(color: tuple[int, int, int] | tuple[int, int, int, int] | None = None, color_normalized: tuple[float, float, float, float] | None = None, viewport: tuple[int, int, int, int] | None = None) None

Clears the window with the configured background color set through background_color.

Parameters:
  • color

    Override the current background color with one of the following:

    1. A Color instance

    2. A 3 or 4-length RGB/RGBA tuple of byte values (0 to 255)

  • color_normalized – override the current background color using normalized values (0.0 to 1.0). For example, (1.0, 0.0, 0.0, 1.0) making the window contents red.

  • viewport – The area of the window to clear. By default, the entire window is cleared. The viewport format is (x, y, width, height).

close() None

Close the Window.

property config: DisplayConfig

A GL config describing the context of this window. Read-only.

property context: Context

The OpenGL context attached to this window. Read-only.

property ctx: ArcadeContext

The OpenGL context for this window.

This context instance provides access to a powerful set of features for lower level OpenGL programming. It is also used internally by Arcade to manage OpenGL resources.

property current_camera: Projector

Get or set the current camera.

This represents the projector currently being used to define the projection and view matrices.

property current_view: View | None

The currently active view.

To set a different view, call show_view().

property default_camera: DefaultProjector

The default camera for the window.

This is an extremely simple camera simply responsible for maintaining the default projection and viewport.

property delta_time: float

Shortcut for the global clock’s delta_time.

dispatch_event(*args: Any) None

Dispatch an event to the attached event handlers.

The event is propagated to all registered event handlers in the stack, starting and the top and going down. If any registered event handler returns EVENT_HANDLED, no further handlers down the stack will receive this event.

This method has several possible return values. If any event hander has returned EVENT_HANDLED, then this method will also return EVENT_HANDLED. If not, this method will return EVENT_UNHANDLED. If there were no events registered to receive this event, False is returned.

Returns:

EVENT_HANDLED if any event handler returned EVENT_HANDLED; EVENT_UNHANDLED if one or more event handlers were invoked without any of them returning EVENT_HANDLED; False if no event handlers were registered.

dispatch_events() None

Dispatch events

dispatch_pending_events() None
dispatch_platform_event(e: struct__XEvent) None
dispatch_platform_event_view(e: struct__XEvent) None
property display: Display

The display this window belongs to. Read-only.

property dpi: int

DPI values of the Window.

Read only.

draw(dt: float) None

Redraw the Window contents.

This method will first call the `switch_to() method to make the GL context current. It then dispatches the on_draw() and on_refresh() events. Finally, it calls the flip() method to swap the front and back OpenGL buffers.

draw_mouse_cursor() None

Draw the custom mouse cursor.

If the current mouse cursor has drawable set, this method is called before the buffers are flipped to render it.

There is little need to override this method; instead, subclass MouseCursor and provide your own draw() method.

event(*args: Any) Callable

Function decorator for an event handler.

If the function or method name matches the event name, the decorator can be added without arguments. Likewise, if the name does not match, you can provide the target event name by passing it as an argument.

Name matches:

win = window.Window()

@win.event
def on_resize(self, width, height):
    # ...

Name does not match:

@win.event('on_resize')
def foo(self, width, height):
    # ...
event_types: list = ['on_key_press', 'on_key_release', 'on_text', 'on_text_motion', 'on_text_motion_select', 'on_mouse_motion', 'on_mouse_drag', 'on_mouse_press', 'on_mouse_release', 'on_mouse_scroll', 'on_mouse_enter', 'on_mouse_leave', 'on_close', 'on_expose', '_on_internal_resize', '_on_internal_scale', 'on_resize', 'on_scale', 'on_move', 'on_activate', 'on_deactivate', 'on_show', 'on_hide', 'on_context_lost', 'on_context_state_lost', 'on_file_drop', 'on_draw', 'on_refresh']
property fixed_delta_time: float

The configured fixed update rate

property fixed_time: float

Shortcut to the fixed clock’s time.

This is the time in seconds since the application started but updated at a fixed rate.

flip() None

Present the rendered content to the screen.

This is not necessary to call when using the standard standard event loop. The event loop will automatically call this method after on_draw has been called.

Window framebuffers normally have a back and front buffer meaning they are “double buffered”. Content is always drawn into the back buffer while the front buffer contains the previous frame. Swapping the buffers makes the back buffer visible and hides the front buffer. This is done to prevent flickering and tearing.

This method also garbage collects OpenGL resources if there are any dead resources to collect. If you override this method, make sure to call the super method to ensure that the garbage collection is done.

property fullscreen: bool

True if the window is currently fullscreen. Read-only.

get_caption() str
get_clipboard_text() str

Access the system clipboard and attempt to retrieve text.

Returns:

A string from the clipboard. String will be empty if no text found.

get_framebuffer_size() tuple[int, int]

Return the size in actual pixels of the Window framebuffer.

When using HiDPI screens, the size of the Window’s framebuffer can be higher than that of the Window size requested. If you are performing operations that require knowing the actual number of pixels in the window, this method should be used instead of Window.get_size(). For example, setting the Window projection or setting the glViewport size.

Returns:

The width and height of the Window’s framebuffer, in pixels.

get_location() tuple[int, int]

Get the current X/Y coordinates of the window.

get_pixel_ratio() float

Return the framebuffer/window size ratio.

Some platforms and/or window systems support subpixel scaling, making the framebuffer size larger than the window size. Retina screens on OS X and Gnome on Linux are some examples.

On a Retina systems the returned ratio would usually be 2.0 as a window of size 500 x 500 would have a framebuffer of 1000 x 1000. Fractional values between 1.0 and 2.0, as well as values above 2.0 may also be encountered.

Deprecated:

Use Window.scale.

get_requested_size() tuple[int, int]

Return the size of the window without any scaling taken into effect.

This does not include the windows’ border or title bar.

Returns:

The width and height of the window, in pixels.

get_single_property(window: xlib.Window, atom_property: xlib.Atom, atom_type: int) tuple[_Pointer[c_ubyte], int, int]

Returns the length, data, and actual atom of a window property.

get_size() tuple[int, int]

Get the size of the window.

get_system_mouse_cursor(name) MouseCursor

Get the system mouse cursor

has_exit: bool = False

True if the user has attempted to close the window.

Deprecated:

Windows are closed immediately by the default on_close() handler when pyglet.app.event_loop is being used.

property height: int

The height of the window, in pixels. Read-write.

hide_view() None

Hide the currently active view (if any).

This is only necessary if you don’t want an active view falling back to the window’s event handlers. It’s not necessary to call when changing the active view.

invalid: bool = True

Window display contents validity. The pyglet.app event loop examines every window each iteration and only dispatches the on_draw() event to windows that have invalid set. By default, windows always have invalid set to True.

You can prevent redundant redraws by setting this variable to False in the window’s on_draw() handler, and setting it to True again in response to any events that actually do require a window contents update.

Type:

bool

Added in version 1.1.

maximize() None

Maximize the window.

minimize() None

Minimize the window.

on_action(action_name: str, state) None

Called when an action is dispatched. This is related to the input manager / controller support.

Parameters:
  • action_name – The name of the action

  • state – The state of the action

on_close() None

Default on_close handler.

on_draw() Literal[True] | None

Override this function to add your custom drawing code.

This method is usually called 60 times a second unless another update rate has been set. Should be called after on_update().

This function should normally start with a call to clear() to clear the screen.

on_fixed_update(delta_time: float)

Called for each fixed update. This is useful for physics engines and other systems that should update at a constant rate.

Parameters:

delta_time – Time interval since the last time the function was called in seconds.

on_key_release(symbol: int, modifiers: int) Literal[True] | None

Called once when a key gets released.

Override this function to add key release functionality.

Situations that require handling key releases include:

  • Rhythm games where a note must be held for a certain amount of time

  • ‘Charging up’ actions that change strength depending on how long a key was pressed

  • Showing which keys are currently pressed down

Parameters:
  • symbol (int) – Key that was released

  • modifiers (int) – Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) active during this event. See keyboard_modifiers.

on_mouse_drag(x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int) Literal[True] | None

Called repeatedly while the mouse moves with a button down.

Override this function to handle dragging.

Parameters:
  • x – x position of mouse

  • y – y position of mouse

  • dx – Change in x since the last time this method was called

  • dy – Change in y since the last time this method was called

  • buttons – Which button is pressed

  • modifiers – Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) active during this event. See keyboard_modifiers.

on_mouse_enter(x: int, y: int) Literal[True] | None

Called once whenever the mouse enters the window area on screen.

This event will not be triggered if the mouse is currently being dragged.

Parameters:
  • x – The x position the mouse entered the window

  • y – The y position the mouse entered the window

on_mouse_leave(x: int, y: int) Literal[True] | None

Called once whenever the mouse leaves the window area on screen.

This event will not be triggered if the mouse is currently being dragged. Note that the coordinates of the mouse pointer will be outside of the window rectangle.

Parameters:
  • x – The x position the mouse entered the window

  • y – The y position the mouse entered the window

on_mouse_motion(x: int, y: int, dx: int, dy: int) Literal[True] | None

Called repeatedly while the mouse is moving in the window area.

Override this function to respond to changes in mouse position.

Parameters:
  • x – x position of mouse within the window in pixels

  • y – y position of mouse within the window in pixels

  • dx – Change in x since the last time this method was called

  • dy – Change in y since the last time this method was called

on_mouse_release(x: int, y: int, button: int, modifiers: int) Literal[True] | None

Called once whenever a mouse button gets released.

Override this function to respond to mouse button releases. This may be useful when you want to use the duration of a mouse click to affect gameplay.

Parameters:
  • x – x position of mouse

  • y – y position of mouse

  • button

    What button was hit. One of:

    • arcade.MOUSE_BUTTON_LEFT

    • arcade.MOUSE_BUTTON_RIGHT

    • arcade.MOUSE_BUTTON_MIDDLE

  • modifiers – Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) active during this event. See keyboard_modifiers.

on_mouse_scroll(x: int, y: int, scroll_x: float, scroll_y: float) Literal[True] | None

Called repeatedly while a mouse scroll wheel moves.

Override this function to respond to scroll events. The scroll arguments may be positive or negative to indicate direction, but the units are unstandardized. How many scroll steps you receive may vary wildly between computers depending a number of factors, including system settings and the input devices used (i.e. mouse scrollwheel, touch pad, etc).

Warning

Not all users can scroll easily!

Only some input devices support horizontal scrolling. Standard vertical scrolling is common, but some laptop touch pads are hard to use.

This means you should be careful about how you use scrolling. Consider making it optional to maximize the number of people who can play your game!

Parameters:
  • x – x position of mouse

  • y – y position of mouse

  • scroll_x – Number of steps scrolled horizontally since the last call of this function

  • scroll_y – Number of steps scrolled vertically since the last call of this function

on_resize(width: int, height: int) Literal[True] | None

Override this method to add custom actions when the window is resized.

An internal _on_resize is called first adjusting the viewport to the new size of the window so there is no need to call `super().on_resize(width, height)`.

Parameters:
  • width – New width of the window

  • height – New height of the window

on_scale(scale: float, dpi: int) Literal[True] | None

A default scale event handler.

This default handler is called if the screen or system’s DPI changes during runtime.

on_update(delta_time: float) bool | None

This method can be implemented and is reserved for game logic. Move sprites. Perform collision checks and other game logic. This method is called every frame before on_draw().

The delta_time can be used to make sure the game runs at the same speed, no matter the frame rate.

Parameters:

delta_time – Time interval since the last time the function was called in seconds.

static parse_filenames(decoded_string: str) list[str]

All of the filenames from file drops come as one big string with some special characters (%20), this will parse them out.

pop_handlers() None

Pop the top level of event handlers off the stack.

property projection: Mat4

The OpenGL window projection matrix. Read-write.

This matrix is used to transform vertices when using any of the built-in drawable classes. view is done first, then projection.

The default projection matrix is orthographic (2D), but a custom Mat4 instance can be set. Alternatively, you can supply a flat tuple of 16 values.

(2D), but can be changed to any 4x4 matrix desired. :see: Mat4.

push_handlers(*args: Any, **kwargs: Any) None

Push a new level onto the handler stack, and add 0 or more handlers.

This method first pushes a new level to the top of the handler stack. It then attaches any handlers that were passed to this new level.

If keyword arguments are given, they name the event type to attach. Otherwise, a callable’s __name__ attribute will be used. Any other object may also be specified, in which case it will be searched for callables with event names.

property rect: Rect

Return a Rect describing the size of the window.

classmethod register_event_type(name: str) str

Register an event type with the dispatcher.

Before dispatching events, they must first be registered by name. Registering event types allows the dispatcher to validate event handler names as they are attached, and to search attached objects for suitable handlers.

remove_handler(name: str, handler: Callable) None

Remove a single event handler.

The given event handler is removed from the first handler stack frame it appears in. The handler must be the exact same callable as passed to set_handler, set_handlers or push_handlers(); and the name must match the event type it is bound to.

No error is raised if the event handler is not set.

remove_handlers(*args: Any, **kwargs: Any) None

Remove event handlers from the event stack.

See push_handlers() for the accepted argument types. All handlers are removed from the first stack frame that contains any of the given handlers. No error is raised if any handler does not appear in that frame, or if no stack frame contains any of the given handlers.

If the stack frame is empty after removing the handlers, it is removed from the stack. Note that this interferes with the expected symmetry of push_handlers() and pop_handlers().

property resizeable: bool

True if the window is resizable. Read-only.

run(view: View | None = None) None

Run the event loop. Optionally start with a specified view.

After the window has been set up, and the event hooks are in place, this is usually one of the last commands on the main program. This is a blocking function starting pyglet’s event loop meaning it will start to dispatch events such as on_draw and on_update.

Parameters:

view – The view to display when starting the run. Defaults to None.

property scale: float

The scale of the window factoring in DPI.

Read only.

property screen: Screen

The screen this window is fullscreen in. Read-only.

set_caption(caption) None

Set the caption/title of the window.

set_clipboard_text(text: str) None

Access the system clipboard and set a text string as the clipboard data.

This will clear the existing clipboard.

set_draw_rate(rate: float) None

Set how often the on_draw function should be run. The draw rate cannot currently be faster than the update rate.

For example:

# Set the draw rate to 60 frames per second.
set.set_draw_rate(1 / 60)
set_exclusive_keyboard(exclusive=True) None

Capture all keyboard input.

set_exclusive_mouse(exclusive=True) None

Capture the mouse.

set_fullscreen(fullscreen: bool = True, screen=None, mode: ScreenMode | None = None, width: float | None = None, height: float | None = None) None

Change the fullscreen status of the window.

In most cases you simply want:

# Enter fullscreen mode
window.set_fullscreen(True)
# Leave fullscreen mode
window.set_fullscreen(False)

When entering fullscreen mode the window will resize to the screen’s resolution. When leaving fullscreen mode the window will resize back to the size it was before entering fullscreen mode.

Parameters:
  • fullscreen – Should we enter or leave fullscreen mode?

  • screen – Which screen should we display on? See get_screens()

  • mode – The screen will be switched to the given mode. The mode must have been obtained by enumerating Screen.get_modes. If None, an appropriate mode will be selected from the given width and height.

  • width – Override the width of the window. Will be rounded to int.

  • height – Override the height of the window. Will be rounded to int.

set_handler(name: str, handler: Callable) None

Attach a single event handler.

set_handlers(*args: Any, **kwargs: Any) None

Attach one or more event handlers to the top level of the handler stack.

See push_handlers() for the accepted argument types.

set_icon(*images: ImageData) None

Set the window icon.

If multiple images are provided, one with an appropriate size will be selected (if the correct size is not provided, the image will be scaled).

Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and 128x128 (Mac only).

set_location(x, y) None

Set location of the window.

set_maximum_size(width: int, height: int) None

Sets the maximum size of the window.

This will limit how large the window can be resized.

Parameters:
  • width – Maximum width

  • height – Maximum height

set_minimum_size(width: int, height: int) None

Set the minimum size of the window.

This will limit how small the window can be resized.

Parameters:
  • width – Minimum width

  • height – Minimum height

set_mouse_cursor(cursor: MouseCursor | None = None) None

Change the appearance of the mouse cursor.

The appearance of the mouse cursor is only changed while it is within this window.

Parameters:

cursor – The cursor to set, or None to restore the default cursor.

set_mouse_platform_visible(platform_visible=None) None

Warning

You are probably looking for set_mouse_visible()!

This is a lower level function inherited from the pyglet window.

For more information on what this means, see the documentation for pyglet.window.Window.set_mouse_platform_visible().

set_mouse_position(x: int, y: int) None
set_mouse_visible(visible: bool = True) None

Set whether to show the system’s cursor while over the window

By default, the system mouse cursor is visible whenever the mouse is over the window. To hide the cursor, pass False to this function. Pass True to make the cursor visible again.

The window will continue receiving mouse events while the cursor is hidden, including movements and clicks. This means that functions like on_mouse_motion() and t’on_mouse_press() will continue to work normally.

You can use this behavior to visually replace the system mouse cursor with whatever you want. One example is a game character that is always at the most recent mouse position in the window.

Note

Advanced users can try using system cursor state icons

It may be possible to use system icons representing cursor interaction states such as hourglasses or resize arrows by using features :class:~arcade.Window inherits from the underlying pyglet window class. See the pyglet overview on cursors for more information.

Parameters:

visible – Whether to hide the system mouse cursor

set_size(width: int, height: int) None

Resize the window.

Parameters:
  • width – New width of the window

  • height – New height of the window

set_update_rate(rate: float) None

Set how often the on_update function should be dispatched. For example:

# Set the update rate to 60 times per second.
self.set_update_rate(1 / 60)
Parameters:

rate – Update frequency in seconds

set_visible(visible: bool = True)

Set if the window should be visible or not.

Parameters:

visible (bool) – Should the window be visible?

set_vsync(vsync: bool) None

Set if we sync our draws to the monitors vertical sync rate.

set_wm_class(name: str) None
show_view(new_view: View) None

Set the currently active view.

This will hide the current view and show the new view in the next frame.

This is not a blocking call. It will simply point to the new view and return immediately.

Calling this function is the same as setting the arcade.Window.current_view attribute.

Parameters:

new_view – The view to activate.

property size: tuple[int, int]

The size of the window. Read-Write.

property style: str

The window style; one of the WINDOW_STYLE_* constants. Read-only.

switch_to() None

Switch the this window context.

This is normally only used in multi-window applications.

test(frames: int = 10) None

Used by unit test cases. Runs the event loop a few times and stops.

Parameters:

frames – How many frames to run the event loop for.

property time: float

Shortcut to the global clock’s time.

This is the time in seconds since the application started.

use() None

Make the window the target for drawing.

The window will always be the target for drawing unless offscreen framebuffers are used in the application.

This simply binds the window’s framebuffer.

property view: Mat4

The OpenGL window view matrix. Read-write.

This matrix is used to transform vertices when using any of the built-in drawable classes. view is done first, then projection.

The default view is an identity matrix, but a custom Mat4 instance can be set. Alternatively, you can supply a flat tuple of 16 values.

property viewport: tuple[int, int, int, int]

Get/set the viewport of the window.

This will define what area of the window is rendered into. The values are x, y, width, height. The value will normally be (0, 0, screen width, screen height).

In most case you don’t want to change this value manually and instead rely on the cameras.

property visible: bool

True if the window is currently visible. Read-only.

property vsync: bool

True if buffer flips are synchronised to the screen’s vertical retrace. Read-only.

property width: int

The width of the window, in pixels. Read-write.

closed

Indicates if the window was closed

headless: bool

If True, the window is running in headless mode.

keyboard: pyglet.window.key.KeyStateHandler | None

A pyglet KeyStateHandler that can be used to poll the state of the keyboard.

Example:

if self.window.keyboard[key.SPACE]:
    print("The space key is currently being held down.")
mouse: pyglet.window.mouse.MouseStateHandler | None

A pyglet MouseStateHandler that can be used to poll the state of the mouse.

Example:

if self.window.mouse.LEFT:
    print("The left mouse button is currently being held down.")
print(
    "The mouse is at position "
    f"{self.window.mouse["x"]}, {self.window.mouse["y"]}"
)

Inheritance

  • Parent Class: arcade.Window

  • Abstract Methods: Must be implemented by subclasses

  • Concrete Methods: Common functionality provided by base class

Core Features

One-Button Input Constraint

All games inherit the strict one-button input constraint, ensuring accessibility and simplicity across the entire game collection.

Asset Management

Integrated asset loading and caching for sprites, sounds, and animations with JSON metadata support.

Sound System

Event-driven audio system with OGG format support and volume control.

Settings Integration

Hierarchical TOML-based configuration system with game-specific settings.

Logging

Structured JSON logging with Loguru for debugging and monitoring.

Abstract Methods

setup()

Signature: def setup(self) -> None

Description: Initialize game-specific components and state.

Required Implementation: Yes

Example:

def setup(self) -> None:
    """Initialize game-specific components."""
    self.player = arcade.Sprite(":resources:images/player.png")
    self.obstacles = arcade.SpriteList()
    self.score = 0
    self.lives = 3

update(delta_time: float)

Signature: def update(self, delta_time: float) -> None

Description: Update game logic and state.

Parameters: - delta_time (float): Time elapsed since last update in seconds

Required Implementation: Yes

Example:

def update(self, delta_time: float) -> None:
    """Update game logic."""
    self.player.update()
    self.obstacles.update()

    # Check collisions
    if arcade.check_for_collision_with_list(self.player, self.obstacles):
        self.lives -= 1
        self.sound_manager.play("player", "collision")

on_draw()

Signature: def on_draw(self) -> None

Description: Render the game screen.

Required Implementation: Yes

Example:

def on_draw(self) -> None:
    """Render the game screen."""
    arcade.start_render()

    # Draw background
    arcade.draw_lrwh_rectangle_textured(
        0, 0, self.width, self.height, self.background
    )

    # Draw game objects
    self.player.draw()
    self.obstacles.draw()

    # Draw UI
    self.draw_ui()

Concrete Methods

Input Handling

on_key_press(key: int, modifiers: int)

Signature: def on_key_press(self, key: int, modifiers: int) -> None

Description: Handle key press events. Implements one-button constraint.

Parameters: - key (int): Key code - modifiers (int): Modifier keys (Ctrl, Alt, etc.)

Implementation: Provided by base class

Behavior: - Only responds to spacebar and mouse clicks - Ignores all other input - Logs input events for debugging

on_mouse_press(x: int, y: int, button: int, modifiers: int)

Signature: def on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> None

Description: Handle mouse press events.

Parameters: - x (int): Mouse X coordinate - y (int): Mouse Y coordinate - button (int): Mouse button - modifiers (int): Modifier keys

Implementation: Provided by base class

Asset Management

load_assets()

Signature: def load_assets(self) -> None

Description: Load game assets using the asset manager.

Implementation: Provided by base class

Features: - Automatic asset discovery - JSON metadata loading - Caching for performance - Error handling for missing assets

get_sprite(name: str) -> arcade.Sprite

Signature: def get_sprite(self, name: str) -> arcade.Sprite

Description: Get a sprite from the asset manager.

Parameters: - name (str): Asset name

Returns: arcade.Sprite - Loaded sprite

Example:

player_sprite = self.get_sprite("player_idle")

Sound Management

play_sound(category: str, name: str)

Signature: def play_sound(self, category: str, name: str) -> None

Description: Play a sound effect.

Parameters: - category (str): Sound category (e.g., “player”, “ui”) - name (str): Sound name

Example:

self.play_sound("player", "jump")
self.play_sound("ui", "button_click")

set_volume(volume: float)

Signature: def set_volume(self, volume: float) -> None

Description: Set master volume (0.0 to 1.0).

Parameters: - volume (float): Volume level

Settings Management

get_setting(section: str, key: str, default=None)

Signature: def get_setting(self, section: str, key: str, default=None) -> Any

Description: Get a setting value.

Parameters: - section (str): Settings section - key (str): Setting key - default: Default value if not found

Returns: Setting value

Example:

difficulty = self.get_setting("game", "difficulty", 3)
volume = self.get_setting("audio", "volume", 0.8)

set_setting(section: str, key: str, value: Any)

Signature: def set_setting(self, section: str, key: str, value: Any) -> None

Description: Set a setting value.

Parameters: - section (str): Settings section - key (str): Setting key - value: Setting value

Game State Management

start_game()

Signature: def start_game(self) -> None

Description: Start the game.

Implementation: Provided by base class

Features: - Initialize game state - Start game loop - Load assets - Set up logging

end_game()

Signature: def end_game(self) -> None

Description: End the game.

Implementation: Provided by base class

Features: - Save high scores - Clean up resources - Log game statistics

reset_game()

Signature: def reset_game(self) -> None

Description: Reset game state.

Implementation: Provided by base class

Features: - Reset score and lives - Clear game objects - Restart game loop

UI Rendering

draw_ui()

Signature: def draw_ui(self) -> None

Description: Draw user interface elements.

Implementation: Provided by base class

Features: - Score display - Lives counter - Game status - Consistent styling

draw_text(text: str, x: int, y: int, color: arcade.Color, size: int = 20)

Signature: def draw_text(self, text: str, x: int, y: int, color: arcade.Color, size: int = 20) -> None

Description: Draw text with consistent styling.

Parameters: - text (str): Text to draw - x (int): X coordinate - y (int): Y coordinate - color (arcade.Color): Text color - size (int): Font size

Logging

log_event(event: str, data: dict = None)

Signature: def log_event(self, event: str, data: dict = None) -> None

Description: Log a game event.

Parameters: - event (str): Event name - data (dict): Event data

Example:

self.log_event("player_jump", {"height": jump_height})
self.log_event("obstacle_hit", {"obstacle_type": "fire"})

Configuration

Settings Structure

The BaseGame class expects the following settings structure:

[display]
fullscreen = true
width = 1920
height = 1080

[audio]
enabled = true
volume = 0.8

[game]
difficulty = 3
lives = 3

[logging]
level = "INFO"
format = "json"

Asset Structure

Assets should be organized as follows:

assets/
├── games/
│   └── game_name/
│       ├── sprites/
│       ├── sounds/
│       └── animations/
└── global/
    ├── ui/
    └── system/

Usage Example

from unipress.core.base_game import BaseGame
import arcade

class MyGame(BaseGame):
    def setup(self) -> None:
        """Initialize game components."""
        self.player = self.get_sprite("player")
        self.obstacles = arcade.SpriteList()
        self.score = 0

    def update(self, delta_time: float) -> None:
        """Update game logic."""
        self.player.update()
        self.obstacles.update()

        # Game logic here

    def on_draw(self) -> None:
        """Render the game."""
        arcade.start_render()
        self.player.draw()
        self.obstacles.draw()
        self.draw_ui()

def main():
    """Run the game."""
    game = MyGame()
    game.run()

if __name__ == "__main__":
    main()

Best Practices

  1. Implement Required Methods Always implement setup(), update(), and on_draw() methods.

  2. Use Asset Manager Load assets through the asset manager for consistent handling.

  3. Follow One-Button Constraint Only respond to spacebar and mouse clicks.

  4. Use Settings System Access configuration through the settings system.

  5. Log Important Events Log game events for debugging and analytics.

  6. Handle Errors Gracefully Use try-catch blocks for asset loading and game logic.