API Reference

Overview

This section contains the complete API documentation for all Unipress modules, automatically generated from docstrings in the source code.

Core Framework

Base Game Framework

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.

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"]}"
)
closed

Indicates if the window was closed

Asset Management

Asset Management System

Handles loading, caching, and management of game assets including: - Sprite images and animations - Sound effects and music - Background images and parallax layers - UI elements and fonts

class unipress.core.assets.AnimationFrame(texture: Texture, duration: float, hitbox: Dict[str, int] | None = None)[source]

Bases: object

Represents a single frame in an animation sequence.

__init__(texture: Texture, duration: float, hitbox: Dict[str, int] | None = None)[source]

Initialize animation frame.

Parameters:
  • texture – Arcade texture for this frame

  • duration – How long to display this frame (seconds)

  • hitbox – Optional collision box {“x”: int, “y”: int, “width”: int, “height”: int}

class unipress.core.assets.Animation(name: str, frames: List[AnimationFrame], loop: bool = True, next_animation: str | None = None)[source]

Bases: object

Manages a sequence of animation frames with timing and metadata.

__init__(name: str, frames: List[AnimationFrame], loop: bool = True, next_animation: str | None = None)[source]

Initialize animation.

Parameters:
  • name – Animation identifier

  • frames – List of animation frames

  • loop – Whether animation should loop

  • next_animation – Name of animation to play after this one finishes

update(delta_time: float) bool[source]

Update animation playback.

Parameters:

delta_time – Time elapsed since last update

Returns:

True if animation changed frames

get_current_texture() Texture[source]

Get texture for current frame.

get_current_hitbox() Dict[str, int][source]

Get hitbox for current frame.

reset() None[source]

Reset animation to beginning.

class unipress.core.assets.AssetManager(base_path: Path = None)[source]

Bases: object

Central manager for all game assets with caching and lazy loading.

__init__(base_path: Path = None)[source]

Initialize asset manager.

Parameters:

base_path – Base path for assets (defaults to unipress/assets)

get_texture(path: str, game_name: str = None) Texture | None[source]

Load and cache a texture.

Parameters:
  • path – Relative path to image file

  • game_name – Game name for game-specific assets (None for global)

Returns:

Loaded texture or None if failed

load_animation(animation_name: str, game_name: str) Animation | None[source]

Load animation from JSON metadata and image files.

Parameters:
  • animation_name – Name of animation (matches JSON filename without _anim.json)

  • game_name – Game name for asset location

Returns:

Loaded animation or None if failed

get_sound(path: str, game_name: str = None) Sound | None[source]

Load and cache a sound effect.

Parameters:
  • path – Relative path to sound file

  • game_name – Game name for game-specific sounds (None for global)

Returns:

Loaded sound or None if failed

preload_game_assets(game_name: str, asset_list: List[str]) None[source]

Preload a list of assets for a game to improve performance.

Parameters:
  • game_name – Name of the game

  • asset_list – List of asset paths to preload

clear_cache(game_name: str = None) None[source]

Clear cached assets to free memory.

Parameters:

game_name – Clear only assets for specific game (None clears all)

get_cache_info() Dict[str, int][source]

Get information about cached assets.

unipress.core.assets.get_asset_manager() AssetManager[source]

Get the global asset manager instance.

Returns:

Global AssetManager instance

unipress.core.assets.get_texture(path: str, game_name: str = None) Texture | None[source]

Get texture from global asset manager.

unipress.core.assets.load_animation(animation_name: str, game_name: str) Animation | None[source]

Load animation from global asset manager.

unipress.core.assets.get_sound(path: str, game_name: str = None) Sound | None[source]

Get sound from global asset manager.

unipress.core.assets.preload_assets(game_name: str, asset_list: List[str]) None[source]

Preload assets using global asset manager.

unipress.core.assets.clear_assets(game_name: str = None) None[source]

Clear assets using global asset manager.

Sound System

Comprehensive sound system for Unipress games.

This module provides centralized sound management with volume control, event-based audio feedback, and game startup synchronization.

