McRogueFace API Reference

Generated on 2025-07-08 11:45:09

Overview

McRogueFace Python API

Core game engine interface for creating roguelike games with Python.

This module provides:

- Scene management (createScene, setScene, currentScene)

- UI components (Frame, Caption, Sprite, Grid)

- Entity system for game objects

- Audio playback (sound effects and music)

- Timer system for scheduled events

- Input handling

- Performance metrics

Example:


    import mcrfpy
    # Create a new scene
    mcrfpy.createScene('game')
    mcrfpy.setScene('game')
    # Add UI elements
    frame = mcrfpy.Frame(10, 10, 200, 100)
    caption = mcrfpy.Caption('Hello World', 50, 50)
    mcrfpy.sceneUI().extend([frame, caption])

Table of Contents

Classes

UI Components

class Frame

Inherits from: Drawable

A rectangular frame UI element that can contain other drawable elements.

Args:
x (float): X position in pixels. Default: 0
y (float): Y position in pixels. Default: 0
w (float): Width in pixels. Default: 0
h (float): Height in pixels. Default: 0
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

Attributes:
x, y (float): Position in pixels
w, h (float): Size in pixels
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
z_index (int): Rendering order
clip_children (bool): Whether to clip children to frame bounds

Methods:

get_bounds()

Get the bounding rectangle of the frame.

Returns: tuple: (x, y, width, height) representing the frame bounds

move(dx, dy)

Move the frame and all its children by a relative offset.

Arguments:

  • dx (float): Horizontal offset in pixels
  • dy (float): Vertical offset in pixels

Note: Child elements maintain their relative positions within the frame.

resize(width, height)

Resize the frame to new dimensions.

Arguments:

  • width (float): New width in pixels
  • height (float): New height in pixels

Note: Does not automatically resize children. Set clip_children=True to clip overflow.


class Caption

Inherits from: Drawable

A text display UI element with customizable font and styling.

Args:
text (str): The text content to display. Default: ''
x (float): X position in pixels. Default: 0
y (float): Y position in pixels. Default: 0
font (Font): Font object for text rendering. Default: engine default font
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
click (callable): Click event handler. Default: None

Attributes:
text (str): The displayed text content
x, y (float): Position in pixels
font (Font): Font used for rendering
fill_color, outline_color (Color): Text appearance
outline (float): Outline thickness
click (callable): Click event handler
visible (bool): Visibility state
z_index (int): Rendering order
w, h (float): Read-only computed size based on text and font

Methods:

get_bounds()

Get the bounding rectangle of the text.

Returns: tuple: (x, y, width, height) based on text content and font size

Note: Bounds are automatically calculated from the rendered text dimensions.

move(dx, dy)

Move the caption by a relative offset.

Arguments:

  • dx (float): Horizontal offset in pixels
  • dy (float): Vertical offset in pixels
resize(width, height)

Set text wrapping bounds (limited support).

Arguments:

  • width (float): Maximum width for text wrapping
  • height (float): Currently unused

Note: Full text wrapping is not yet implemented. This prepares for future multiline support.


class Sprite

Inherits from: Drawable

A sprite UI element that displays a texture or portion of a texture atlas.

Args:
x (float): X position in pixels. Default: 0
y (float): Y position in pixels. Default: 0
texture (Texture): Texture object to display. Default: None
sprite_index (int): Index into texture atlas (if applicable). Default: 0
scale (float): Sprite scaling factor. Default: 1.0
click (callable): Click event handler. Default: None

Attributes:
x, y (float): Position in pixels
texture (Texture): The texture being displayed
sprite_index (int): Current sprite index in texture atlas
scale (float): Scale multiplier
click (callable): Click event handler
visible (bool): Visibility state
z_index (int): Rendering order
w, h (float): Read-only computed size based on texture and scale

Methods:

get_bounds()

Get the bounding rectangle of the sprite.

Returns: tuple: (x, y, width, height) based on texture size and scale

Note: Bounds account for current scale. Returns (x, y, 0, 0) if no texture.

move(dx, dy)

Move the sprite by a relative offset.

Arguments:

  • dx (float): Horizontal offset in pixels
  • dy (float): Vertical offset in pixels
