McRogueFace API Reference - Complete Documentation

Generated on 2025-07-15 21:28:13

Table of Contents

Functions

Scene Management

createScene(name: str) -> None

Create a new empty scene with the given name.

Arguments:
name (str): Unique name for the new scene
Raises: ValueError: If a scene with this name already exists
Note: The scene is created but not made active. Use setScene() to switch to it.
Example:

mcrfpy.createScene("game_over")

setScene(scene: str, transition: str = None, duration: float = 0.0) -> None

Switch to a different scene with optional transition effect.

Arguments:
scene (str): Name of the scene to switch to
transition (str): Transition type: "fade", "slide_left", "slide_right", "slide_up", "slide_down"
duration (float): Transition duration in seconds (default: 0.0 for instant)
Raises: KeyError: If the scene doesn't exist
Example:

mcrfpy.setScene("game", "fade", 0.5)

currentScene() -> str

Get the name of the currently active scene.

Returns: str: Name of the current scene
Example:

scene_name = mcrfpy.currentScene()

sceneUI(scene: str = None) -> UICollection

Get all UI elements for a scene.

Arguments:
scene (str): Scene name. If None, uses current scene
Returns: UICollection: All UI elements in the scene
Raises: KeyError: If the specified scene doesn't exist
Example:

ui_elements = mcrfpy.sceneUI("game")

keypressScene(handler: callable) -> None

Set the keyboard event handler for the current scene.

Arguments:
handler (callable): Function that receives (key_name: str, is_pressed: bool)
Example:

def on_key(key, pressed):
    if key == "SPACE" and pressed:
        player.jump()
mcrfpy.keypressScene(on_key)

Audio

createSoundBuffer(filename: str) -> int

Load a sound effect from a file and return its buffer ID.

Arguments:
filename (str): Path to the sound file (WAV, OGG, FLAC)
Returns: int: Buffer ID for use with playSound()
Raises: RuntimeError: If the file cannot be loaded
Example:

jump_sound = mcrfpy.createSoundBuffer("assets/jump.wav")

loadMusic(filename: str, loop: bool = True) -> None

Load and immediately play background music from a file.

Arguments:
filename (str): Path to the music file (WAV, OGG, FLAC)
loop (bool): Whether to loop the music (default: True)
Note: Only one music track can play at a time. Loading new music stops the current track.
Example:

mcrfpy.loadMusic("assets/background.ogg", True)

playSound(buffer_id: int) -> None

Play a sound effect using a previously loaded buffer.

Arguments:
buffer_id (int): Sound buffer ID returned by createSoundBuffer()
Raises: RuntimeError: If the buffer ID is invalid
Example:

mcrfpy.playSound(jump_sound)

getMusicVolume() -> int

Get the current music volume level.

Returns: int: Current volume (0-100)
Example:

current_volume = mcrfpy.getMusicVolume()

getSoundVolume() -> int

Get the current sound effects volume level.

Returns: int: Current volume (0-100)
Example:

current_volume = mcrfpy.getSoundVolume()

setMusicVolume(volume: int) -> None

Set the global music volume.

Arguments:
volume (int): Volume level from 0 (silent) to 100 (full volume)
Example:

mcrfpy.setMusicVolume(50)  # Set to 50% volume

setSoundVolume(volume: int) -> None

Set the global sound effects volume.

Arguments:
volume (int): Volume level from 0 (silent) to 100 (full volume)
Example:

mcrfpy.setSoundVolume(75)  # Set to 75% volume

UI Utilities

find(name: str, scene: str = None) -> UIDrawable | None

Find the first UI element with the specified name.

Arguments:
name (str): Exact name to search for
scene (str): Scene to search in (default: current scene)
Returns: UIDrawable or None: The found element, or None if not found
Note: Searches scene UI elements and entities within grids.
Example:

button = mcrfpy.find("start_button")

findAll(pattern: str, scene: str = None) -> list

Find all UI elements matching a name pattern.

Arguments:
pattern (str): Name pattern with optional wildcards (* matches any characters)
scene (str): Scene to search in (default: current scene)
Returns: list: All matching UI elements and entities
Example:

enemies = mcrfpy.findAll("enemy_*")

System

exit() -> None

Cleanly shut down the game engine and exit the application.

Note: This immediately closes the window and terminates the program.
Example:

mcrfpy.exit()

getMetrics() -> dict

Get current performance metrics.

