### Setup Development Environment Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Provides the command-line steps to clone the repository, create a virtual environment with uv, install dependencies, and configure git hooks. ```bash git clone git@github.com:yourusername/ARCEngine.git cd ARCEngine uv venv source .venv/bin/activate uv sync pre-commit install ``` -------------------------------- ### Create a Basic ARCEngine Game Source: https://github.com/arcprize/arcengine/blob/main/README.md A quick start example demonstrating how to create a simple game by subclassing ARCBaseGame and implementing the step() method. It shows game initialization with a level, sprite, and camera, and how to perform an action. ```python from arcengine import ARCBaseGame, ActionInput, Camera, GameAction, Level, Sprite class MyGame(ARCBaseGame): def step(self) -> None: # Your game logic here. # Call complete_action() when you are done handling the input. self.complete_action() level = Level([Sprite([[1]], name="player")]) # Camera is optional (defaults to 64x64). game = MyGame(game_id="my_game", levels=[level], camera=Camera()) # Multiple frames are returned if an animation was played as a result of the action frames = game.perform_action(ActionInput(id=GameAction.ACTION1)) ``` -------------------------------- ### Install ARCEngine Source: https://github.com/arcprize/arcengine/blob/main/README.md Instructions for installing the ARCEngine library using either uv or pip package managers. ```bash uv add arcengine # or pip install arcengine ``` -------------------------------- ### RenderableUserDisplay - Custom UI Overlays Source: https://context7.com/arcprize/arcengine/llms.txt Explains how to create custom UI elements that render on top of the game view using the `RenderableUserDisplay` abstract class. Includes an example of a health bar UI. ```APIDOC ## RenderableUserDisplay - UI Overlay System ### Description The `RenderableUserDisplay` abstract class allows creating custom UI overlays that render on top of the game after camera scaling. Implement the `render_interface` method to define your UI's drawing logic. ### Method - `render_interface(self, frame: np.ndarray) -> np.ndarray`: Abstract method to be implemented by subclasses for rendering UI elements onto the provided frame. - `draw_sprite(self, frame: np.ndarray, sprite: Sprite, x: int, y: int) -> np.ndarray`: Helper method to draw a sprite onto the frame at the specified coordinates. ### Parameters #### Request Body - **frame** (np.ndarray) - The current frame buffer to draw UI elements onto. - **sprite** (Sprite) - The sprite to draw. - **x** (int) - The x-coordinate for drawing the sprite. - **y** (int) - The y-coordinate for drawing the sprite. ### Request Example ```python from arcengine import RenderableUserDisplay, Sprite, Camera import numpy as np class HealthBarUI(RenderableUserDisplay): """Custom UI showing player health as colored bars.""" def __init__(self, max_health: int = 5): self.max_health = max_health self.current_health = max_health # Create heart sprites for each health point self.heart_full = Sprite([[8, 8], [8, 8]], name="heart_full") self.heart_empty = Sprite([[5, 5], [5, 5]], name="heart_empty") def set_health(self, health: int) -> None: self.current_health = max(0, min(health, self.max_health)) def render_interface(self, frame: np.ndarray) -> np.ndarray: """Render health bar at top of screen.""" for i in range(self.max_health): x_pos = 2 + (i * 5) # Space hearts 5 pixels apart y_pos = 2 if i < self.current_health: frame = self.draw_sprite(frame, self.heart_full, x_pos, y_pos) else: frame = self.draw_sprite(frame, self.heart_empty, x_pos, y_pos) return frame # Using custom UI with camera health_ui = HealthBarUI(max_health=3) health_ui.set_health(2) camera = Camera( width=32, height=32, interfaces=[health_ui], # Add UI overlay ) # UI renders after camera scaling, always in 64x64 space sprites = [Sprite([[1]], x=5, y=5)] frame = camera.render(sprites) # Frame includes UI overlay # Replace interfaces at runtime new_ui = HealthBarUI(max_health=5) camera.replace_interface([new_ui]) ``` ``` -------------------------------- ### Install ARCEngine using uv Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md This snippet shows how to add ARCEngine to your project's dependencies in pyproject.toml and install it using the uv package manager. ```toml [project] dependencies = [ "arcengine @ git+ssh://git@github.com/arcprize/ARCEngine.git@main", ] ``` ```bash uv sync ``` -------------------------------- ### Merge Puzzle Game Example (Python) Source: https://context7.com/arcprize/arcengine/llms.txt A complete example of a Merge Puzzle game using ArcEngine. It showcases sprite creation, level setup, player movement, sprite merging logic, collision detection, and win condition checking. ```python from arcengine import ( ARCBaseGame, ActionInput, Camera, GameAction, Level, Sprite, BlockingMode, InteractionMode ) import numpy as np class MergePuzzle(ARCBaseGame): """Puzzle game: merge sprites to match the target pattern.""" def __init__(self) -> None: # Player sprite (can merge with other sprites) player = Sprite( pixels=[[9]], name="player", x=3, y=10, blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, tags=["merge"], ) # Piece to merge with piece = Sprite( pixels=[[8, 8], [-1, 8]], name="piece", x=4, y=5, blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, tags=["merge"], ) # Target pattern to match target = Sprite( pixels=[[8, 8], [9, 8]], name="target", x=12, y=2, blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, tags=["target"], ) # Walls walls = Sprite( pixels=[ [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, -1, -1, -1, -1, -1, -1], [5, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1], [5, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1], [5, -1, -1, -1, -1, -1, -1, -1, -1, 5, 5, 5, 5, 5, 5, 5], [5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5], [5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], ], name="walls", blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, layer=-1, ) level = Level( sprites=[walls, player, piece, target], grid_size=(16, 16), name="Merge Level 1", ) camera = Camera(width=16, height=16, background=1, letter_box=3) super().__init__(game_id="merge_puzzle", levels=[level], camera=camera) self._player = player self._target = target def on_set_level(self, level: Level) -> None: """Called when level changes - cache sprite references.""" players = level.get_sprites_by_name("player") targets = level.get_sprites_by_tag("target") if players: self._player = players[0] if targets: self._target = targets[0] def step(self) -> None: dx, dy = 0, 0 if self.action.id == GameAction.ACTION1: dy = -1 elif self.action.id == GameAction.ACTION2: dy = 1 elif self.action.id == GameAction.ACTION3: dx = -1 elif self.action.id == GameAction.ACTION4: dx = 1 if dx != 0 or dy != 0: collisions = self.try_move_sprite(self._player, dx, dy) for sprite in collisions: if "merge" in sprite.tags: # Merge player with the collided sprite old_player = self._player self._player = self._player.merge(sprite) # Update level sprites self.current_level.remove_sprite(sprite) self.current_level.remove_sprite(old_player) self.current_level.add_sprite(self._player) # Move merged sprite self._player.move(dx, dy) # Check win condition: player pattern matches target if self._check_win(): self.next_level() self.complete_action() def _check_win(self) -> bool: """Check if player pixels match target pixels.""" player_pixels = self.get_pixels_at_sprite(self._player) target_pixels = self.get_pixels_at_sprite(self._target) return np.array_equal(player_pixels, target_pixels) # Run the game game = MergePuzzle() ``` -------------------------------- ### Implement Custom UI Rendering with RenderableUserDisplay in Python Source: https://github.com/arcprize/arcengine/blob/main/README.md Shows how to create a custom user interface element by inheriting from the abstract base class `RenderableUserDisplay`. The example demonstrates overriding the `render_interface` method to modify the camera's frame. ```python import numpy as np from arcengine import RenderableUserDisplay, Sprite class MyUI(RenderableUserDisplay): def render_interface(self, frame: np.ndarray) -> np.ndarray: # Modify the frame in-place and return it return frame ``` -------------------------------- ### Create a Sprite Instance Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Provides examples of creating Sprite objects in ARCEngine. Sprites can be initialized with pixel data and various properties like name, position, scale, rotation, blocking mode, layer, and interaction mode. ```python from arcengine import Sprite, BlockingMode, InteractionMode # Create a simple 2x2 sprite sprite = Sprite([ [1, 2], [3, 4] ]) # Create a sprite with custom properties sprite = Sprite( pixels=[[1, 2], [3, 4]], name="player", x=10, y=20, scale=2, rotation=90, blocking=BlockingMode.BOUNDING_BOX, layer=1, # Higher values render on top interaction=InteractionMode.TANGIBLE ) ``` -------------------------------- ### Sprite Methods: Clone, Set Position, and Move Source: https://github.com/arcprize/arcengine/blob/main/README.md Provides examples of common Sprite manipulation methods. `clone()` creates an independent copy, `set_position()` updates the sprite's coordinates, and `move()` adjusts its position by given deltas. ```python # Create a sprite sprite = Sprite([[1]]) # Clone the sprite sprite_copy = sprite.clone("player_copy") # Set the sprite's position sprite.set_position(50, 100) # Move the sprite sprite.move(10, -5) ``` -------------------------------- ### Get Camera Pixels by Region Source: https://github.com/arcprize/arcengine/blob/main/README.md Fetches camera pixel data for a specified rectangular region. This function allows for targeted image sampling from the camera's view. ```python import numpy as np # x, y: top-left corner coordinates # width, height: dimensions of the region # pixels_region = get_pixels(x=10, y=20, width=50, height=60) # print(pixels_region.shape) # Example: (height, width, channels) ``` -------------------------------- ### Implement Game Logic with ARCBaseGame in Python Source: https://context7.com/arcprize/arcengine/llms.txt Subclass ARCBaseGame to define custom game logic, including sprite initialization, level setup, and handling player actions within the step() method. The engine manages the game loop and rendering. ```Python from arcengine import ARCBaseGame, ActionInput, Camera, GameAction, Level, Sprite, BlockingMode, InteractionMode class MyMazeGame(ARCBaseGame): """A simple maze game with player movement and collision detection.""" def __init__(self) -> None: # Define sprites player = Sprite( pixels=[[8]], # Single red pixel name="player", x=1, y=1, blocking=BlockingMode.BOUNDING_BOX, interaction=InteractionMode.TANGIBLE, ) exit_goal = Sprite( pixels=[[9]], # Blue exit marker name="exit", x=6, y=6, blocking=BlockingMode.BOUNDING_BOX, interaction=InteractionMode.TANGIBLE, ) maze_walls = Sprite( pixels=[ [5, 5, 5, 5, 5, 5, 5, 5], [5, -1, -1, -1, 5, -1, -1, 5], # -1 = transparent [5, -1, 5, -1, 5, -1, 5, 5], [5, -1, 5, -1, -1, -1, -1, 5], [5, -1, 5, 5, 5, 5, -1, 5], [5, -1, -1, -1, -1, 5, -1, 5], [5, 5, 5, 5, -1, -1, -1, 5], [5, 5, 5, 5, 5, 5, 5, 5], ], name="walls", blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, layer=-1, # Render below player ) # Create level with sprites level = Level( sprites=[maze_walls, player, exit_goal], grid_size=(8, 8), name="Level 1" ) # Initialize with custom camera camera = Camera(background=0, letter_box=3) super().__init__(game_id="my_maze", levels=[level], camera=camera) def step(self) -> None: """Process player input and update game state.""" dx, dy = 0, 0 if self.action.id == GameAction.ACTION1: # Up dy = -1 elif self.action.id == GameAction.ACTION2: # Down dy = 1 elif self.action.id == GameAction.ACTION3: # Left dx = -1 elif self.action.id == GameAction.ACTION4: # Right dx = 1 # try_move returns list of collided sprites, moves player if no collision collisions = self.try_move("player", dx, dy) # Check if player reached the exit if any(sprite.name == "exit" for sprite in collisions): if self.is_last_level(): self.win() else: self.next_level() self.complete_action() # Required: signals action is finished # Create and run the game game = MyMazeGame() # Perform actions and get rendered frames frame_data = game.perform_action(ActionInput(id=GameAction.ACTION4)) # Move right print(f"Game state: {frame_data.state}") print(f"Frames generated: {len(frame_data.frame)}") # frame_data.frame contains list of 64x64 pixel arrays ``` -------------------------------- ### Configure and Use Camera for Rendering Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates how to initialize a camera with custom dimensions, move it, resize the viewport, and render sprites into a 64x64 output. It also shows how to map display coordinates back to world coordinates. ```python camera = Camera(x=0, y=0, width=32, height=32, background=5, letter_box=5) camera.move(dx=10, dy=5) camera.resize(width=16, height=16) sprites = [Sprite([[1, 2], [3, 4]], x=5, y=5), Sprite([[8]], x=10, y=10)] frame = camera.render(sprites) world_coords = camera.display_to_grid(display_x=32, display_y=32) ``` -------------------------------- ### Initialize and Configure Camera Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Demonstrates how to instantiate a default Camera or a custom Camera with specific viewport dimensions, background colors, and interface lists. The Camera handles rendering a 64x64 viewport from the game world. ```python from arcengine import Camera, RenderableUserDisplay # Create a default camera (64x64 viewport) camera = Camera() # Create a custom camera camera = Camera( x=10, # X position in pixels y=20, # Y position in pixels width=32, # Viewport width (max 64) height=32, # Viewport height (max 64) background=1, # Background color index letter_box=2, # Letter box color index interfaces=[], # Optional list of renderable interfaces ) ``` -------------------------------- ### Initialize and Configure Camera in Python Source: https://github.com/arcprize/arcengine/blob/main/README.md Demonstrates how to create a Camera object in Python, both with default settings and custom parameters for position, viewport size, and colors. The camera's output is always 64x64 pixels, with scaling and letterboxing applied. ```python from arcengine import Camera # Create a default camera (64x64 viewport) camera = Camera() # Create a custom camera camera = Camera( x=10, # X position in pixels y=20, # Y position in pixels width=32, # Viewport width (max 64) height=32, # Viewport height (max 64) background=1, # Background color index letter_box=2, # Letter box color index interfaces=[], # Optional list of renderable interfaces ) ``` -------------------------------- ### Initialize and Scale Sprite Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Demonstrates how to instantiate a new Sprite object and apply various scaling factors, including upscaling and downscaling. ```python sprite = Sprite([[1, 2], [3, 4]]) # Upscaling examples sprite.set_scale(2) # Doubles size in both dimensions sprite.set_scale(3) # Triples size in both dimensions # Downscaling examples sprite.set_scale(-1) # Half size (divide dimensions by 2) sprite.set_scale(-2) # One-third size (divide dimensions by 3) sprite.set_scale(-3) # One-fourth size (divide dimensions by 4) ``` -------------------------------- ### Get Camera Pixels by Sprite Source: https://github.com/arcprize/arcengine/blob/main/README.md Retrieves camera pixel data at the location of a given sprite. This is useful for analyzing visual information associated with specific game entities. ```python import numpy as np from arcengine import Sprite # Assume 'my_sprite' is an existing Sprite object # pixels_at_sprite = get_pixels_at_sprite(my_sprite) # print(pixels_at_sprite.shape) # Example: (height, width, channels) ``` -------------------------------- ### Run Development Tools Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Commands to manually execute linting, formatting, and type checking tools using pre-commit. ```bash pre-commit run --all-files ``` -------------------------------- ### Initialize Level with Sprites Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Demonstrates how to instantiate the Level class, either as an empty container or pre-populated with a list of Sprite objects. ```python from arcengine import Level, Sprite # Create an empty level level = Level() # Create a level with initial sprites sprites = [ Sprite([[1]], name="player"), Sprite([[2]], name="enemy") ] level = Level(sprites=sprites) ``` -------------------------------- ### Game State and Score Tracking (Python) Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates how to access game state information like win/loss conditions, score, and player actions. It also shows how to retrieve available actions and check for full game resets. ```python # GameState.NOT_FINISHED - Game in progress # GameState.WIN - Player won # GameState.GAME_OVER - Player lost # Score tracking print(f"Levels completed: {result.levels_completed}") print(f"Levels to win: {result.win_levels}") # Action that was performed print(f"Action: {result.action_input.id}") # Check if full reset occurred if result.full_reset: print("Game was fully reset") # Get available actions print(f"Available actions: {result.available_actions}") # For raw numpy frames instead of lists raw_result = game.perform_action(ActionInput(id=GameAction.ACTION1), raw=True) # raw_result.frame contains numpy arrays instead of nested lists ``` -------------------------------- ### Create Custom UI Overlays with RenderableUserDisplay Source: https://context7.com/arcprize/arcengine/llms.txt Shows how to extend RenderableUserDisplay to create custom UI elements like health bars that render over the game scene after camera scaling. ```python class HealthBarUI(RenderableUserDisplay): def render_interface(self, frame: np.ndarray) -> np.ndarray: for i in range(self.max_health): x_pos = 2 + (i * 5) y_pos = 2 if i < self.current_health: frame = self.draw_sprite(frame, self.heart_full, x_pos, y_pos) else: frame = self.draw_sprite(frame, self.heart_empty, x_pos, y_pos) return frame health_ui = HealthBarUI(max_health=3) camera = Camera(width=32, height=32, interfaces=[health_ui]) ``` -------------------------------- ### Create and Configure a Sprite Source: https://github.com/arcprize/arcengine/blob/main/README.md Demonstrates the creation of a Sprite object, both with default settings and custom properties. Sprites represent 2D objects with position, scale, rotation, and interaction behaviors. Notes on pixel transparency and scaling are provided. ```python from arcengine import Sprite, BlockingMode, InteractionMode # Create a simple 2x2 sprite sprite_simple = Sprite([ [1, 2], [3, 4] ]) # Create a sprite with custom properties sprite_custom = Sprite( pixels=[[1, 2], [3, 4]], name="player", x=10, y=20, layer=1, scale=2, rotation=90, mirror_ud=False, mirror_lr=False, blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, # If interaction is None, visible/collidable determine the mode. # visible=True, collidable=True are the defaults. tags=["player"], ) ``` -------------------------------- ### Camera Viewport Configuration Source: https://context7.com/arcprize/arcengine/llms.txt Initializes the camera viewport for rendering the game world to the output grid. ```python from arcengine import Camera camera = Camera() ``` -------------------------------- ### Implement Custom UI Element Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Shows how to create a custom UI element by extending the RenderableUserDisplay abstract base class. Users must implement the render_interface method to modify the 64x64 frame directly. ```python from abc import ABC, abstractmethod from arcengine import RenderableUserDisplay class MyCustomUI(RenderableUserDisplay): def render_interface(self, frame: np.ndarray) -> None: # Implement custom rendering logic here pass ``` -------------------------------- ### Initialize and Configure Level Source: https://github.com/arcprize/arcengine/blob/main/README.md Demonstrates how to instantiate a Level object with sprites, grid dimensions, and metadata. This is the primary way to define the game environment in ARCEngine. ```python from arcengine import Level, Sprite, PlaceableArea sprites = [ Sprite([[1]], name="player"), Sprite([[2]], name="enemy") ] # Create an empty level level_empty = Level() # Create a level with initial sprites level = Level( sprites=sprites, grid_size=(16, 16), data={"difficulty": "easy"}, name="level_1", ) ``` -------------------------------- ### Implement Game Actions and Input Handling Source: https://context7.com/arcprize/arcengine/llms.txt Shows how to define player actions using GameAction and ActionInput, and how to process these inputs within a custom game class inheriting from ARCBaseGame. ```python click_action = ActionInput(id=GameAction.ACTION6, data={"x": 32, "y": 32}) class ClickGame(ARCBaseGame): def step(self) -> None: if self.action.id == GameAction.ACTION6: world_pos = self.camera.display_to_grid(self.action.data.get("x"), self.action.data.get("y")) if world_pos: print(f"Clicked on: {self.current_level.get_sprite_at(*world_pos).name}") self.complete_action() ``` -------------------------------- ### Simulate Gameplay Actions in ARCEngine Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates how to execute a sequence of game actions using the ARCEngine framework. It iterates through a list of actions, performs them via the game engine, and checks for a win state. ```python actions = [ GameAction.ACTION1, # Up GameAction.ACTION1, # Up (merge with piece) GameAction.ACTION4, # Right GameAction.ACTION4, # Right ] for action in actions: result = game.perform_action(ActionInput(id=action)) print(f"Action: {action.name}, State: {result.state}") if result.state.value == "WIN": print("Puzzle solved!") break ``` -------------------------------- ### Initialize ARCBaseGame Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Demonstrates how to create an instance of ARCBaseGame, the base class for ARCEngine games. It manages levels and camera, and requires a game_id. A custom camera can be provided, otherwise a default one is used. ```python from arcengine import ARCBaseGame, Level, Camera # Create a game with levels and optional custom camera game = ARCBaseGame(game_id="my_gane", levels=[level1, level2], camera=camera) # camera is optional ``` -------------------------------- ### Sprite Transformation and Interaction Management Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates how to manipulate sprite properties such as position, rotation, scale, and visibility. It also shows how to manage interaction modes and perform collision detection between sprites. ```python player.set_position(10, 15) player.move(1, 0) player.set_rotation(180) player.rotate(90) player.set_scale(3) player.set_mirror_lr(True) player.set_interaction(InteractionMode.TANGIBLE) rendered_pixels = player.render() if player.collides_with(wall): print("Collision detected!") player_copy = player.clone(new_name="player_clone") ``` -------------------------------- ### Sprite Initialization Parameters Source: https://github.com/arcprize/arcengine/blob/main/README.md Details the parameters for initializing a Sprite object. This includes pixel data, name, position, layer, scale, rotation, mirroring, blocking behavior, interaction mode, visibility, collidability, and tags. It also specifies potential ValueErrors. ```python sprite = Sprite( pixels=[[1, 2], [3, 4]], name="player", x=10, y=20, layer=1, scale=2, rotation=90, mirror_ud=False, mirror_lr=False, blocking=BlockingMode.PIXEL_PERFECT, interaction=None, visible=True, collidable=True, tags=["player"], ) ``` -------------------------------- ### Configure Sprite Interaction and Collision Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates how to define Sprite interaction modes (tangible, intangible, invisible, removed) and perform collision checks between sprites using blocking modes. ```python player = Sprite([[8]], interaction=InteractionMode.TANGIBLE) decoration = Sprite([[3]], interaction=InteractionMode.INTANGIBLE) trigger_zone = Sprite([[0]], interaction=InteractionMode.INVISIBLE) disabled = Sprite([[1]], interaction=InteractionMode.REMOVED) # Collision check sprite_a = Sprite([[1]], x=0, y=0, blocking=BlockingMode.PIXEL_PERFECT) sprite_b = Sprite([[2]], x=0, y=0, blocking=BlockingMode.PIXEL_PERFECT) print(sprite_a.collides_with(sprite_b)) ``` -------------------------------- ### Perform Action with ARCBaseGame Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Shows how to use the perform_action method of ARCBaseGame to process game actions and retrieve resulting frame data. Game logic should be implemented in the step() method, and complete_action() should be called when an action is resolved. ```python # Perform an action and return the resulting frame data frame_data = game.perform_action(action_input) # Complete the action when it's fully resolved game.complete_action() ``` -------------------------------- ### Configure Sprite Collision and Interaction Modes Source: https://context7.com/arcprize/arcengine/llms.txt Explains how to use BlockingMode and InteractionMode to define how sprites behave during collision detection and their visibility in the game world. ```python ghost = Sprite([[7, 7], [7, 7]], name="ghost", blocking=BlockingMode.NOT_BLOCKED) box = Sprite([[5, 5, 5], [5, -1, 5], [5, 5, 5]], name="box", blocking=BlockingMode.BOUNDING_BOX) wall = Sprite([[5, 5, 5], [5, -1, 5], [5, 5, 5]], name="wall", blocking=BlockingMode.PIXEL_PERFECT) ``` -------------------------------- ### Sprite Color Remapping and Merging Source: https://context7.com/arcprize/arcengine/llms.txt Shows how to modify the color palette of a sprite and how to combine multiple sprites into a single entity. ```python sprite.color_remap(old_color=1, new_color=5) sprite_a = Sprite([[1, -1], [-1, 1]], name="a", x=0, y=0) sprite_b = Sprite([[-1, 2], [2, -1]], name="b", x=0, y=0) merged = sprite_a.merge(sprite_b) ``` -------------------------------- ### Manage Toggleable UI Elements Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Demonstrates using the ToggleableUserDisplay class to manage sprite pairs with enabled/disabled states. It allows for easy toggling and status checking of UI components. ```python from arcengine import ToggleableUserDisplay, Sprite # Create a toggleable UI element with sprite pairs ui_element = ToggleableUserDisplay([ (enabled_sprite1, disabled_sprite1), (enabled_sprite2, disabled_sprite2) ]) # Enable/disable specific sprite pairs ui_element.enable(0) # Enable first pair ui_element.disable(1) # Disable second pair # Check if a pair is enabled is_enabled = ui_element.is_enabled(0) ``` -------------------------------- ### Create and Configure 2D Sprites in Python Source: https://context7.com/arcprize/arcengine/llms.txt Define game objects using the Sprite class, specifying pixel data, position, scale, rotation, mirroring, and collision properties. Sprites can have tags for easier identification and management. ```Python from arcengine import Sprite, BlockingMode, InteractionMode import numpy as np # Create a simple 2x2 sprite simple_sprite = Sprite( pixels=[[1, 2], [3, 4]], name="my_sprite", x=10, y=20, layer=1, # Higher layers render on top ) # Create sprite with full configuration player = Sprite( pixels=[ [8, 8, 8], [8, 9, 8], [8, 8, 8], ], name="player", x=5, y=5, scale=2, # 2x upscale (6x6 rendered size) rotation=90, # Valid: 0, 90, 180, 270 mirror_ud=False, # Vertical flip mirror_lr=False, # Horizontal flip blocking=BlockingMode.PIXEL_PERFECT, interaction=InteractionMode.TANGIBLE, tags=["player", "controllable"], ) ``` -------------------------------- ### Main Game Loop Logic Source: https://github.com/arcprize/arcengine/blob/main/arcengine/OVERVIEW.md The core game loop processes the RESET action, checks for win/loss states, and executes the STEP and RENDER functions to generate frames. ```pseudocode handle RESET action if game is won or lost: return [] frames = [] while action is not complete: STEP() frames.append(RENDER()) return frames ``` -------------------------------- ### ToggleableUserDisplay Methods Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Methods for managing sprite pair states and rendering the UI interface. ```APIDOC ## POST /toggleable_user_display/enable ### Description Enables a specific sprite pair by its index. ### Method POST ### Parameters #### Request Body - **index** (int) - Required - The index of the sprite pair to enable. ### Response #### Success Response (200) - **status** (string) - Success message. ## POST /toggleable_user_display/disable ### Description Disables a specific sprite pair by its index. ### Method POST ### Parameters #### Request Body - **index** (int) - Required - The index of the sprite pair to disable. ## POST /toggleable_user_display/render ### Description Renders the UI element onto a provided 64x64 frame. ### Method POST ### Parameters #### Request Body - **frame** (numpy.ndarray) - Required - The 64x64 array to render onto. ``` -------------------------------- ### Handle Action Results with FrameData Source: https://context7.com/arcprize/arcengine/llms.txt Explains how to retrieve and inspect FrameData after performing a game action, including accessing rendered frames and game state information. ```python result = game.perform_action(ActionInput(id=GameAction.ACTION1)) print(f"Game ID: {result.game_id}") print(f"Frames: {len(result.frame)}") print(f"State: {result.state}") ``` -------------------------------- ### Import Core Arc Engine Components Source: https://github.com/arcprize/arcengine/blob/main/README.md Imports essential classes for game development from the arcengine library. These include base game functionality, camera handling, and level management. ```python from arcengine import ( ARCBaseGame, Camera, Level, ) ``` -------------------------------- ### Sprite Interaction Modes and Collision Source: https://context7.com/arcprize/arcengine/llms.txt Demonstrates different interaction modes for Sprites (TANGIBLE, INTANGIBLE, INVISIBLE, REMOVED) and how they affect visibility and collidability. Also shows sprite collision detection with and without ignoring interaction modes. ```APIDOC ## Sprite Interaction Modes and Collision ### Description This section details the various interaction modes available for Sprites in ArcEngine and how they influence their properties like visibility and collidability. It also illustrates sprite-to-sprite collision detection, including the `ignoreMode` parameter. ### Sprite Interaction Modes - **TANGIBLE**: Visible and collidable. - **INTANGIBLE**: Visible but not collidable. - **INVISIBLE**: Not visible but collidable. - **REMOVED**: Not visible and not collidable (effectively deleted). ### Collision Detection Sprites can collide with each other. The `collides_with` method checks for overlap. The `ignoreMode` parameter can be used to bypass interaction mode checks during collision detection. ### Request Example ```python from arcengine import Sprite, InteractionMode, BlockingMode player = Sprite([[8]], interaction=InteractionMode.TANGIBLE) decoration = Sprite([[3]], interaction=InteractionMode.INTANGIBLE) trigger_zone = Sprite([[0]], interaction=InteractionMode.INVISIBLE) disabled = Sprite([[1]], interaction=InteractionMode.REMOVED) # Check interaction properties print(player.is_visible) # True print(player.is_collidable) # True print(decoration.is_visible) # True print(decoration.is_collidable) # False print(trigger_zone.is_visible) # False print(trigger_zone.is_collidable) # True # Collision between sprites considers both blocking mode and interaction sprite_a = Sprite([[1]], x=0, y=0, blocking=BlockingMode.PIXEL_PERFECT) sprite_b = Sprite([[2]], x=0, y=0, blocking=BlockingMode.PIXEL_PERFECT) print(sprite_a.collides_with(sprite_b)) # True (overlapping) # Ignore interaction mode for collision check sprite_a.collides_with(sprite_b, ignoreMode=True) ``` ``` -------------------------------- ### ARCBaseGame Class Source: https://context7.com/arcprize/arcengine/llms.txt The foundation class for all ARCEngine games. Developers subclass this to implement game logic, handle input, and manage level progression. ```APIDOC ## CLASS ARCBaseGame ### Description The base class for defining game logic. It manages the game loop, rendering, and frame generation. Users must implement the `step()` method. ### Methods - **step()**: Called every turn to process game logic. - **try_move(name, dx, dy)**: Attempts to move a sprite; returns list of collided sprites. - **perform_action(action_input)**: Executes a game action and returns the rendered frame data. - **win()**: Signals game completion. - **next_level()**: Transitions to the next level in the sequence. ### Request Example ```python game = MyMazeGame() frame_data = game.perform_action(ActionInput(id=GameAction.ACTION4)) ``` ### Response - **frame_data** (object) - Contains the updated game state and the 64x64 pixel frame array. ``` -------------------------------- ### FrameData - Action Result Container Source: https://context7.com/arcprize/arcengine/llms.txt Describes the `FrameData` class, which serves as a container for the results of performing an action in the game, including rendered frames, game state, and score. ```APIDOC ## FrameData - Action Result Container ### Description The `FrameData` class contains the results of performing an action, including rendered frames, game state, and score information. It is returned by the `perform_action` method of an `ARCBaseGame` instance. ### Properties - **game_id** (str): The unique identifier of the game. - **frame** (List[np.ndarray]): A list of rendered frames (pixel arrays) from the action. - **state** (GameState): The final state of the game after the action was performed. ### Game States - **GameState.NOT_PLAYED**: Initial state before any action is taken. - **GameState.PLAYING**: The game is currently in progress. - **GameState.WON**: The player has won the game. - **GameState.LOST**: The player has lost the game. - **GameState.TIED**: The game ended in a tie. - **GameState.QUIT**: The game was quit by the player or system. ### Request Example ```python from arcengine import ARCBaseGame, ActionInput, GameAction, GameState, Level, Sprite # Create a simple game level = Level([Sprite([[1]], name="player", x=5, y=5)]) class SimpleGame(ARCBaseGame): def step(self) -> None: self.complete_action() game = SimpleGame(game_id="demo", levels=[level]) # Perform action and get FrameData result = game.perform_action(ActionInput(id=GameAction.ACTION1)) # Access frame data properties print(f"Game ID: {result.game_id}") print(f"Frames: {len(result.frame)}") # List of 64x64 pixel arrays print(f"State: {result.state}") # GameState enum ``` ``` -------------------------------- ### ToggleableUserDisplay - Toggle-based UI Elements Source: https://context7.com/arcprize/arcengine/llms.txt Details the `ToggleableUserDisplay` class for managing UI elements that switch between enabled and disabled states using sprite pairs. Supports toggling by index or tag. ```APIDOC ## ToggleableUserDisplay - Toggle-based UI Elements ### Description The `ToggleableUserDisplay` class manages sprite pairs that can be toggled between enabled/disabled states, useful for indicators, checkboxes, and status displays. Toggling can be performed by index or by applying actions to all elements with a specific tag. ### Methods - `enable(self, index: int)`: Enables the sprite pair at the given index. - `disable(self, index: int)`: Disables the sprite pair at the given index. - `is_enabled(self, index: int) -> bool`: Checks if the sprite pair at the given index is currently enabled. - `enable_all_by_tag(self, tag: str)`: Enables all sprite pairs associated with the given tag. - `disabled_all_by_tag(self, tag: str)`: Disables all sprite pairs associated with the given tag. - `enable_first_by_tag(self, tag: str) -> bool`: Enables the first found sprite pair with the given tag and returns True if successful. - `disabled_first_by_tag(self, tag: str) -> bool`: Disables the first found sprite pair with the given tag and returns True if successful. - `clone(self)`: Creates an independent copy of the `ToggleableUserDisplay` instance. ### Parameters #### Request Body - **index** (int) - The index of the sprite pair to toggle. - **tag** (str) - The tag used to identify and group sprite pairs. ### Request Example ```python from arcengine import ToggleableUserDisplay, Sprite, Camera # Create sprite pairs (enabled_sprite, disabled_sprite) checkbox_on = Sprite([[9, 9], [9, 9]], name="check_on", x=5, y=5, tags=["checkbox"]) checkbox_off = Sprite([[5, 5], [5, 5]], name="check_off", x=5, y=5, tags=["checkbox"]) star_filled = Sprite([[6]], name="star_on", x=15, y=5, tags=["star"]) star_empty = Sprite([[0]], name="star_off", x=15, y=5, tags=["star"]) # Create toggleable UI with sprite pairs ui = ToggleableUserDisplay([ (checkbox_on, checkbox_off), # Index 0 (star_filled, star_empty), # Index 1 ]) # Toggle by index ui.enable(0) # Show checkbox_on, hide checkbox_off ui.disable(1) # Show star_empty, hide star_filled # Check state if ui.is_enabled(0): print("Checkbox is checked") # Toggle by tag ui.enable_all_by_tag("star") # Enable all star pairs ui.disabled_all_by_tag("checkbox") # Disable all checkbox pairs # Toggle first matching disabled/enabled by tag ui.enable_first_by_tag("star") # Returns True if found and enabled ui.disabled_first_by_tag("star") # Returns True if found and disabled # Clone for independent copy ui_copy = ui.clone() # Add to camera camera = Camera(interfaces=[ui]) ``` ``` -------------------------------- ### Sprite Manipulation API Source: https://github.com/arcprize/arcengine/blob/main/README.md Methods for color remapping and merging sprites. ```APIDOC ## Sprite Manipulation API ### Description This section covers methods for manipulating sprite colors and merging sprites. ### Methods #### `color_remap(old_color, new_color)` ##### Description Remap colors within the sprite. ##### Parameters - **old_color** (tuple or None) - Required - The old color to remap (e.g., RGB tuple), or None to remap all colors. - **new_color** (tuple) - Required - The new color to remap to (e.g., RGB tuple). #### `merge(other)` ##### Description Merge this sprite with another sprite, creating a new sprite with combined pixels. ##### Parameters - **other** (Sprite) - Required - The other sprite to merge with. ##### Returns - A new `Sprite` instance containing the merged pixels. Overlapping pixels prioritize non -1 values. ``` -------------------------------- ### Cite ARC Game Engine in BibTeX Source: https://github.com/arcprize/arcengine/blob/main/README.md This snippet provides the standard BibTeX entry for referencing the ARC Game Engine in academic or technical research papers. It includes the author, title, year, URL, and version information. ```bibtex @software{arc_agi, author = {ARC Prize Foundation}, title = {ARC Game Engine}, year = {2026}, url = {https://github.com/arcprize/ARCEngine}, version = {0.9.3} } ``` -------------------------------- ### Sprite Rendering and Collision API Source: https://github.com/arcprize/arcengine/blob/main/README.md Methods for rendering a sprite and checking for collisions with other sprites. ```APIDOC ## Sprite Rendering and Collision API ### Description This section covers methods related to rendering a sprite and detecting collisions. ### Methods #### `render()` ##### Description Render the sprite with its current scale and rotation. ##### Returns - A 2D numpy array representing the rendered sprite. ##### Raises - `ValueError` if a downscaling factor does not evenly divide the sprite dimensions. #### `collides_with(other, ignoreMode=False)` ##### Description Check if this sprite collides with another sprite, considering interaction and blocking modes. ##### Parameters - **other** (Sprite) - Required - The other sprite to check collision with. - **ignoreMode** (bool) - Optional - If True, bypasses interaction and blocking checks. ##### Returns - True if the sprites collide, False otherwise. ##### Collision Rules: 1. A sprite cannot collide with itself. 2. Non-collidable sprites never collide (unless `ignoreMode=True`). 3. For collidable sprites, collision detection depends on their blocking mode: - `NOT_BLOCKED`: Always returns False. - `BOUNDING_BOX`: Simple rectangular collision check. - `PIXEL_PERFECT`: Precise pixel-level collision detection. ``` -------------------------------- ### Move Sprite with Collision Detection Source: https://github.com/arcprize/arcengine/blob/main/arcengine/README.md Illustrates the try_move method for sprites in ARCEngine. This method attempts to move a sprite by specified deltas (dx, dy) and returns a list of sprites it collides with. If collisions occur, the sprite's position is not updated. ```python # Try to move a sprite right by 1 pixel collisions = game.try_move("player", 1, 0) if not collisions: print("Move successful!") else: print(f"Collided with: {[sprite.name for sprite in collisions]}") ```