resize(width, height)

Resize the sprite by adjusting its scale.

Arguments:

  • width (float): Target width in pixels
  • height (float): Target height in pixels

Note: Calculates and applies uniform scale to best fit the target dimensions.


class Grid

Inherits from: Drawable

A grid-based tilemap UI element for rendering tile-based levels and game worlds.

Args:
x (float): X position in pixels. Default: 0
y (float): Y position in pixels. Default: 0
grid_size (tuple): Grid dimensions as (width, height) in tiles. Default: (20, 20)
texture (Texture): Texture atlas containing tile sprites. Default: None
tile_width (int): Width of each tile in pixels. Default: 16
tile_height (int): Height of each tile in pixels. Default: 16
scale (float): Grid scaling factor. Default: 1.0
click (callable): Click event handler. Default: None

Attributes:
x, y (float): Position in pixels
grid_size (tuple): Grid dimensions (width, height) in tiles
tile_width, tile_height (int): Tile dimensions in pixels
texture (Texture): Tile texture atlas
scale (float): Scale multiplier
points (list): 2D array of GridPoint objects for tile data
entities (list): Collection of Entity objects in the grid
background_color (Color): Grid background color
click (callable): Click event handler
visible (bool): Visibility state
z_index (int): Rendering order

Methods:

at(x, y) or at((x, y))

Get the GridPoint at the specified grid coordinates.

Arguments:

  • x (int): Grid x coordinate (0-based)
  • y (int): Grid y coordinate (0-based)

Returns: GridPoint: The grid point at (x, y)

Note: Raises IndexError if coordinates are out of range. Accepts either two arguments or a tuple.

get_bounds()

Get the bounding rectangle of the entire grid.

Returns: tuple: (x, y, width, height) of the grid's display area

move(dx, dy)

Move the grid display by a relative offset.

Arguments:

  • dx (float): Horizontal offset in pixels
  • dy (float): Vertical offset in pixels

Note: Moves the entire grid viewport. Use center property to pan within the grid.

resize(width, height)

Resize the grid's display viewport.

Arguments:

  • width (float): New viewport width in pixels
  • height (float): New viewport height in pixels

Note: Changes the visible area, not the grid dimensions. Use zoom to scale content.


class Entity


Entity(x=0, y=0, sprite_id=0)

Game entity that can be placed in a Grid.

Arguments:

x (int)
Grid x coordinate. Default: 0
y (int)
Grid y coordinate. Default: 0
sprite_id (int)
Sprite index for rendering. Default: 0

Methods:

at(x, y)

Get the GridPointState at the specified grid coordinates relative to this entity.

Arguments:

  • x (int): Grid x offset from entity position
  • y (int): Grid y offset from entity position

Returns: GridPointState: State of the grid point at the specified position

Note: Requires entity to be associated with a grid. Raises ValueError if not.

die()

Remove this entity from its parent grid.

Returns: None

Note: The entity object remains valid but is no longer rendered or updated.

get_bounds()

Get the bounding rectangle of the entity's sprite.

Returns: tuple: (x, y, width, height) of the sprite bounds

Note: Delegates to the internal sprite's get_bounds method.

index()

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

Returns: int: Zero-based index in the parent grid's entity list

Note: Raises RuntimeError if not associated with a grid, ValueError if not found.

move(dx, dy)

Move the entity by a relative offset in pixels.

Arguments:

  • dx (float): Horizontal offset in pixels
  • dy (float): Vertical offset in pixels

Note: Updates both sprite position and entity grid position.

resize(width, height)

Entities do not support direct resizing.

Arguments:

  • width (float): Ignored
  • height (float): Ignored

Note: This method exists for interface compatibility but has no effect.

Example:


entity = mcrfpy.Entity(5, 10, 42)
entity.move(1, 0)  # Move right one tile

Collections

class EntityCollection

Container for Entity objects in a Grid. Supports iteration and indexing.

Methods:

append(entity)

Add an entity to the end of the collection.

Arguments:

  • entity (Entity): The entity to add
remove(entity)

Remove the first occurrence of an entity from the collection.

Arguments:

  • entity (Entity): The entity to remove

Note: Raises ValueError if entity is not found.

extend(iterable)