class unipress.core.sound.SoundCategory(*values)[source]

Bases: Enum

Sound event categories for volume control and organization.

GAME_START = 'game_start'
PLAYER_ACTION = 'player_action'
SUCCESS = 'success'
FAILURE = 'failure'
ACHIEVEMENT = 'achievement'
UI_FEEDBACK = 'ui_feedback'
AMBIENT = 'ambient'
classmethod __contains__(value)

Return True if value is in cls.

value is in cls if: 1) value is a member of cls, or 2) value is the value of one of the cls’s members. 3) value is a pseudo-member (flags)

classmethod __getitem__(name)

Return the member matching name.

classmethod __iter__()

Return members in definition order.

classmethod __len__()

Return the number of members (no aliases)

class unipress.core.sound.SoundEvent(category: SoundCategory, file_path: str, volume_multiplier: float = 1.0, global_sound: bool = False)[source]

Bases: object

Definition of a sound event with metadata.

category: SoundCategory
file_path: str
volume_multiplier: float = 1.0
global_sound: bool = False
__post_init__()[source]

Validate sound event parameters.

__init__(category: SoundCategory, file_path: str, volume_multiplier: float = 1.0, global_sound: bool = False) None
class unipress.core.sound.SoundManager(game_name: str, settings: Dict[str, Any])[source]

Bases: object

Centralized sound management for games with volume control and event handling.

__init__(game_name: str, settings: Dict[str, Any])[source]

Initialize sound manager for a specific game.

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

  • settings – Game settings dictionary

calculate_volume(event: SoundEvent, volume_override: float | None = None) float[source]

Calculate final volume for a sound event.

Parameters:
  • event – Sound event definition

  • volume_override – Optional volume override (0.0-1.0)

Returns:

Final volume level (0.0-1.0)

load_sound(event: SoundEvent) Sound | None[source]

Load a sound for the given event.

Parameters:

event – Sound event definition

Returns:

Loaded arcade.Sound or None if loading failed

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

Play a sound event with appropriate volume.

Parameters:
  • event – Sound event to play

  • volume_override – Optional volume override (0.0-1.0)

Returns:

Playing arcade.Sound or None if sound unavailable

wait_for_sound_completion(sound: Sound, timeout: float = 5.0) None[source]

Wait for a sound to complete playing.

Parameters:
  • sound – Sound to wait for

  • timeout – Maximum wait time in seconds

stop_all_sounds() None[source]

Stop all currently playing sounds.

preload_sounds(events: Dict[str, SoundEvent]) None[source]

Preload multiple sound events for better performance.

Parameters:

events – Dictionary of event_name -> SoundEvent mappings

Settings Management

Settings management for Unipress games.

Handles hierarchical settings loading with priority: 1. Constructor parameters (highest) 2. Game-specific settings 3. Global settings 4. Default values (lowest)

unipress.core.settings.get_default_settings() dict[str, Any][source]

Get hardcoded default settings.

unipress.core.settings.load_toml_file(file_path: str | Path) dict[str, Any][source]

Load TOML file safely, return empty dict if file doesn’t exist.

unipress.core.settings.merge_settings(base: dict[str, Any], override: dict[str, Any]) dict[str, Any][source]

Merge two settings dictionaries recursively.

unipress.core.settings.load_settings(game_name: str, **constructor_overrides) dict[str, Any][source]

Load settings with hierarchical priority.

Parameters:
  • game_name – Name of the game (e.g., “demo_jump”)

  • **constructor_overrides – Settings passed to BaseGame constructor

Returns:

Merged settings dictionary

unipress.core.settings.get_setting(settings: dict[str, Any], key_path: str, default: Any = None) Any[source]

Get setting value using dot notation.

Parameters:
  • settings – Settings dictionary

  • key_path – Dot-separated path (e.g., “game.difficulty”)

  • default – Default value if key not found

Returns:

Setting value or default

Logging System

Logger initialization and configuration for Unipress games. Provides centralized logging setup using Loguru with TOML configuration.