Returns: dict: Performance data with keys: - frame_time: Last frame duration in seconds - avg_frame_time: Average frame time - fps: Frames per second - draw_calls: Number of draw calls - ui_elements: Total UI element count - visible_elements: Visible element count - current_frame: Frame counter - runtime: Total runtime in seconds
Example:

metrics = mcrfpy.getMetrics()

setTimer(name: str, handler: callable, interval: int) -> None

Create or update a recurring timer.

Arguments:
name (str): Unique identifier for the timer
handler (callable): Function called with (runtime: float) parameter
interval (int): Time between calls in milliseconds
Note: If a timer with this name exists, it will be replaced.
Example:

def update_score(runtime):
    score += 1
mcrfpy.setTimer("score_update", update_score, 1000)

delTimer(name: str) -> None

Stop and remove a timer.

Arguments:
name (str): Timer identifier to remove
Note: No error is raised if the timer doesn't exist.
Example:

mcrfpy.delTimer("score_update")

setScale(multiplier: float) -> None

Scale the game window size.

Arguments:
multiplier (float): Scale factor (e.g., 2.0 for double size)
Note: The internal resolution remains 1024x768, but the window is scaled.
Example:

mcrfpy.setScale(2.0)  # Double the window size

Classes

Animation

Animation object for animating UI properties

Properties:

property: str: Name of the property being animated (e.g., "x", "y", "scale")
duration: float: Total duration of the animation in seconds
elapsed_time: float: Time elapsed since animation started (read-only)
current_value: float: Current interpolated value of the animation (read-only)
is_running: bool: True if animation is currently running (read-only)
is_finished: bool: True if animation has completed (read-only)

Methods:

update(delta_time)

Update the animation by the given time delta.

delta_time (float): Time elapsed since last update in seconds
Returns: bool: True if animation is still running, False if finished
complete(...)
hasValidTarget(...)
get_current_value()

Get the current interpolated value of the animation.

Returns: float: Current animation value between start and end
start(target)

Start the animation on a target UI element.

target (UIDrawable): The UI element to animate
Note: The target must have the property specified in the animation constructor.

Caption

Caption(pos=None, font=None, text='', **kwargs) A text display UI element with customizable font and styling. Args: pos (tuple, optional): Position as (x, y) tuple. Default: (0, 0) font (Font, optional): Font object for text rendering. Default: engine default font text (str, optional): The text content to display. Default: '' Keyword Args: fill_color (Color): Text fill color. Default: (255, 255, 255, 255) outline_color (Color): Text outline color. Default: (0, 0, 0, 255) outline (float): Text outline thickness. Default: 0 font_size (float): Font size in points. Default: 16 click (callable): Click event handler. Default: None visible (bool): Visibility state. Default: True opacity (float): Opacity (0.0-1.0). Default: 1.0 z_index (int): Rendering order. Default: 0 name (str): Element name for finding. Default: None x (float): X position override. Default: 0 y (float): Y position override. Default: 0 Attributes: text (str): The displayed text content x, y (float): Position in pixels pos (Vector): Position as a Vector object font (Font): Font used for rendering font_size (float): Font size in points fill_color, outline_color (Color): Text appearance outline (float): Outline thickness click (callable): Click event handler visible (bool): Visibility state opacity (float): Opacity value z_index (int): Rendering order name (str): Element name w, h (float): Read-only computed size based on text and font

Methods:

move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.

Color

SFML Color Object

Methods:

to_hex()

Convert this Color to a hexadecimal string.

Returns: str: Hex color string in format "#RRGGBB"
Example:

hex_str = color.to_hex()  # Returns "#FF0000"
from_hex(hex_string)

Create a Color from a hexadecimal color string.

hex_string (str): Hex color string (e.g., "#FF0000" or "FF0000")
Returns: Color: New Color object from hex string
Example:

red = Color.from_hex("#FF0000")
lerp(other, t)

Linearly interpolate between this color and another.

other (Color): The color to interpolate towards
t (float): Interpolation factor from 0.0 to 1.0
Returns: Color: New interpolated Color object
Example:

mixed = red.lerp(blue, 0.5)  # 50% between red and blue

Drawable

Base class for all drawable UI elements

Methods:

move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.

Entity