Add multiple entities from an iterable.

Arguments:

  • iterable (iterable): An iterable of Entity objects
count(entity)

Count occurrences of an entity in the collection.

Arguments:

  • entity (Entity): The entity to count

Returns: int: Number of times the entity appears

index(entity)

Find the index of the first occurrence of an entity.

Arguments:

  • entity (Entity): The entity to find

Returns: int: Zero-based index of the entity

Note: Raises ValueError if entity is not found.


class UICollection

Container for UI drawable elements. Supports iteration and indexing.

Methods:

append(drawable)

Add a drawable element to the end of the collection.

Arguments:

  • drawable (Drawable): Any UI element (Frame, Caption, Sprite, Grid)
remove(drawable)

Remove the first occurrence of a drawable from the collection.

Arguments:

  • drawable (Drawable): The drawable to remove

Note: Raises ValueError if drawable is not found.

extend(iterable)

Add multiple drawables from an iterable.

Arguments:

  • iterable (iterable): An iterable of Drawable objects
count(drawable)

Count occurrences of a drawable in the collection.

Arguments:

  • drawable (Drawable): The drawable to count

Returns: int: Number of times the drawable appears

index(drawable)

Find the index of the first occurrence of a drawable.

Arguments:

  • drawable (Drawable): The drawable to find

Returns: int: Zero-based index of the drawable

Note: Raises ValueError if drawable is not found.


class UICollectionIter

Iterator for UICollection. Automatically created when iterating over a UICollection.


class UIEntityCollectionIter

Iterator for EntityCollection. Automatically created when iterating over an EntityCollection.


System Types

class Color


Color(r=255, g=255, b=255, a=255)

RGBA color representation.

Arguments:

r (int)
Red component (0-255). Default: 255
g (int)
Green component (0-255). Default: 255
b (int)
Blue component (0-255). Default: 255
a (int)
Alpha component (0-255). Default: 255

Methods:

from_hex(...)

Create Color from hex string (e.g., '#FF0000' or 'FF0000')

lerp(...)

Linearly interpolate between this color and another

to_hex(...)

Convert Color to hex string

Example:


red = mcrfpy.Color(255, 0, 0)

class Vector


Vector(x=0.0, y=0.0)

2D vector for positions and directions.

Arguments:

x (float)
X component. Default: 0.0
y (float)
Y component. Default: 0.0

Methods:

angle(...)

Return the angle in radians from the positive X axis

copy(...)

Return a copy of this vector

distance_to(...)

Return the distance to another vector

dot(...)

Return the dot product with another vector

magnitude(...)

Return the length of the vector

magnitude_squared(...)

Return the squared length of the vector

normalize(...)

Return a unit vector in the same direction


class Texture


Texture(filename)

Load a texture from file.

Arguments:

filename (str)
Path to image file (PNG/JPG/BMP)

class Font


Font(filename)

Load a font from file.

Arguments:

filename (str)
Path to font file (TTF/OTF)

Other Classes

class Animation


Animation(property_name, start_value, end_value, duration, transition="linear", loop=False)

Animate UI element properties over time.

Arguments:

property_name (str)
Property to animate (e.g., "x", "y", "scale")
start_value (float)
Starting value
end_value (float)
Ending value
duration (float)
Duration in seconds
transition (str)
Easing function. Default: "linear"
loop (bool)
Whether to loop. Default: False

Attributes:

current_value
Property of Animation
elapsed_time
Property of Animation
is_running
Property of Animation
is_finished
Property of Animation

Methods:

get_current_value()

Get the current interpolated value.

Returns: float: Current animation value

start(target)

Start the animation on a target UI element.

Arguments:

  • target (UIDrawable): The element to animate
update(...)

Update the animation by deltaTime (returns True if still running)


class Drawable

Base class for all drawable UI elements

Methods:

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.

move(dx, dy)

Move the element by a relative offset.

Arguments:

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

resize(width, height)

Resize the element to new dimensions.

Arguments:

  • width (float): New width in pixels
  • height (float): New height in pixels

Note: Behavior varies by element type. Some elements may ignore or constrain dimensions.


class GridPoint

Represents a single tile in a Grid.

Attributes:

x
Property of GridPoint
y
Property of GridPoint
texture_index
Property of GridPoint
solid
Property of GridPoint
transparent
Property of GridPoint
color
Property of GridPoint

class GridPointState

State information for a GridPoint.

Attributes:

visible
Property of GridPointState
discovered
Property of GridPointState
custom_flags
Property of GridPointState

class Scene

Base class for object-oriented scenes

Methods:

activate(...)

Make this the active scene

get_ui(...)

Get the UI element collection for this scene

register_keyboard(...)

Register a keyboard handler function (alternative to overriding on_keypress)


class Timer


Timer(name, callback, interval_ms)

Create a recurring timer.

Arguments:

name (str)
Unique timer identifier
callback (callable)
Function to call
interval_ms (int)
Interval in milliseconds

Methods:

cancel(...)

Cancel the timer and remove it from the system

pause(...)

Pause the timer

restart(...)

Restart the timer from the current time

resume(...)

Resume a paused timer


class Window

Window singleton for accessing and modifying the game window properties

Methods:

center(...)

Center the window on the screen

get(...)

Get the Window singleton instance

screenshot(...)

Take a screenshot. Pass filename to save to file, or get raw bytes if no filename.


Functions

Scene Management

createScene(name: str) -> None

Create a new empty scene.

Arguments:
name : str
Unique name for the new scene
Returns:

None

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")
mcrfpy.createScene("menu")
mcrfpy.setScene("game")

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"). Default: None
duration : float
Transition duration in seconds. Default: 0.0 for instant
Returns:

None

Raises:
KeyError
If the scene doesn't exist
ValueError
If the transition type is invalid
Example:

mcrfpy.setScene("menu")
mcrfpy.setScene("game", "fade", 0.5)
mcrfpy.setScene("credits", "slide_left", 1.0)

currentScene() -> str

Get the name of the currently active scene.

Returns:

str: Name of the current scene

Example:

scene = mcrfpy.currentScene()
print(f"Currently in scene: {scene}")

sceneUI(scene: str = None) -> list

Get all UI elements for a scene.

Arguments:
scene : str
Scene name. If None, uses current scene. Default: None
Returns:

list: All UI elements (Frame, Caption, Sprite, Grid) in the scene

Raises:
KeyError
If the specified scene doesn't exist
Example:

# Get UI for current scene
ui_elements = mcrfpy.sceneUI()

# Get UI for specific scene
menu_ui = mcrfpy.sceneUI("menu")
for element in menu_ui:
    print(f"{element.name}: {type(element).__name__}")

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)
Returns:

None

Note: The handler is called for every key press and release event. Key names are single characters (e.g., "A", "1") or special keys (e.g., "Space", "Enter", "Escape").

Example:

def on_key(key, pressed):
    if pressed:
        if key == "Space":
            player.jump()
        elif key == "Escape":
            mcrfpy.setScene("pause_menu")
    else:
        # Handle key release
        if key in ["A", "D"]:
            player.stop_moving()
            
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

Note: Sound buffers are stored in memory for fast playback. Load sound effects once and reuse the buffer ID.

Example:

# Load sound effects
jump_sound = mcrfpy.createSoundBuffer("assets/sounds/jump.wav")
coin_sound = mcrfpy.createSoundBuffer("assets/sounds/coin.ogg")

# Play later
mcrfpy.playSound(jump_sound)

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
Returns:

None

Note: Only one music track can play at a time. Loading new music stops the current track.

Example:

# Play looping background music
mcrfpy.loadMusic("assets/music/theme.ogg")

# Play music once without looping
mcrfpy.loadMusic("assets/music/victory.ogg", loop=False)

playSound(buffer_id: int) -> None

Play a sound effect using a previously loaded buffer.

Arguments:
buffer_id : int
Sound buffer ID returned by createSoundBuffer()
Returns:

None

Raises:
RuntimeError
If the buffer ID is invalid

Note: Multiple sounds can play simultaneously. Each call creates a new sound instance.

Example:

# Load once
explosion_sound = mcrfpy.createSoundBuffer("explosion.wav")

# Play multiple times
for enemy in destroyed_enemies:
    mcrfpy.playSound(explosion_sound)