unipress.core.logger.init_logger(game_name: str = None, **overrides) None[source]

Initialize the logger with settings from TOML configuration.

Parameters:
  • game_name – Name of the game for per-game settings (optional)

  • **overrides – Direct setting overrides for logging configuration

unipress.core.logger.get_logger(name: str = None)[source]

Get a logger instance with optional name binding.

Parameters:

name – Optional name to bind to the logger (e.g., game name, module name)

Returns:

Configured logger instance

unipress.core.logger.log_game_event(event: str, **context)[source]

Log a game event with structured context.

unipress.core.logger.log_player_action(action: str, **context)[source]

Log a player action with structured context.

unipress.core.logger.log_performance(metric: str, value: float, unit: str = '', **context)[source]

Log a performance metric.

unipress.core.logger.log_error(error: Exception, context: str = '', **extra_context)[source]

Log an error with full context and traceback.

High Scores

High Score Persistence System

Manages high scores for all games using JSON file storage. Provides simple interface for getting, setting, and updating high scores.

class unipress.core.high_scores.HighScoreManager(scores_file: str = 'high_scores.json')[source]

Bases: object

Manages high scores for all games using JSON file storage.

__init__(scores_file: str = 'high_scores.json')[source]

Initialize high score manager.

Parameters:

scores_file – Path to JSON file for storing high scores

_load_scores() None[source]

Load high scores from JSON file.

_save_scores() None[source]

Save high scores to JSON file.

get_high_score(game_name: str) int[source]

Get high score for a game.

Parameters:

game_name – Name of the game

Returns:

High score for the game (0 if no score recorded)

set_high_score(game_name: str, score: int) bool[source]

Set high score for a game if it’s higher than current record.

Parameters:
  • game_name – Name of the game

  • score – New score to potentially record

Returns:

True if new high score was set, False otherwise

update_score(game_name: str, score: int) bool[source]

Update score and check if it’s a new high score.

Parameters:
  • game_name – Name of the game

  • score – Final score from game session

Returns:

True if new high score was achieved, False otherwise

get_all_scores() dict[str, int][source]

Get all high scores.

Returns:

Dictionary mapping game names to high scores

reset_high_score(game_name: str) None[source]

Reset high score for a specific game.

Parameters:

game_name – Name of the game to reset

reset_all_scores() None[source]

Reset all high scores.

unipress.core.high_scores.get_high_score_manager() HighScoreManager[source]

Get the global high score manager instance.

Returns:

Global HighScoreManager instance

unipress.core.high_scores.get_high_score(game_name: str) int[source]

Get high score for a game.

unipress.core.high_scores.update_high_score(game_name: str, score: int) bool[source]

Update high score if score is higher than current record.

unipress.core.high_scores.is_new_high_score(game_name: str, score: int) bool[source]

Check if score would be a new high score without updating.

Game Server

Game server for running games in Docker container. Provides HTTP API for launching different games.

unipress.core.game_server.run_game_in_thread(game_module: str, difficulty: int = 5) None[source]

Run game in separate thread to avoid blocking the server.

unipress.core.game_server.health() Dict[str, Any][source]

Health check endpoint.

unipress.core.game_server.run_game() Dict[str, Any][source]

Run a specific game.

unipress.core.game_server.stop_game() Dict[str, Any][source]

Stop currently running game.

unipress.core.game_server.game_status() Dict[str, Any][source]

Get current game status.

unipress.core.game_server.list_games() Dict[str, Any][source]

List available games.

unipress.core.game_server.main() None[source]

Start the game server.

Messages

Message loading system for internationalization.

Handles loading and merging of JSON message files with fallback support.

class unipress.core.messages.MessageLoader(language: str, game_name: str)[source]

Bases: object

Loads and manages localized messages from JSON files.

__init__(language: str, game_name: str)[source]

Initialize message loader.

Parameters:
  • language – Language code (e.g., “pl_PL”, “en_US”)

  • game_name – Name of the game for game-specific messages

_load_json_file(file_path: Path) dict[str, Any][source]