Entity(grid_pos=None, texture=None, sprite_index=0, **kwargs) A game entity that exists on a grid with sprite rendering. Args: grid_pos (tuple, optional): Grid position as (x, y) tuple. Default: (0, 0) texture (Texture, optional): Texture object for sprite. Default: default texture sprite_index (int, optional): Index into texture atlas. Default: 0 Keyword Args: grid (Grid): Grid to attach entity to. Default: None visible (bool): Visibility state. Default: True opacity (float): Opacity (0.0-1.0). Default: 1.0 name (str): Element name for finding. Default: None x (float): X grid position override. Default: 0 y (float): Y grid position override. Default: 0 Attributes: pos (tuple): Grid position as (x, y) tuple x, y (float): Grid position coordinates draw_pos (tuple): Pixel position for rendering gridstate (GridPointState): Visibility state for grid points sprite_index (int): Current sprite index visible (bool): Visibility state opacity (float): Opacity value name (str): Element name

Methods:

die()

Remove this entity from its parent grid.

Note: The entity object remains valid but is no longer rendered or updated.
move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
at(x, y)

Check if this entity is at the specified grid coordinates.

x (int): Grid x coordinate to check
y (int): Grid y coordinate to check
Returns: bool: True if entity is at position (x, y), False otherwise
path_to(...)
update_visibility(...)
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.
index()

Get the index of this entity in its parent grid's entity list.

Returns: int: Index position, or -1 if not in a grid

EntityCollection

Iterable, indexable collection of Entities

Methods:

remove(entity)

Remove the first occurrence of an entity from the collection.

entity (Entity): The entity to remove
count(entity)

Count the number of occurrences of an entity in the collection.

entity (Entity): The entity to count
Returns: int: Number of times entity appears in collection
extend(iterable)

Add all entities from an iterable to the collection.

iterable (Iterable[Entity]): Entities to add
index(entity)

Find the index of the first occurrence of an entity.

entity (Entity): The entity to find
Returns: int: Index of entity in collection
append(entity)

Add an entity to the end of the collection.

entity (Entity): The entity to add

Font

SFML Font Object

Frame

Frame(pos=None, size=None, **kwargs) A rectangular frame UI element that can contain other drawable elements. Args: pos (tuple, optional): Position as (x, y) tuple. Default: (0, 0) size (tuple, optional): Size as (width, height) tuple. Default: (0, 0) Keyword Args: fill_color (Color): Background fill color. Default: (0, 0, 0, 128) outline_color (Color): Border outline color. Default: (255, 255, 255, 255) outline (float): Border outline thickness. Default: 0 click (callable): Click event handler. Default: None children (list): Initial list of child drawable elements. Default: None visible (bool): Visibility state. Default: True opacity (float): Opacity (0.0-1.0). Default: 1.0 z_index (int): Rendering order. Default: 0 name (str): Element name for finding. Default: None x (float): X position override. Default: 0 y (float): Y position override. Default: 0 w (float): Width override. Default: 0 h (float): Height override. Default: 0 clip_children (bool): Whether to clip children to frame bounds. Default: False Attributes: x, y (float): Position in pixels w, h (float): Size in pixels pos (Vector): Position as a Vector object fill_color, outline_color (Color): Visual appearance outline (float): Border thickness click (callable): Click event handler children (list): Collection of child drawable elements visible (bool): Visibility state opacity (float): Opacity value z_index (int): Rendering order name (str): Element name clip_children (bool): Whether to clip children to frame bounds

Methods:

move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.

Grid

Grid(pos=None, size=None, grid_size=None, texture=None, **kwargs) A grid-based UI element for tile-based rendering and entity management. Args: pos (tuple, optional): Position as (x, y) tuple. Default: (0, 0) size (tuple, optional): Size as (width, height) tuple. Default: auto-calculated from grid_size grid_size (tuple, optional): Grid dimensions as (grid_x, grid_y) tuple. Default: (2, 2) texture (Texture, optional): Texture containing tile sprites. Default: default texture Keyword Args: fill_color (Color): Background fill color. Default: None click (callable): Click event handler. Default: None center_x (float): X coordinate of center point. Default: 0 center_y (float): Y coordinate of center point. Default: 0 zoom (float): Zoom level for rendering. Default: 1.0 perspective (int): Entity perspective index (-1 for omniscient). Default: -1 visible (bool): Visibility state. Default: True opacity (float): Opacity (0.0-1.0). Default: 1.0 z_index (int): Rendering order. Default: 0 name (str): Element name for finding. Default: None x (float): X position override. Default: 0 y (float): Y position override. Default: 0 w (float): Width override. Default: auto-calculated h (float): Height override. Default: auto-calculated grid_x (int): Grid width override. Default: 2 grid_y (int): Grid height override. Default: 2 Attributes: x, y (float): Position in pixels w, h (float): Size in pixels pos (Vector): Position as a Vector object size (tuple): Size as (width, height) tuple center (tuple): Center point as (x, y) tuple center_x, center_y (float): Center point coordinates zoom (float): Zoom level for rendering grid_size (tuple): Grid dimensions (width, height) in tiles grid_x, grid_y (int): Grid dimensions texture (Texture): Tile texture atlas fill_color (Color): Background color entities (EntityCollection): Collection of entities in the grid perspective (int): Entity perspective index click (callable): Click event handler visible (bool): Visibility state opacity (float): Opacity value z_index (int): Rendering order name (str): Element name