getMusicVolume() -> int

Get the current music volume level.

Returns:

int: Current volume (0-100)

Example:

volume = mcrfpy.getMusicVolume()
print(f"Music volume: {volume}%")

getSoundVolume() -> int

Get the current sound effects volume level.

Returns:

int: Current volume (0-100)

Example:

volume = mcrfpy.getSoundVolume()
print(f"Sound effects volume: {volume}%")

setMusicVolume(volume: int) -> None

Set the global music volume.

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

None

Example:

# Mute music
mcrfpy.setMusicVolume(0)

# Half volume
mcrfpy.setMusicVolume(50)

# Full volume
mcrfpy.setMusicVolume(100)

setSoundVolume(volume: int) -> None

Set the global sound effects volume.

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

None

Example:

# Audio settings from options menu
mcrfpy.setSoundVolume(sound_slider.value)
mcrfpy.setMusicVolume(music_slider.value)

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:

Frame, Caption, Sprite, Grid, or Entity if found; None otherwise

Note: Searches scene UI elements and entities within grids. Returns the first match found.

Example:

# Find in current scene
player = mcrfpy.find("player")
if player:
    player.x = 100
    
# Find in specific scene
menu_button = mcrfpy.find("start_button", "main_menu")

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

Note: Supports wildcard patterns for flexible searching.

Example:

# Find all enemies
enemies = mcrfpy.findAll("enemy*")
for enemy in enemies:
    enemy.sprite_id = 0  # Reset sprite
    
# Find all buttons
buttons = mcrfpy.findAll("*_button")
for btn in buttons:
    btn.visible = True
    
# Find exact matches
health_bars = mcrfpy.findAll("health_bar")  # No wildcards = exact match

System

exit() -> None

Cleanly shut down the game engine and exit the application.

Returns:

None

Note: This immediately closes the window and terminates the program. Ensure any necessary cleanup is done before calling.

Example:

def quit_game():
    # Save game state
    save_progress()
    
    # Exit
    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()
print(f"FPS: {metrics['fps']}")
print(f"Frame time: {metrics['frame_time']*1000:.1f}ms")
print(f"Draw calls: {metrics['draw_calls']}")
print(f"Runtime: {metrics['runtime']:.1f}s")

# Performance monitoring
if metrics['fps'] < 30:
    print("Performance warning: FPS below 30")

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
Returns:

None

Note: If a timer with this name exists, it will be replaced. The handler receives the total runtime in seconds as its argument.

Example:

# Simple repeating timer
def spawn_enemy(runtime):
    enemy = mcrfpy.Entity()
    enemy.x = random.randint(0, 800)
    grid.entities.append(enemy)
    
mcrfpy.setTimer("enemy_spawner", spawn_enemy, 2000)  # Every 2 seconds

# Timer with runtime check
def update_timer(runtime):
    time_left = 60 - runtime
    timer_text.text = f"Time: {int(time_left)}"
    if time_left <= 0:
        mcrfpy.delTimer("game_timer")
        game_over()
        
mcrfpy.setTimer("game_timer", update_timer, 100)  # Update every 100ms

delTimer(name: str) -> None

Stop and remove a timer.

Arguments:
name : str
Timer identifier to remove
Returns:

None

Note: No error is raised if the timer doesn't exist.

Example:

# Stop spawning enemies
mcrfpy.delTimer("enemy_spawner")

# Clean up all game timers
for timer_name in ["enemy_spawner", "powerup_timer", "score_updater"]:
    mcrfpy.delTimer(timer_name)

setScale(multiplier: float) -> None

Scale the game window size.

Arguments:
multiplier : float
Scale factor (e.g., 2.0 for double size)
Returns:

None

Raises:
ValueError
If multiplier is not between 0.2 and 4.0

Note: The internal resolution remains 1024x768, but the window is scaled. This is deprecated - use Window.resolution instead.

Example:

# Double the window size
mcrfpy.setScale(2.0)

# Half size window
mcrfpy.setScale(0.5)

# Better approach (not deprecated):
mcrfpy.Window.resolution = (1920, 1080)

Automation Module

The mcrfpy.automation module provides testing and automation capabilities for simulating user input and capturing screenshots.

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