Load JSON file safely, return empty dict if file doesn’t exist.

_merge_messages(base: dict[str, Any], override: dict[str, Any]) dict[str, Any][source]

Merge two message dictionaries recursively.

_load_messages() None[source]

Load messages for the specified language with fallback.

_load_language_messages(locales_path: Path, language: str) dict[str, Any][source]

Load all message files for a specific language.

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

Get localized message with parameter substitution.

Parameters:
  • key – Dot-separated message key (e.g., “ui.score”)

  • **kwargs – Parameters for string formatting

Returns:

Formatted message string, or the key itself if not found

has_message(key: str) bool[source]

Check if a message key exists.

get_available_languages() list[str][source]

Get list of available language codes.

reload(language: str = None, game_name: str = None) None[source]

Reload messages with optionally different language or game.

unipress.core.messages.load_messages(language: str, game_name: str) MessageLoader[source]

Convenience function to create and return a MessageLoader.

Parameters:
  • language – Language code (e.g., “pl_PL”, “en_US”)

  • game_name – Name of the game

Returns:

Configured MessageLoader instance

Client Interface

Unipress Game Client Client for communicating with the game server running in Docker container.

class unipress.client.UnipressClient(server_url: str = 'http://localhost:5000')[source]

Bases: object

Client for Unipress game server.

__init__(server_url: str = 'http://localhost:5000')[source]

Initialize client.

Parameters:

server_url – URL of the game server (default: http://localhost:5000)

health_check() Dict[str, Any][source]

Check server health.

list_games() Dict[str, Any][source]

List available games.

run_game(game: str, difficulty: int = 5) Dict[str, Any][source]

Run a specific game.

Parameters:
  • game – Game name or module (e.g., “jumper”, “demo_jump”)

  • difficulty – Difficulty level 1-10 (default: 5)

stop_game() Dict[str, Any][source]

Stop currently running game.

game_status() Dict[str, Any][source]

Get current game status.

wait_for_game_completion(timeout: int = 300) bool[source]

Wait for current game to complete.

Parameters:

timeout – Maximum time to wait in seconds (default: 300)

Returns:

True if game completed, False if timeout

unipress.client.main()[source]

Example usage of the client.

Game Implementations

Demo Jump Game

Demo Jump Game - Simple one-button jumping game.

Click to make the player jump over incoming obstacles. Difficulty affects how much time you have to react to obstacles.

class unipress.games.demo_jump.game.Obstacle(x: float, y: float, width: float = 30, height: float = 50)[source]

Bases: object

Simple obstacle that moves from right to left.

__init__(x: float, y: float, width: float = 30, height: float = 50)[source]
update(delta_time: float) None[source]

Move obstacle left.

draw() None[source]

Draw obstacle as red rectangle.

collides_with(player_x: float, player_y: float, player_size: float) bool[source]

Check collision with player.

class unipress.games.demo_jump.game.DemoJumpGame(difficulty: int = None)[source]

Bases: BaseGame

Simple jumping game demo.

  • Click to jump

  • Avoid red obstacles

  • Score increases over time

  • Difficulty affects obstacle spacing (reaction time)

__init__(difficulty: int = 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, float | int][source]

Override to add game-specific difficulty settings.

reset_game() None[source]

Reset game state.

on_action_press() None[source]

Handle main action (jump or start/restart game).

on_update(delta_time: float) None[source]

Update game logic.

on_draw() None[source]

Draw the game.

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

_complete_life_lost_continue() None

Complete the life lost continuation sequence.

_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.

_exit_game() None

Exit the game from end screen.

_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.

_restart_game() None

Restart the game from end screen.

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.

check_and_play_high_score_sound(new_score: int) None

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

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.

complete_game_start() None

Complete the game start sequence.

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_heart(x: float, y: float, filled: bool = True) None

Draw a smooth heart shape at the given position.

draw_hearts() None

Draw hearts to represent remaining lives.

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.

draw_ui() None

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

end_game() None

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

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_message(key: str, **kwargs) str

Get localized message with parameter substitution.

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

handle_life_lost_continue() bool

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

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.

is_game_paused() bool

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

lose_life() None

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

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_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_press(key: int, modifiers: int) None

Handle keyboard events (if needed for alternative input).

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_press(x: float, y: float, button: int, modifiers: int) None

Handle mouse press events.

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.

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.

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

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

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

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

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().

reset_animations() None

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

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
should_draw_player() bool

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

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.

start_game() None

Start the game after user clicks.

start_game_sound_timer() None

Start non-blocking game start sound timer.

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.

update_life_lost_effects(delta_time: float) None

Update visual effects during life lost pause.

update_sound_timer(delta_time: float) None

Update non-blocking sound timer.

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.

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"]}"
)
closed