Methods:

get_dijkstra_path(...)
compute_astar_path(...)
move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
is_in_fov(...)
at(x, y)

Get the GridPoint at the specified grid coordinates.

x (int): Grid x coordinate
y (int): Grid y coordinate
Returns: GridPoint or None: The grid point at (x, y), or None if out of bounds
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.
find_path(...)
compute_fov(...)
compute_dijkstra(...)
get_dijkstra_distance(...)

GridPoint

UIGridPoint object

Properties:

x: int: Grid x coordinate of this point
y: int: Grid y coordinate of this point
texture_index: int: Index of the texture/sprite to display at this point
solid: bool: Whether this point blocks movement
transparent: bool: Whether this point allows light/vision through
color: Color: Color tint applied to the texture at this point

GridPointState

UIGridPointState object

Properties:

visible: bool: Whether this point is currently visible to the player
discovered: bool: Whether this point has been discovered/explored
custom_flags: int: Bitfield for custom game-specific flags

Scene

Base class for object-oriented scenes

Methods:

get_ui()

Get the UI element collection for this scene.

Returns: UICollection: Collection of all UI elements in this scene
keypress(handler)

Register a keyboard handler function for this scene.

handler (callable): Function that takes (key_name: str, is_pressed: bool)
Note: Alternative to overriding the on_keypress method.
activate()

Make this scene the active scene.

Note: Equivalent to calling setScene() with this scene's name.
register_keyboard(callable)

Register a keyboard event handler function for the scene.

callable (callable): Function that takes (key: str, action: str) parameters
Note: Alternative to overriding the on_keypress method when subclassing Scene objects.
Example:

def handle_keyboard(key, action):
    print(f"Key '{key}' was {action}")
    if key == "q" and action == "press":
        # Handle quit
        pass
scene.register_keyboard(handle_keyboard)

Sprite

Sprite(pos=None, texture=None, sprite_index=0, **kwargs) A sprite UI element that displays a texture or portion of a texture atlas. Args: pos (tuple, optional): Position as (x, y) tuple. Default: (0, 0) texture (Texture, optional): Texture object to display. Default: default texture sprite_index (int, optional): Index into texture atlas. Default: 0 Keyword Args: scale (float): Uniform scale factor. Default: 1.0 scale_x (float): Horizontal scale factor. Default: 1.0 scale_y (float): Vertical scale factor. Default: 1.0 click (callable): Click event handler. Default: None visible (bool): Visibility state. Default: True opacity (float): Opacity (0.0-1.0). Default: 1.0 z_index (int): Rendering order. Default: 0 name (str): Element name for finding. Default: None x (float): X position override. Default: 0 y (float): Y position override. Default: 0 Attributes: x, y (float): Position in pixels pos (Vector): Position as a Vector object texture (Texture): The texture being displayed sprite_index (int): Current sprite index in texture atlas scale (float): Uniform scale factor scale_x, scale_y (float): Individual scale factors click (callable): Click event handler visible (bool): Visibility state opacity (float): Opacity value z_index (int): Rendering order name (str): Element name w, h (float): Read-only computed size based on texture and scale

Methods:

move(dx, dy)

Move the element by a relative offset.

dx (float): Horizontal offset in pixels
dy (float): Vertical offset in pixels
Note: This modifies the x and y position properties by the given amounts.
get_bounds()

Get the bounding rectangle of this drawable element.

Returns: tuple: (x, y, width, height) representing the element's bounds
Note: The bounds are in screen coordinates and account for current position and size.
resize(width, height)

Resize the element to new dimensions.

width (float): New width in pixels
height (float): New height in pixels
Note: For Caption and Sprite, this may not change actual size if determined by content.

Texture

SFML Texture Object

Timer

