diff --git a/docs/api_reference.html b/docs/api_reference.html new file mode 100644 index 0000000..0731bfd --- /dev/null +++ b/docs/api_reference.html @@ -0,0 +1,852 @@ + +
+ +McRogueFace Python API\n\nCore game engine interface for creating roguelike games with Python.\n\nThis module provides:\n- Scene management (createScene, setScene, currentScene)\n- UI components (Frame, Caption, Sprite, Grid)\n- Entity system for game objects\n- Audio playback (sound effects and music)\n- Timer system for scheduled events\n- Input handling\n- Performance metrics\n\nExample:\n import mcrfpy\n \n # Create a new scene\n mcrfpy.createScene('game')\n mcrfpy.setScene('game')\n \n # Add UI elements\n frame = mcrfpy.Frame(10, 10, 200, 100)\n caption = mcrfpy.Caption('Hello World', 50, 50)\n mcrfpy.sceneUI().extend([frame, caption])\n
+ +
+Caption(text='', x=0, y=0, font=None, fill_color=None, outline_color=None, outline=0, click=None)
+
+
+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
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +UIEntity objects
+ +Remove this entity from its grid
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +
+Frame(x=0, y=0, w=0, h=0, fill_color=None, outline_color=None, outline=0, click=None, children=None)
+
+
+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
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +
+Grid(x=0, y=0, grid_size=(20, 20), texture=None, tile_width=16, tile_height=16, scale=1.0, click=None)
+
+
+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
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +
+Sprite(x=0, y=0, texture=None, sprite_index=0, scale=1.0, click=None)
+
+
+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
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +Iterable, indexable collection of Entities
+ +Iterable, indexable collection of UI objects
+ +Iterator for a collection of UI objects
+ +Iterator for a collection of UI objects
+ +SFML Color Object
+ +Create Color from hex string (e.g., '#FF0000' or 'FF0000')
+ +Linearly interpolate between this color and another
+ +Convert Color to hex string
+ +SFML Font Object
+ +SFML Texture Object
+ +SFML Vector Object
+ +Return the distance to another vector
+ +Return the length of the vector
+ +Return the squared length of the vector
+ +Return a unit vector in the same direction
+ +Animation object for animating UI properties
+ +Get the current interpolated value
+ +Start the animation on a target UIDrawable
+ +Update the animation by deltaTime (returns True if still running)
+ +Base class for all drawable UI elements
+ +Get bounding box as (x, y, width, height)
+ +Move by relative offset (dx, dy)
+ +Resize to new dimensions (width, height)
+ +UIGridPoint object
+ +UIGridPointState object
+ +Base class for object-oriented scenes
+ +Make this the active scene
+ +Get the UI element collection for this scene
+ +Register a keyboard handler function (alternative to overriding on_keypress)
+ +Timer object for scheduled callbacks
+ +Cancel the timer and remove it from the system
+ +Pause the timer
+ +Restart the timer from the current time
+ +Resume a paused timer
+ +Window singleton for accessing and modifying the game window properties
+ +Center the window on the screen
+ +Get the Window singleton instance
+ +Create a new empty scene.
+ +*Args:* +name: 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.
+ +Get the name of the currently active scene.
+ +*Returns:* +str: Name of the current scene
+ +Set the keyboard event handler for the current scene.
+ +*Args:* +handler: Callable that receives (key_name: str, is_pressed: bool)
+ +*Example:* +def on_key(key, pressed):
+if key == 'A' and pressed:
+print('A key pressed')
+mcrfpy.keypressScene(on_key)
+ +Get all UI elements for a scene.
+ +*Args:* +scene: Scene name. If None, uses current scene
+ +*Returns:* +list: All UI elements (Frame, Caption, Sprite, Grid) in the scene
+ +*Raises:* +KeyError: If the specified scene doesn't exist
+ +Switch to a different scene with optional transition effect.
+ +*Args:* +scene: Name of the scene to switch to
+transition: Transition type ('fade', 'slide_left', 'slide_right', 'slide_up', 'slide_down')
+duration: Transition duration in seconds (default: 0.0 for instant)
+ +*Raises:* +KeyError: If the scene doesn't exist
+ValueError: If the transition type is invalid
+ +Load a sound effect from a file and return its buffer ID.
+ +*Args:* +filename: Path to the sound file (WAV, OGG, FLAC)
+ +*Returns:* +int: Buffer ID for use with playSound()
+ +*Raises:* +RuntimeError: If the file cannot be loaded
+ +Get the current music volume level.
+ +*Returns:* +int: Current volume (0-100)
+ +Get the current sound effects volume level.
+ +*Returns:* +int: Current volume (0-100)
+ +Load and immediately play background music from a file.
+ +*Args:* +filename: Path to the music file (WAV, OGG, FLAC)
+ +*Note:* +Only one music track can play at a time. Loading new music stops the current track.
+ +Play a sound effect using a previously loaded buffer.
+ +*Args:* +buffer_id: Sound buffer ID returned by createSoundBuffer()
+ +*Raises:* +RuntimeError: If the buffer ID is invalid
+ +Set the global music volume.
+ +*Args:* +volume: Volume level from 0 (silent) to 100 (full volume)
+ +Set the global sound effects volume.
+ +*Args:* +volume: Volume level from 0 (silent) to 100 (full volume)
+ +Find the first UI element with the specified name.
+ +*Args:* +name: Exact name to search for
+scene: 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.
+ +Find all UI elements matching a name pattern.
+ +*Args:* +pattern: Name pattern with optional wildcards (* matches any characters)
+scene: Scene to search in (default: current scene)
+ +*Returns:* +list: All matching UI elements and entities
+ +*Example:* +findAll('enemy*') # Find all elements starting with 'enemy'
+findAll('*_button') # Find all elements ending with '_button'
+ +Stop and remove a timer.
+ +*Args:* +name: Timer identifier to remove
+ +*Note:* +No error is raised if the timer doesn't exist.
+ +Cleanly shut down the game engine and exit the application.
+ +*Note:* +This immediately closes the window and terminates the program.
+ +Get current performance metrics.
+ +*Returns:* +dict: Performance data with keys:
+Scale the game window size.
+ +*Args:* +multiplier: Scale factor (e.g., 2.0 for double size)
+ +*Note:* +The internal resolution remains 1024x768, but the window is scaled.
+This is deprecated - use Window.resolution instead.
+ +Create or update a recurring timer.
+ +*Args:* +name: Unique identifier for the timer
+handler: Function called with (runtime: float) parameter
+interval: Time between calls in milliseconds
+ +*Note:* +If a timer with this name exists, it will be replaced.
+The handler receives the total runtime in seconds as its argument.
+ +The mcrfpy.automation
module provides testing and automation capabilities.
click(x=None, y=None, clicks=1, interval=0.0, button='left') - Click at position
+ +doubleClick(x=None, y=None) - Double click at position
+ +dragRel(xOffset, yOffset, duration=0.0, button='left') - Drag mouse relative to current position
+ +dragTo(x, y, duration=0.0, button='left') - Drag mouse to position
+ +hotkey(*keys) - Press a hotkey combination (e.g., hotkey('ctrl', 'c'))
+ +keyDown(key) - Press and hold a key
+ +keyUp(key) - Release a key
+ +middleClick(x=None, y=None) - Middle click at position
+ +mouseDown(x=None, y=None, button='left') - Press mouse button
+ +mouseUp(x=None, y=None, button='left') - Release mouse button
+ +moveRel(xOffset, yOffset, duration=0.0) - Move mouse relative to current position
+ +moveTo(x, y, duration=0.0) - Move mouse to absolute position
+ +onScreen(x, y) - Check if coordinates are within screen bounds
+ +position() - Get current mouse position as (x, y) tuple
+ +rightClick(x=None, y=None) - Right click at position
+ +screenshot(filename) - Save a screenshot to the specified file
+ +scroll(clicks, x=None, y=None) - Scroll wheel at position
+ +size() - Get screen size as (width, height) tuple
+ +tripleClick(x=None, y=None) - Triple click at position
+ +typewrite(message, interval=0.0) - Type text with optional interval between keystrokes
+ +')
+ in_code_block = True
+ continue
+
+ if in_code_block:
+ html.append(line)
+ continue
+
+ # Headers
+ if stripped.startswith('#'):
+ level = len(stripped.split()[0])
+ text = stripped[level:].strip()
+ html.append(f'{text} ')
+ # Lists
+ elif stripped.startswith('- '):
+ if not in_list:
+ html.append('')
+ in_list = True
+ html.append(f'- {stripped[2:]}
')
+ # Horizontal rule
+ elif stripped == '---':
+ if in_list:
+ html.append('
')
+ in_list = False
+ html.append('
')
+ # Emphasis
+ elif stripped.startswith('*') and stripped.endswith('*') and len(stripped) > 2:
+ html.append(f'{stripped[1:-1]}')
+ # Bold
+ elif stripped.startswith('**') and stripped.endswith('**'):
+ html.append(f'{stripped[2:-2]}')
+ # Regular paragraph
+ elif stripped:
+ if in_list:
+ html.append('')
+ in_list = False
+ # Convert inline code
+ text = stripped
+ if '`' in text:
+ import re
+ text = re.sub(r'`([^`]+)`', r'\1
', text)
+ html.append(f'{text}
')
+ else:
+ if in_list:
+ html.append('')
+ in_list = False
+ # Empty line
+ html.append('')
+
+ if in_list:
+ html.append('')
+ if in_code_block:
+ html.append('
')
+
+ html.append('')
+ return '\n'.join(html)
+
+def main():
+ """Generate API documentation in multiple formats."""
+ print("Generating McRogueFace API Documentation...")
+
+ # Create docs directory
+ docs_dir = Path("docs")
+ docs_dir.mkdir(exist_ok=True)
+
+ # Generate markdown documentation
+ print("- Generating Markdown documentation...")
+ markdown_content = generate_markdown_docs()
+
+ # Write markdown
+ md_path = docs_dir / "API_REFERENCE.md"
+ with open(md_path, 'w') as f:
+ f.write(markdown_content)
+ print(f" ✓ Written to {md_path}")
+
+ # Generate HTML
+ print("- Generating HTML documentation...")
+ html_content = generate_html_docs(markdown_content)
+
+ # Write HTML
+ html_path = docs_dir / "api_reference.html"
+ with open(html_path, 'w') as f:
+ f.write(html_content)
+ print(f" ✓ Written to {html_path}")
+
+ # Summary statistics
+ lines = markdown_content.split('\n')
+ class_count = markdown_content.count('### class')
+ func_count = len([l for l in lines if l.strip().startswith('### `') and 'class' not in l])
+
+ print("\nDocumentation Statistics:")
+ print(f"- Classes documented: {class_count}")
+ print(f"- Functions documented: {func_count}")
+ print(f"- Total lines: {len(lines)}")
+ print(f"- File size: {len(markdown_content):,} bytes")
+
+ print("\nAPI documentation generated successfully!")
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/generate_api_docs_simple.py b/generate_api_docs_simple.py
new file mode 100644
index 0000000..2bb405f
--- /dev/null
+++ b/generate_api_docs_simple.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""Generate API reference documentation for McRogueFace - Simple version."""
+
+import os
+import sys
+import datetime
+from pathlib import Path
+
+import mcrfpy
+
+def generate_markdown_docs():
+ """Generate markdown API documentation."""
+ lines = []
+
+ # Header
+ lines.append("# McRogueFace API Reference")
+ lines.append("")
+ lines.append("*Generated on {}*".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
+ lines.append("")
+
+ # Module description
+ if mcrfpy.__doc__:
+ lines.append("## Overview")
+ lines.append("")
+ lines.extend(mcrfpy.__doc__.strip().split('\n'))
+ lines.append("")
+
+ # Collect all components
+ classes = []
+ functions = []
+
+ for name in sorted(dir(mcrfpy)):
+ if name.startswith('_'):
+ continue
+
+ obj = getattr(mcrfpy, name)
+
+ if isinstance(obj, type):
+ classes.append((name, obj))
+ elif callable(obj):
+ functions.append((name, obj))
+
+ # Document classes
+ lines.append("## Classes")
+ lines.append("")
+
+ for name, cls in classes:
+ lines.append("### class {}".format(name))
+ if cls.__doc__:
+ doc_lines = cls.__doc__.strip().split('\n')
+ for line in doc_lines[:5]: # First 5 lines
+ lines.append(line)
+ lines.append("")
+ lines.append("---")
+ lines.append("")
+
+ # Document functions
+ lines.append("## Functions")
+ lines.append("")
+
+ for name, func in functions:
+ lines.append("### {}".format(name))
+ if func.__doc__:
+ doc_lines = func.__doc__.strip().split('\n')
+ for line in doc_lines[:5]: # First 5 lines
+ lines.append(line)
+ lines.append("")
+ lines.append("---")
+ lines.append("")
+
+ # Automation module
+ if hasattr(mcrfpy, 'automation'):
+ lines.append("## Automation Module")
+ lines.append("")
+
+ automation = mcrfpy.automation
+ for name in sorted(dir(automation)):
+ if not name.startswith('_'):
+ obj = getattr(automation, name)
+ if callable(obj):
+ lines.append("### automation.{}".format(name))
+ if obj.__doc__:
+ lines.append(obj.__doc__.strip().split('\n')[0])
+ lines.append("")
+
+ return '\n'.join(lines)
+
+def main():
+ """Generate API documentation."""
+ print("Generating McRogueFace API Documentation...")
+
+ # Create docs directory
+ docs_dir = Path("docs")
+ docs_dir.mkdir(exist_ok=True)
+
+ # Generate markdown
+ markdown_content = generate_markdown_docs()
+
+ # Write markdown
+ md_path = docs_dir / "API_REFERENCE.md"
+ with open(md_path, 'w') as f:
+ f.write(markdown_content)
+ print("Written to {}".format(md_path))
+
+ # Summary
+ lines = markdown_content.split('\n')
+ class_count = markdown_content.count('### class')
+ func_count = markdown_content.count('### ') - class_count - markdown_content.count('### automation.')
+
+ print("\nDocumentation Statistics:")
+ print("- Classes documented: {}".format(class_count))
+ print("- Functions documented: {}".format(func_count))
+ print("- Total lines: {}".format(len(lines)))
+
+ print("\nAPI documentation generated successfully!")
+ sys.exit(0)
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file