Indicates if the window was closed

unipress.games.demo_jump.game.main() None[source]

Run the demo game.

Jumper Game

Jumper Game - Enhanced version of demo_jump with sprites, animations and sounds.

A one-button jumping game where the player (animated running character) must jump over fire obstacles using sprite animations and sound effects with parallax scrolling background.

class unipress.games.jumper.game.BackgroundLayer(texture: Texture, scroll_speed: float, z_order: int)[source]

Bases: object

Represents a single parallax background layer.

__init__(texture: Texture, scroll_speed: float, z_order: int)[source]

Initialize background layer.

Parameters:
  • texture – Background texture

  • scroll_speed – Scrolling speed multiplier

  • z_order – Drawing order (lower = back, higher = front)

update(delta_time: float, base_speed: float) None[source]

Update layer scrolling position.

draw(window_width: int, window_height: int) None[source]

Draw the background layer with seamless tiling.

class unipress.games.jumper.game.AnimatedSprite(x: float, y: float, game_name: str)[source]

Bases: object

Sprite with animation support.

__init__(x: float, y: float, game_name: str)[source]

Initialize animated sprite.

Parameters:
  • x – Initial X position

  • y – Initial Y position

  • game_name – Game name for asset loading

set_animation(animation_name: str, force: bool = False) bool[source]

Set current animation.

Parameters:
  • animation_name – Name of animation to play

  • force – Force change even if same animation is playing

Returns:

True if animation was changed

update(delta_time: float) None[source]

Update sprite animation.

draw() None[source]

Draw the sprite at current animation frame.

get_hitbox() dict[source]

Get current hitbox for collision detection.

class unipress.games.jumper.game.Obstacle(x: float, y: float, speed: float, game_name: str)[source]

Bases: object

Fire obstacle with animation.

__init__(x: float, y: float, speed: float, game_name: str)[source]

Initialize obstacle.

draw() None[source]

Draw the obstacle.

update(delta_time: float) None[source]

Update obstacle position and animation.

is_off_screen() bool[source]

Check if obstacle is off the left side of screen.

get_collision_rect() dict[source]

Get collision rectangle.

class unipress.games.jumper.game.JumperGame(difficulty: int = None)[source]

Bases: BaseGame

Jumper game with sprite animations and sound effects.

Enhanced version of demo_jump featuring: - Animated running player character - Animated fire obstacles - Parallax scrolling background - Sound effects for actions - Sprite-based graphics

__init__(difficulty: int = None)[source]

Initialize Jumper game.

load_background_layers() None[source]

Load background layers from JSON configuration.

reset_game() None[source]

Reset game to initial state.

reset_animations() None[source]

Reset all animations to prevent accumulated time during startup sound.

on_resize(width: int, height: int) None[source]

Handle window resize to maintain proper ground positioning.

on_action_press() None[source]

Handle jump action.

update_player(delta_time: float) None[source]

Update player physics and animation.

spawn_obstacle() None[source]

Spawn a new fire obstacle.

update_obstacles(delta_time: float) None[source]

Update all obstacles.

check_collisions() None[source]

Check for player-obstacle collisions.

update_background(delta_time: float) None[source]

Update parallax background layers.

on_update(delta_time: float) None[source]

Update game state.

draw_background() None[source]