Timer(name, callback, interval, once=False) Create a timer that calls a function at regular intervals. Args: name (str): Unique identifier for the timer callback (callable): Function to call - receives (timer, runtime) args interval (int): Time between calls in milliseconds once (bool): If True, timer stops after first call. Default: False Attributes: interval (int): Time between calls in milliseconds remaining (int): Time until next call in milliseconds (read-only) paused (bool): Whether timer is paused (read-only) active (bool): Whether timer is active and not paused (read-only) callback (callable): The callback function once (bool): Whether timer stops after firing once Methods: pause(): Pause the timer, preserving time remaining resume(): Resume a paused timer cancel(): Stop and remove the timer restart(): Reset timer to start from beginning Example: def on_timer(timer, runtime): print(f'Timer {timer} fired at {runtime}ms') if runtime > 5000: timer.cancel() timer = mcrfpy.Timer('my_timer', on_timer, 1000) timer.pause() # Pause timer timer.resume() # Resume timer timer.once = True # Make it one-shot

Methods:

cancel()

Cancel the timer and remove it from the system.

Note: After cancelling, the timer object cannot be reused.
pause()

Pause the timer, stopping its callback execution.

Note: Use resume() to continue the timer from where it was paused.
resume()

Resume a paused timer.

Note: Has no effect if timer is not paused.
restart()

Restart the timer from the beginning.

Note: Resets the timer's internal clock to zero.

UICollection

Iterable, indexable collection of UI objects

Methods:

remove(drawable)

Remove the first occurrence of a drawable from the collection.

drawable (UIDrawable): The drawable to remove
count(drawable)

Count the number of occurrences of a drawable in the collection.

drawable (UIDrawable): The drawable to count
Returns: int: Number of times drawable appears in collection
extend(iterable)

Add all drawables from an iterable to the collection.

iterable (Iterable[UIDrawable]): Drawables to add
index(drawable)

Find the index of the first occurrence of a drawable.

drawable (UIDrawable): The drawable to find
Returns: int: Index of drawable in collection
append(drawable)

Add a drawable element to the end of the collection.

drawable (UIDrawable): The drawable element to add

UICollectionIter

Iterator for a collection of UI objects

UIEntityCollectionIter

Iterator for a collection of UI objects

Vector

SFML Vector Object

Methods:

magnitude_squared()

Calculate the squared magnitude of this vector.

Returns: float: The squared magnitude (faster than magnitude())
Note: Use this for comparisons to avoid expensive square root calculation.
copy()

Create a copy of this vector.

Returns: Vector: New Vector object with same x and y values
magnitude()

Calculate the length/magnitude of this vector.

Returns: float: The magnitude of the vector
Example:

length = vector.magnitude()
angle()

Get the angle of this vector in radians.

Returns: float: Angle in radians from positive x-axis
distance_to(other)

Calculate the distance to another vector.

other (Vector): The other vector
Returns: float: Distance between the two vectors
normalize()

Return a unit vector in the same direction.

Returns: Vector: New normalized vector with magnitude 1.0
dot(other)

Calculate the dot product with another vector.

other (Vector): The other vector
Returns: float: Dot product of the two vectors

Window

Window singleton for accessing and modifying the game window properties

Methods:

get()

Get the Window singleton instance.

Returns: Window: The singleton window object
Note: This is a static method that returns the same instance every time.
screenshot(filename)

Take a screenshot and save it to a file.

filename (str): Path where to save the screenshot
Note: Supports PNG, JPG, and BMP formats based on file extension.
center()

Center the window on the screen.

Note: Only works if the window is not fullscreen.

Automation Module

The mcrfpy.automation module provides testing and automation capabilities.

automation.click

Click at position

automation.doubleClick

Double click at position

automation.dragRel

Drag mouse relative to current position

automation.dragTo

Drag mouse to position

automation.hotkey

Press a hotkey combination (e.g., hotkey('ctrl', 'c'))

automation.keyDown

Press and hold a key

automation.keyUp

Release a key

automation.middleClick

Middle click at position

automation.mouseDown

Press mouse button

automation.mouseUp

Release mouse button

automation.moveRel

Move mouse relative to current position

automation.moveTo

Move mouse to absolute position

automation.onScreen

Check if coordinates are within screen bounds

automation.position

Get current mouse position as (x, y) tuple

automation.rightClick

Right click at position

automation.screenshot

Save a screenshot to the specified file

automation.scroll

Scroll wheel at position

automation.size

Get screen size as (width, height) tuple

automation.tripleClick

Triple click at position

automation.typewrite

Type text with optional interval between keystrokes