Draw parallax background layers.

draw_game_objects() None[source]

Draw all game objects.

draw_jump_window() None[source]

Draw jump window indicator like in demo_jump.

on_draw() None[source]

Draw the game.

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

_complete_life_lost_continue() None

Complete the life lost continuation sequence.

_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.

_exit_game() None

Exit the game from end screen.

_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.

_restart_game() None

Restart the game from end screen.

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.

check_and_play_high_score_sound(new_score: int) None

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

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.

complete_game_start() None

Complete the game start sequence.

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_heart(x: float, y: float, filled: bool = True) None

Draw a smooth heart shape at the given position.

draw_hearts() None

Draw hearts to represent remaining lives.

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.

draw_ui() None

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

end_game() None

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

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_difficulty_settings() dict[str, Any]

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

Returns:

Dictionary with difficulty-specific game settings

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_message(key: str, **kwargs) str

Get localized message with parameter substitution.

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

handle_life_lost_continue() bool

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

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.

is_game_paused() bool

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

lose_life() None

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

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_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_press(key: int, modifiers: int) None

Handle keyboard events (if needed for alternative input).

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_press(x: float, y: float, button: int, modifiers: int) None

Handle mouse press events.

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_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.

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.

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

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

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

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

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
should_draw_player() bool

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

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.

start_game() None

Start the game after user clicks.

start_game_sound_timer() None

Start non-blocking game start sound timer.

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.

update_life_lost_effects(delta_time: float) None

Update visual effects during life lost pause.

update_sound_timer(delta_time: float) None

Update non-blocking sound timer.

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.

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"]}"
)
closed

Indicates if the window was closed

UI Components

End Game Screen

End Game Screen UI Component

Provides standardized end game screen with two cycling buttons: - Play Again: Restart the current game - Exit: Close the game

Buttons cycle on each click, selected button is highlighted.

class unipress.ui.end_game.screen.EndGameAction(*values)[source]

Bases: Enum

Available actions on end game screen.

PLAY_AGAIN = 'play_again'
EXIT = 'exit'
classmethod __contains__(value)

Return True if value is in cls.

value is in cls if: 1) value is a member of cls, or 2) value is the value of one of the cls’s members. 3) value is a pseudo-member (flags)

classmethod __getitem__(name)

Return the member matching name.

classmethod __iter__()

Return members in definition order.

classmethod __len__()

Return the number of members (no aliases)

class unipress.ui.end_game.screen.EndGameScreen(messages: MessageLoader, final_score: int = 0, cycle_time: float = 2.0, game_name: str = '', on_cycle: Callable[[], None] | None = None)[source]

Bases: object

Standardized end game screen with cycling buttons.

Features: - Two buttons: Play Again / Exit - Buttons cycle on each click - Selected button is highlighted - Shared across all games with override capability

__init__(messages: MessageLoader, final_score: int = 0, cycle_time: float = 2.0, game_name: str = '', on_cycle: Callable[[], None] | None = None)[source]

Initialize end game screen.

Parameters:
  • messages – Message loader for localized text

  • final_score – Player’s final score to display

  • cycle_time – Time in seconds between automatic button cycling

  • game_name – Name of the game for high score lookup

update(delta_time: float) None[source]

Update the end game screen (handles automatic cycling).

Parameters:

delta_time – Time elapsed since last update in seconds

get_selected_action() EndGameAction[source]

Get currently selected action without cycling.

draw(window_width: int, window_height: int) None[source]

Draw the end game screen.

Parameters:
  • window_width – Width of the game window

  • window_height – Height of the game window

_draw_button(text: str, center_x: float, center_y: float, width: float, height: float, is_selected: bool) None[source]

Draw a rounded button with optional selection highlighting.

Parameters:
  • text – Button text

  • center_x – Button center X coordinate

  • center_y – Button center Y coordinate

  • width – Button width

  • height – Button height

  • is_selected – Whether button is currently selected

Package Information

Unipress - One-Button Games Collection

A collection of simple games controlled with a single button.

Module Index