### Example: Getting Action IDs from Tuples Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Demonstrates converting human-readable action combinations (arrow, button) into their corresponding integer action IDs. ```python action_id = env.get_action_id("up", "A") # Converts to action index action_id = env.get_action_id(None, "start") ``` -------------------------------- ### Example: Closing the Environment Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md A simple example showing the call to `env.close()` to release resources. ```python env.close() # Free pygame resources ``` -------------------------------- ### Example: Rendering Environment Frames Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Demonstrates how to step through the environment and render frames. This example uses 'human' render mode to display the game visually. ```python env = PyGBAEnv(gba, game_wrapper, render_mode="human") for _ in range(10): obs, reward, done, truncated, info = env.step(0) env.render() # Display on screen ``` -------------------------------- ### Example Reward Implementation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md An example implementation of the reward method. This specific example calculates reward based on the change in the current level read from game memory. ```python def reward(self, gba: PyGBA, observation: np.ndarray) -> float: if observation is None or observation.sum() < 1: return 0.0 current_level = gba.read_u8(0x02024f00) reward = (current_level - self.prev_level) * 0.5 self.prev_level = current_level return reward ``` -------------------------------- ### Example Info Implementation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md An example implementation of the info method. This returns a dictionary containing the current level, HP, and player location, read from specific memory addresses. ```python def info(self, gba: PyGBA, observation: np.ndarray) -> dict[str, Any]: return { "level": gba.read_u8(0x02024f00), "hp": gba.read_u16(0x02024f10), "location": gba.read_u16(0x02024f20), } ``` -------------------------------- ### Example: Getting Action Tuples from IDs Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Shows how to use `get_action_by_id` to retrieve the corresponding arrow key and button for specific action IDs. ```python arrow, button = env.get_action_by_id(0) # (None, None) arrow, button = env.get_action_by_id(1) # (None, "A") arrow, button = env.get_action_by_id(5) # ("up", None) ``` -------------------------------- ### Read Pokemon Storage Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Example of reading Pokemon storage and counting Pokemon in the first box. Requires a PyGBA instance. ```python storage = read_pokemon_storage(gba) if storage: box_0 = storage["boxes"][0] caught_in_box_0 = sum(1 for mon in box_0 if mon is not None) print(f"Pokemon in box 0: {caught_in_box_0}") ``` -------------------------------- ### Install mGBA with Pre-built Wheels Source: https://github.com/dvruette/pygba/blob/main/README.md For Python 3.10+ on Linux and macOS, install mGBA using pre-built wheels if available. ```bash pip install mgba ``` -------------------------------- ### Example: Handling Game Over Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Illustrates how to check for a game over state and reset the environment if it occurs. ```python if env.check_if_done(): print("Game over!") obs, info = env.reset() ``` -------------------------------- ### Install PyGBA Source: https://github.com/dvruette/pygba/blob/main/README.md Install the PyGBA library using pip. Ensure mGBA with Python bindings is also installed. ```bash pip install pygba ``` -------------------------------- ### Full Example: Custom Game Wrapper Implementation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md A comprehensive example of a CustomGameWrapper demonstrating detailed reward calculation based on score, level, and HP changes, along with game-over detection and info reporting. ```python from pygba import GameWrapper, PyGBA import numpy as np from typing import Any class CustomGameWrapper(GameWrapper): """Wrapper for a custom GBA game.""" def __init__(self, score_reward: float = 0.01, level_reward: float = 1.0, hp_penalty: float = -0.1): self.score_reward = score_reward self.level_reward = level_reward self.hp_penalty = hp_penalty self.prev_score = 0 self.prev_level = 1 self.prev_hp = 100 def reward(self, gba: PyGBA, observation: np.ndarray) -> float: if observation is None or observation.sum() < 1: return 0.0 # Read game state score = gba.read_u32(0x03005d00) level = gba.read_u8(0x02024f08) hp = gba.read_u8(0x02024f10) # Calculate reward components score_delta = (score - self.prev_score) * self.score_reward level_delta = (level - self.prev_level) * self.level_reward hp_delta = (hp - self.prev_hp) * self.hp_penalty if hp < self.prev_hp else 0 # Update tracking self.prev_score = score self.prev_level = level self.prev_hp = hp return score_delta + level_delta + hp_delta def game_over(self, gba: PyGBA, observation: np.ndarray) -> bool: hp = gba.read_u8(0x02024f10) return hp == 0 def reset(self, gba: PyGBA) -> None: self.prev_score = 0 self.prev_level = 1 self.prev_hp = 100 def info(self, gba: PyGBA, observation: np.ndarray) -> dict[str, Any]: return { "score": gba.read_u32(0x03005d00), "level": gba.read_u8(0x02024f08), "hp": gba.read_u8(0x02024f10), } ``` -------------------------------- ### Install PyGBA Source: https://github.com/dvruette/pygba/blob/main/_autodocs/README.md Install the PyGBA library using pip. Ensure mGBA with Python bindings is also installed separately. ```bash pip install pygba # Also requires mGBA with Python bindings # See README.md in project root for build instructions ``` -------------------------------- ### Standard PyGBA Environment Usage Pattern Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Demonstrates a typical workflow for using the PyGBA environment, including initialization, resetting, stepping, rendering, and closing. This example uses random actions for demonstration. ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald gba = PyGBA.load("pokemon_emerald.gba", autoload_save=True) env = PyGBAEnv(gba, game_wrapper=PokemonEmerald(), render_mode="human") obs, info = env.reset() for episode in range(5): obs, info = env.reset() done = False truncated = False total_reward = 0 while not done and not truncated: action = env.action_space.sample() # Random action obs, reward, done, truncated, info = env.step(action) total_reward += reward env.render() print(f"Episode reward: {total_reward}") env.close() ``` -------------------------------- ### Example Reset Implementation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md An example implementation of the reset method. This initializes internal state variables like previous level, money, enemies defeated count, and a set for visited locations. ```python def reset(self, gba: PyGBA) -> None: self.prev_level = 1 self.prev_money = 0 self.enemies_defeated = 0 self.visited_locations = set() ``` -------------------------------- ### AsciiCharmap Decode Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Shows how to instantiate and use AsciiCharmap to decode strings from game memory, including examples with player names and text containing special characters. ```python from pygba.utils import AsciiCharmap charmap = AsciiCharmap() # Decode player name name = charmap.decode(b'TRAINER\x00') # "TRAINER" # Decode text with special characters text = charmap.decode(b'Hello!\x00') # "Hello!" ``` -------------------------------- ### Read Save Block 2 Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Example of reading Save Block 2 and accessing player name and playtime. Requires a PyGBA instance. ```python save_block_2 = read_save_block_2(gba) if save_block_2: print(f"Player: {save_block_2['playerName']}") print(f"Play time: {save_block_2['playTimeHours']}h") ``` -------------------------------- ### Pokemon Emerald Environment Setup and Training Loop Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Sets up the Pokemon Emerald environment using PyGBA and runs a basic training loop. This snippet demonstrates how to initialize the environment, sample actions, and track rewards and game state. ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald import numpy as np # Create environment gba = PyGBA.load("pokemon_emerald.gba", autoload_save=True) wrapper = PokemonEmerald( badge_reward=20.0, champion_reward=200.0, caught_pokemon_reward=2.0, ) env = PyGBAEnv(gba, game_wrapper=wrapper, frameskip=4, max_episode_steps=50000) # Run training loop obs, info = env.reset() total_reward = 0 for step in range(1000): action = env.action_space.sample() obs, reward, done, truncated, info = env.step(action) total_reward += reward if step % 100 == 0: state = info["game_state"] print(f"Step {step}:") print(f" Badges: {state['num_badges']}") print(f" Pokemon caught: {state['num_caught_pokemon']}") print(f" Cumulative reward: {total_reward}") if done or truncated: print(f"Episode ended. Total reward: {total_reward}") obs, info = env.reset() total_reward = 0 env.close() ``` -------------------------------- ### PyGBA Key Press Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use the KEY_MAP to press a key on a loaded GBA instance. It includes a check for key validity. ```python from pygba import PyGBA from pygba.utils import KEY_MAP gba = PyGBA.load("game.gba") # Check if a key is valid key_name = "A" if key_name in KEY_MAP: gba.press_key(key_name) # Iterate all available keys for key_name, key_constant in KEY_MAP.items(): print(f"{key_name}: {key_constant}") ``` -------------------------------- ### Example Game Over Implementation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md An example implementation of the game_over method. This logic checks if the player's HP, read from memory, has reached 0. ```python def game_over(self, gba: PyGBA, observation: np.ndarray) -> bool: # Read HP from memory hp = gba.read_u8(0x02024f10) return hp == 0 # Game over when HP reaches 0 ``` -------------------------------- ### Read Save Block 1 Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Example of reading Save Block 1 and accessing player location, party size, and money. Requires PyGBA instance and the read_save_block_1 function. ```python from pygba import PyGBA from pygba.game_wrappers.utils.emerald_utils import read_save_block_1 gba = PyGBA.load("pokemon_emerald.gba") save_block_1 = read_save_block_1(gba) if save_block_1: print(f"Player location: {save_block_1['location']}") print(f"Party size: {save_block_1['playerPartyCount']}") print(f"Money: {save_block_1['money']}") ``` -------------------------------- ### Configure and Build mGBA on Unix Source: https://github.com/dvruette/pygba/blob/main/README.md Configure mGBA with Python bindings enabled using CMake, then build and install it on Unix-based systems. ```bash mkdir build cd build cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr -DBUILD_PYTHON=ON .. make sudo make install ``` -------------------------------- ### Read Species Names Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Example of reading Pokemon species names and accessing the name for species ID 1 (Bulbasaur). Requires a PyGBA instance. ```python species_names = read_species_names(gba) if species_names: print(f"Species 1: {species_names[1]}") # "Bulbasaur" ``` -------------------------------- ### PyGBAEnv Frameskip Examples Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Illustrates different configurations for the frameskip parameter in PyGBAEnv. Frameskip controls how many frames are advanced per action, with options for fixed, random, or distribution-based skipping. ```python frameskip=0 ``` ```python frameskip=4 ``` ```python frameskip=(2, 4) ``` ```python frameskip=(0, 1, 2) ``` -------------------------------- ### Configure PyGBAEnv for Debug Mode Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Instantiate the PyGBAEnv with specific parameters for debugging. This setup enables human rendering and resets the environment to its initial state after each episode. ```python env = PyGBAEnv( gba, frameskip=0, render_mode="human", reset_to_initial_state=True, ) ``` -------------------------------- ### PyGBA Character Decoding Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Illustrates decoding game text using AsciiCharmap, showing how to handle raw byte strings and correctly interpret text that may contain null terminators. ```python from pygba.utils import AsciiCharmap charmap = AsciiCharmap() # Decode game text from memory raw_text = b'Item Name\x00' decoded = charmap.decode(raw_text) print(decoded) # "Item Name" # Handle text with terminator in middle text_with_null = b'Text\x00ExtraData' decoded = charmap.decode(text_with_null) print(decoded) # "Text" (stops at first null) ``` -------------------------------- ### Example of BaseCharmap Decode Usage Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Illustrates how to use the decode method of a BaseCharmap subclass to convert game bytes into a readable string, stopping at the terminator. ```python charmap = AsciiCharmap() name_bytes = b'PLAYER\x00' name = charmap.decode(name_bytes) # "PLAYER" ``` -------------------------------- ### Configure and Build mGBA on macOS Source: https://github.com/dvruette/pygba/blob/main/README.md Configure mGBA with Python bindings enabled using CMake, installing necessary dependencies via Homebrew on macOS. ```bash brew install cmake ffmpeg libzip qt5 sdl2 libedit lua pkg-config mkdir build cd build cmake -DCMAKE_PREFIX_PATH=`brew --prefix qt5` -DBUILD_PYTHON=ON .. make sudo make install ``` -------------------------------- ### Verify mGBA Python Bindings Source: https://github.com/dvruette/pygba/blob/main/README.md Check if the mGBA Python bindings were built and installed correctly by attempting to import the 'mgba' module. ```python import mgba ``` -------------------------------- ### Extending Charmap Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Example of how to extend the BaseCharmap to support a different game's character encoding by defining a custom charmap and terminator. ```APIDOC ## Extending Charmap To support a different game's character encoding: ```python from pygba.utils import BaseCharmap class MyGameCharmap(BaseCharmap): charmap = [ # 256 character strings "", "", "", "A", "B", "C", ... # Your game's encoding ] terminator = 0xFF # Your game's string terminator # Usage charmap = MyGameCharmap() decoded = charmap.decode(game_text_bytes) ``` ``` -------------------------------- ### PyGBA Emerald Game State Usage Example Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Demonstrates how to load a Pokemon Emerald ROM, read various game state data including player status, party, and gym progress, and display this information. It utilizes functions like get_game_state, read_species_names, and read_species_info. ```python from pygba import PyGBA from pygba.game_wrappers.utils.emerald_utils import ( get_game_state, read_species_names, read_species_info, ) gba = PyGBA.load("pokemon_emerald.gba") # Read all game state data state = get_game_state(gba) species_names = read_species_names(gba) species_info = read_species_info(gba) # Display player status print(f"Badges: {state['num_badges']}/8") print(f"Pokemon caught: {state['num_caught_pokemon']}") print(f"Money: {state['money']}") # Show party print("\nParty:") for i, mon in enumerate(state['party']): if mon: species_id = mon['substructs'][0]['species'] species_name = species_names[species_id] level = mon['level'] print(f" {i+1}. {species_name} (Level {level})") # Check specific badges print("\nGym Progress:") for gym_name, defeated in state['defeated_gyms'].items(): status = "✓" if defeated else "✗" print(f" {status} {gym_name}") ``` -------------------------------- ### Get Game State Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Reads and parses high-level game state for the current step. Returns a dictionary containing various game information. ```python def get_game_state(gba): # ... implementation details ... pass ``` ```python state = get_game_state(gba) print(f"Badges: {state['num_badges']}/8") print(f"Money: {state['money']}") print(f"Caught: {state['num_caught_pokemon']}") print(f"Is Champion: {state['is_champion']}") for city, visited in state['visited_cities'].items(): if visited: print(f" - Visited {city}") ``` -------------------------------- ### Get Flag from Byte Array Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Reads a single flag from a byte array. Useful for checking specific game flags like badges. ```python def get_flag(flags, flag_id): # ... implementation details ... pass ``` ```python from pygba.game_wrappers.utils.emerald_utils import get_flag, FLAG_BADGE01_GET save_block_1 = read_save_block_1(gba) has_badge_1 = get_flag(save_block_1['flags'], FLAG_BADGE01_GET) print(f"Has Rustboro Badge: {has_badge_1}") ``` -------------------------------- ### Configure Training for Quick Testing Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Sets up the environment for quick testing with limited episode steps and reset to initial state. ```python # Quick testing env = PyGBAEnv( gba, frameskip=4, max_episode_steps=1000, reset_to_initial_state=True, ) ``` -------------------------------- ### Configure Action Space for Testing Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Sets up the environment for rapid testing with frame-perfect actions and no action repetition. ```python # For rapid testing / frame-perfect actions env = PyGBAEnv(gba, frameskip=0, repeat_action_probability=0.0) ``` -------------------------------- ### Render and Debug PyGBA Environment Source: https://github.com/dvruette/pygba/blob/main/_autodocs/README.md Demonstrates how to initialize a PyGBA environment in human-readable render mode, sample actions, step through the environment, and render frames. Useful for debugging and visualizing game states. ```python env = PyGBAEnv(gba, game_wrapper=wrapper, render_mode="human", frameskip=0) obs, info = env.reset() for step in range(100): action = env.action_space.sample() obs, reward, done, truncated, info = env.step(action) state = info["game_state"] print(f"Step {step}: Reward={reward}, Badges={state['num_badges']}") env.render() # Display frame if done or truncated: break ``` -------------------------------- ### Basic PyGBA Environment Usage Source: https://github.com/dvruette/pygba/blob/main/_autodocs/README.md Demonstrates loading the emulator, creating a Pokemon Emerald environment with a specific game wrapper, and running a basic episode loop. ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald # Load emulator gba = PyGBA.load("pokemon_emerald.gba", autoload_save=True) # Create environment wrapper = PokemonEmerald() env = PyGBAEnv(gba, game_wrapper=wrapper, frameskip=4) # Run episode obs, info = env.reset() for _ in range(1000): action = env.action_space.sample() obs, reward, done, truncated, info = env.step(action) if done or truncated: break env.close() ``` -------------------------------- ### PyGBA Basic Usage Pattern Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba.md Demonstrates the fundamental workflow for loading a ROM, interacting with the emulator (button presses, waiting), and reading memory values. ```python from pygba import PyGBA # Load ROM gba = PyGBA.load("pokemon_emerald.gba") # Interact with emulator gba.press_a() # Press A button gba.wait(30) # Wait 30 frames gba.press_start() # Open menu # Read memory player_x = gba.read_u16(0x02024f00) player_y = gba.read_u16(0x02024f02) # Advance emulation gba.wait(60) # 1 second of game time ``` -------------------------------- ### Usage of Custom Game Wrapper with PyGBAEnv Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md Demonstrates how to instantiate PyGBAEnv with a custom game wrapper, highlighting the internal calls made to the wrapper's methods during environment reset and step operations. ```python from pygba import PyGBA, PyGBAEnv gba = PyGBA.load("game.gba") wrapper = CustomGameWrapper() env = PyGBAEnv(gba, game_wrapper=wrapper) # PyGBAEnv calls: # - wrapper.reset(gba) on env.reset() # - wrapper.reward(gba, obs) on env.step() # - wrapper.game_over(gba, obs) on env.step() # - wrapper.info(gba, obs) on env.step() ``` -------------------------------- ### Load GBA ROM and Create Gymnasium Environment Source: https://github.com/dvruette/pygba/blob/main/README.md Load a GBA ROM using PyGBA and optionally enable automatic save file loading. Then, create a Gymnasium environment using a game-specific wrapper for reinforcement learning. ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald rom_path = "path/to/pokemon_emerald.gba" gba = PyGBA.load(rom_path, autoload_save=True) # if autoload_save is True, a save file will be loaded if one exists next to the ROM game_wrapper = PokemonEmerald() # optionally customize the reward function by passing additional arguments env = PyGBAEnv(gba, game_wrapper) ``` -------------------------------- ### step Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Executes one step of the environment by taking an action, advancing the emulation, and returning the new state, reward, and termination status. ```APIDOC ## step ### Description Executes one step of the environment by taking an action, advancing the emulation, and returning the new state, reward, and termination status. ### Method `step(action_id: int)` ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Action ID - **action_id** (`int`) - Required - Action index (0 to num_actions-1) ### Returns Tuple of `(observation, reward, done, truncated, info)` #### Observation - `np.ndarray` - Screen observation with shape (240, 160, 3) or (240, 160) for grayscale #### Reward - `float` - Reward from game wrapper (0.0 if no wrapper) #### Done - `bool` - Episode terminated (from game wrapper) #### Truncated - `bool` - Episode truncated (max_episode_steps reached) #### Info - `dict` - Additional info dict from game wrapper ### Behavior 1. Sets the desired key inputs for the action 2. Applies repeat_action_probability to randomly repeat previous action 3. Advances emulation by frameskip+1 frames 4. Generates observation from video buffer 5. Queries game_wrapper for reward and done status 6. Updates step counter and checks truncation ### Example ```python obs, reward, done, truncated, info = env.step(5) if done or truncated: obs, info = env.reset() ``` ``` -------------------------------- ### Configure Action Space for Realistic Gameplay Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Sets up the environment for more realistic gameplay with moderate frameskip and action repetition. ```python # For realistic gameplay with some variation env = PyGBAEnv(gba, frameskip=4, repeat_action_probability=0.1) ``` -------------------------------- ### Flag Ranges Constants Source: https://github.com/dvruette/pygba/blob/main/_autodocs/types.md Defines the starting offsets for different types of flags used in save data, including script, trainer, system, and daily flags. ```python SCRIPT_FLAGS_START = 0x50 # Bit 80-2559 TRAINER_FLAGS_START = 0x500 # Bit 1280-2175 SYSTEM_FLAGS_START = 0x860 # Bit 2176-2335 DAILY_FLAGS_START = 0x920 # Bit 2336+ ``` -------------------------------- ### Render Current Frame Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Renders the current frame of the environment. Use 'human' mode for display or 'rgb_array' to get a numpy array. Initializes pygame in 'human' mode on the first call. ```python def render(self) -> np.ndarray | None: # ... (implementation details omitted for brevity) ``` -------------------------------- ### Configure Training for Long Runs Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Sets up the environment for long training runs with a high step limit and stochastic frame skipping. ```python # Long training runs env = PyGBAEnv( gba, frameskip=(2, 4), max_episode_steps=100000, repeat_action_probability=0.05, ) ``` -------------------------------- ### PyGBAEnv Step Method Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Executes a single step in the environment. Use this to send actions and receive observations, rewards, and termination signals. ```python def step(self, action_id) -> tuple: ``` ```python obs, reward, done, truncated, info = env.step(5) if done or truncated: obs, info = env.reset() ``` -------------------------------- ### Get Game State Information Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Retrieves detailed game state including the full game state dictionary and the previous reward. Use this to access specific game details like badges or party members. ```python def info(self, gba: PyGBA, observation: np.ndarray) -> dict[str, Any]: # ... implementation details ... ``` ```python obs, reward, done, truncated, info = env.step(action) print(info["game_state"]["num_badges"]) print(info["game_state"]["party"]) ``` -------------------------------- ### Configure Reward for Reaching Champion Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Sets up rewards to prioritize reaching the Champion, with higher badge and champion rewards. ```python # Goal: Reach the Champion wrapper = PokemonEmerald(badge_reward=20.0, champion_reward=200.0) env = PyGBAEnv(gba, game_wrapper=wrapper) ``` -------------------------------- ### info Method Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md Returns auxiliary information about the current game state. Subclasses can override this to provide game-specific metrics. The default implementation returns an empty dictionary. ```APIDOC ## info(gba: PyGBA, observation: np.ndarray) -> dict[str, Any] ### Description Returns auxiliary information about the current game state. Default implementation returns empty dict. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Returns `dict[str, Any]` — Dictionary of auxiliary information ### Default Behavior Returns {} (empty dict) ### Override to: Return game state details useful for logging/debugging ### Keys typically include: - `game_state` — Current game state snapshot (dict) - `inventory` — Current inventory items - `location` — Current player location - Any other game-specific metrics ### Example: ```python def info(self, gba: PyGBA, observation: np.ndarray) -> dict[str, Any]: return { "level": gba.read_u8(0x02024f00), "hp": gba.read_u16(0x02024f10), "location": gba.read_u16(0x02024f20), } ``` ``` -------------------------------- ### PyGBAEnv Constructor Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Initializes the PyGBAEnv with a PyGBA instance and optional game wrapper. Configure observation type, frameskip, rendering, and episode limits. ```python def __init__( self, gba: PyGBA, game_wrapper: GameWrapper | None = None, obs_type: Literal["rgb", "grayscale"] = "rgb", frameskip: int | tuple[int, int] | tuple[int, int, int] = 0, repeat_action_probability: float = 0.0, render_mode: Literal["human", "rgb_array"] | None = None, reset_to_initial_state: bool = True, max_episode_steps: int | None = None, **kwargs, ): # Implementation details omitted for brevity ``` ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald gba = PyGBA.load("pokemon_emerald.gba") wrapper = PokemonEmerald() env = PyGBAEnv( gba, game_wrapper=wrapper, obs_type="rgb", frameskip=4, render_mode="human", max_episode_steps=10000, ) ``` -------------------------------- ### Press Action Buttons Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba.md Convenience methods like `press_a`, `press_b`, `press_l`, `press_r`, `press_start`, and `press_select` simulate action button presses. An optional `frames` parameter can specify the duration. ```python gba.press_a() # Press A for 2 frames gba.press_start(4) # Press Start for 4 frames gba.press_b() gba.press_select(10) ``` -------------------------------- ### PyGBAEnv Constructor Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Initializes a gymnasium environment for GBA emulation. It wraps a PyGBA instance and configures observation type, frame skipping, action repetition, rendering, and episode step limits. ```APIDOC ## PyGBAEnv Constructor ### Description Initializes a gymnasium environment for GBA emulation. It wraps a PyGBA instance and configures observation type, frame skipping, action repetition, rendering, and episode step limits. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `__init__(self, gba: PyGBA, game_wrapper: GameWrapper | None = None, obs_type: Literal["rgb", "grayscale"] = "rgb", frameskip: int | tuple[int, int] | tuple[int, int, int] = 0, repeat_action_probability: float = 0.0, render_mode: Literal["human", "rgb_array"] | None = None, reset_to_initial_state: bool = True, max_episode_steps: int | None = None, **kwargs)` #### Parameters - **gba** (`PyGBA`) - Required - A PyGBA instance to wrap - **game_wrapper** (`GameWrapper | None`) - Optional - Optional game-specific wrapper for reward/game-over logic - **obs_type** (`Literal["rgb", "grayscale"]`) - Optional - Default: "rgb" - Observation color format - **frameskip** (`int | tuple[int, int] | tuple[int, int, int]`) - Optional - Default: 0 - Frames to skip per action (can be random range) - **repeat_action_probability** (`float`) - Optional - Default: 0.0 - Probability [0.0-1.0] to repeat previous action - **render_mode** (`Literal["human", "rgb_array"] | None`) - Optional - Default: None - Rendering mode: "human" for pygame display, "rgb_array" for raw numpy - **reset_to_initial_state** (`bool`) - Optional - Default: True - Whether to save/restore initial state on reset - **max_episode_steps** (`int | None`) - Optional - Default: None - Maximum steps per episode before truncation - **kwargs** - Optional - Extra keyword arguments (stored internally) ### Raises - `TypeError` — If gba is not a PyGBA instance - `TypeError` — If game_wrapper is not a GameWrapper instance (when provided) ### Note If no game_wrapper is provided, reward is always 0.0 and done is never True (no game-over detection). ### Example ```python from pygba import PyGBA, PyGBAEnv, PokemonEmerald gba = PyGBA.load("pokemon_emerald.gba") wrapper = PokemonEmerald() env = PyGBAEnv( gba, game_wrapper=wrapper, obs_type="rgb", frameskip=4, render_mode="human", max_episode_steps=10000, ) ``` ``` -------------------------------- ### Load GBA ROM with PyGBA Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba.md Use the static `load` method to initialize PyGBA with a GBA ROM file. Optionally, provide a save file to load. ```python from pygba import PyGBA # Load a ROM gba = PyGBA.load("path/to/pokemon_emerald.gba") # Load a ROM with an existing save file gba = PyGBA.load("path/to/pokemon_emerald.gba", save_file="path/to/pokemon_emerald.sav") ``` -------------------------------- ### info Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Returns detailed game state information, including the full game state and the previous step's cumulative reward. ```APIDOC ## info(gba: PyGBA, observation: np.ndarray) -> dict[str, Any] ### Description Returns detailed game state information. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (This is a Python method call) ### Endpoint None (This is a Python method call) ### Request Example ```python obs, reward, done, truncated, info = env.step(action) print(info["game_state"]["num_badges"]) print(info["game_state"]["party"]) ``` ### Response #### Success Response - **game_state** (dict) - Full game state (see game_state() method) - **prev_reward** (float) - Previous step's cumulative reward #### Response Example ```json { "game_state": { ... }, "prev_reward": 0.5 } ``` ``` -------------------------------- ### Import Core PyGBA Components Source: https://github.com/dvruette/pygba/blob/main/_autodocs/README.md Imports essential classes from the PyGBA library, including the core emulator wrapper, Gymnasium environment, and game wrapper abstractions. Used for setting up emulation and game-specific logic. ```python from pygba import ( PyGBA, # Core emulator wrapper PyGBAEnv, # Gymnasium environment GameWrapper, # Abstract game wrapper PokemonEmerald, # Pokemon Emerald implementation ) ``` -------------------------------- ### PokemonEmerald Constructor Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Initializes a Pokemon Emerald game wrapper with customizable reward weights for various in-game progression metrics. ```APIDOC ## PokemonEmerald Constructor ### Description Initializes a Pokemon Emerald game wrapper with customizable reward weights. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **badge_reward** (`float`) - Optional - Reward per gym badge collected. Default: 10.0 - **champion_reward** (`float`) - Optional - Reward for defeating the Champion. Default: 100.0 - **visit_city_reward** (`float`) - Optional - Reward per unique city visited. Default: 5.0 - **money_reward** (`float`) - Optional - Reward scale per currency unit. Default: 0.0 - **seen_pokemon_reward** (`float`) - Optional - Reward per unique Pokemon seen. Default: 0.2 - **caught_pokemon_reward** (`float`) - Optional - Reward per unique Pokemon caught. Default: 1.0 - **trainer_beat_reward** (`float`) - Optional - Reward per trainer battle won. Default: 1.0 - **event_reward** (`float`) - Optional - Reward per game script event triggered. Default: 1.0 - **exp_reward_scale** (`float`) - Optional - Scale factor for total experience points. Default: 0.1 ### Request Example ```python from pygba import PokemonEmerald # Default rewards wrapper = PokemonEmerald() # Custom rewards emphasizing Pokemon capture wrapper = PokemonEmerald( badge_reward=5.0, caught_pokemon_reward=5.0, trainer_beat_reward=0.5, ) # Rewards only for major milestones wrapper = PokemonEmerald( badge_reward=20.0, champion_reward=500.0, caught_pokemon_reward=2.0, visit_city_reward=0.0, ) ``` ### Response None ``` -------------------------------- ### PokemonEmerald Constructor with Default Rewards Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Initializes a PokemonEmerald game wrapper using default reward values for various progression metrics. ```python def __init__( self, badge_reward: float = 10.0, champion_reward: float = 100.0, visit_city_reward: float = 5.0, money_reward: float = 0.0, seen_pokemon_reward: float = 0.2, caught_pokemon_reward: float = 1.0, trainer_beat_reward: float = 1.0, event_reward: float = 1.0, exp_reward_scale: float = 0.1, ): ``` -------------------------------- ### Info Method Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md This method returns auxiliary information about the current game state. The default implementation returns an empty dictionary. Override this method to provide game-specific metrics for logging or debugging. ```python def info(self, gba: PyGBA, observation: np.ndarray) -> dict[str, Any]: ``` -------------------------------- ### PokemonEmerald Constructor with Custom Rewards Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Initializes a PokemonEmerald game wrapper with custom reward weights, allowing for tailored reward schemes. ```python from pygba import PokemonEmerald # Default rewards wrapper = PokemonEmerald() # Custom rewards emphasizing Pokemon capture wrapper = PokemonEmerald( badge_reward=5.0, caught_pokemon_reward=5.0, trainer_beat_reward=0.5, ) # Rewards only for major milestones wrapper = PokemonEmerald( badge_reward=20.0, champion_reward=500.0, caught_pokemon_reward=2.0, visit_city_reward=0.0, ) ``` -------------------------------- ### reset Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Resets the environment to its initial state, preparing it for a new episode. This includes resetting the emulation core and optionally restoring the initial savestate. ```APIDOC ## reset ### Description Resets the environment to its initial state, preparing it for a new episode. This includes resetting the emulation core and optionally restoring the initial savestate. ### Method `reset(seed: int | None = None) -> tuple[ndarray, dict]` ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Seed - **seed** (`int | None`) - Optional - Default: None - Random seed (for gymnasium compatibility) ### Returns Tuple of `(observation, info)` #### Observation - `np.ndarray` - Initial screen observation #### Info - `dict` - Info dict (from game_wrapper if provided) ### Behavior 1. Resets step counter and total reward 2. Resets emulation core 3. Restores initial savestate if `reset_to_initial_state=True` 4. Generates observation 5. Calls game_wrapper.reset() if provided ### Example ```python obs, info = env.reset() ``` ``` -------------------------------- ### Balanced Reward Configuration (Default) Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Uses default reward weights for a balanced gameplay experience. Suitable for general objectives. ```python wrapper = PokemonEmerald() # Rewards: badges=10, champion=100, cities=5, pokemon_caught=1, trainers=1 ``` -------------------------------- ### PyGBA.load Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba.md Loads a GBA ROM file and returns a PyGBA instance. It handles the creation of a temporary directory for save files and resets the core state. ```APIDOC ## PyGBA.load ### Description Loads a GBA ROM file and returns a PyGBA instance. Automatically handles creating a temporary directory to prevent mGBA from overwriting save files. ### Method `@staticmethod load(gba_file: str, save_file: str | None = None) -> "PyGBA"` ### Parameters #### Path Parameters - **gba_file** (str) - Required - Path to the GBA ROM file - **save_file** (str | None) - Optional - Path to a save file to load alongside the ROM ### Returns `PyGBA` - A loaded and initialized PyGBA instance with core state reset. ### Raises - `ValueError` - If the GBA file cannot be loaded ### Example ```python from pygba import PyGBA # Load a ROM gba = PyGBA.load("path/to/pokemon_emerald.gba") # Load a ROM with an existing save file gba = PyGBA.load("path/to/pokemon_emerald.gba", save_file="path/to/pokemon_emerald.sav") ``` ``` -------------------------------- ### Integrate Custom Wrapper with PyGBAEnv Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/game_wrapper.md Instantiate PyGBAEnv with your custom game wrapper to enable custom reward and game-over logic during environment interaction. ```python from pygba import PyGBA, PyGBAEnv gba = PyGBA.load("game.gba") wrapper = MyGameWrapper(reward_scale=2.0) env = PyGBAEnv(gba, game_wrapper=wrapper) obs, info = env.reset() for _ in range(100): obs, reward, done, truncated, info = env.step(env.action_space.sample()) print(f"Reward: {reward}, Info: {info}") if done or truncated: break ``` -------------------------------- ### Speed Run Reward Configuration Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Prioritizes gym badge and champion rewards for speed-running objectives. Sets other rewards to zero. ```python wrapper = PokemonEmerald( badge_reward=50.0, champion_reward=500.0, visit_city_reward=0.0, caught_pokemon_reward=0.0, ) ``` -------------------------------- ### PyGBAEnv Reset Method Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba_env.md Resets the environment to its initial state. Call this when an episode terminates or truncates. ```python def reset(self, seed=None) -> tuple: ``` ```python obs, info = env.reset() ``` -------------------------------- ### PokemonEmerald Reward Method Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pokemon_emerald.md Calculates the reward delta for the current step based on game progression metrics. Reads game state and compares it to the previous state to determine changes. ```python def reward(self, gba: PyGBA, observation: np.ndarray) -> float: ``` ```python env = PyGBAEnv(gba, game_wrapper=PokemonEmerald()) obs, info = env.reset() obs, reward, done, truncated, info = env.step(action) print(f"Step reward: {reward}") # Reward delta for this step print(f"Total reward: {sum(rewards)}") # Cumulative ``` -------------------------------- ### Extending BaseCharmap for Custom Games Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Provides a template for creating a custom character map by subclassing BaseCharmap. Users need to define their game's specific charmap and terminator. ```python from pygba.utils import BaseCharmap class MyGameCharmap(BaseCharmap): charmap = [ # 256 character strings "", "", "", "A", "B", "C", ... # Your game's encoding ] terminator = 0xFF # Your game's string terminator # Usage charmap = MyGameCharmap() decoded = charmap.decode(game_text_bytes) ``` -------------------------------- ### PyGBAEnv Constructor Parameters Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Defines the parameters accepted by the PyGBAEnv constructor, including game instance, observation type, frame skipping, action repetition probability, render mode, and state management options. ```python PyGBAEnv( gba: PyGBA, game_wrapper: GameWrapper | None = None, obs_type: Literal["rgb", "grayscale"] = "rgb", frameskip: int | tuple[int, int] | tuple[int, int, int] = 0, repeat_action_probability: float = 0.0, render_mode: Literal["human", "rgb_array"] | None = None, reset_to_initial_state: bool = True, max_episode_steps: int | None = None, **kwargs, ) ``` -------------------------------- ### Read Experience Tables Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/emerald_utils.md Reads and caches experience requirements for all Pokemon growth rates. Returns a list of experience tables or None if the address is invalid. ```python import functools @functools.lru_cache(maxsize=1) def read_experience_tables(gba): # ... implementation details ... pass ``` ```python exp_tables = read_experience_tables(gba) if exp_tables: slow_growth = exp_tables[0] print(f"Level 50 (slow): {slow_growth[50]} EXP") print(f"Level 100 (slow): {slow_growth[100]} EXP") ``` -------------------------------- ### Usage of KEY_MAP for Key Validation Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/utils.md Demonstrates how to check if a given key name exists in the KEY_MAP before attempting to use it, preventing potential errors. ```python from pygba.utils import KEY_MAP # Check valid keys if key_name in KEY_MAP: key_constant = KEY_MAP[key_name] ``` -------------------------------- ### Configure Action Space for Stochastic Frame Skipping Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Enables stochastic frame skipping, varying the skip count between episodes for added randomness. ```python # For stochastic frame skipping (varies between episodes) env = PyGBAEnv(gba, frameskip=(2, 6)) ``` -------------------------------- ### PyGBA Button Methods Source: https://github.com/dvruette/pygba/blob/main/_autodocs/api-reference/pygba.md Convenience methods for pressing action buttons. All accept an optional `frames` parameter. ```APIDOC ## PyGBA Button Methods ### Description Convenience methods for pressing action buttons. All accept optional `frames` parameter (default 2). ### Methods - `press_a(frames: int = 2) -> None` - `press_b(frames: int = 2) -> None` - `press_l(frames: int = 2) -> None` - `press_r(frames: int = 2) -> None` - `press_start(frames: int = 2) -> None` - `press_select(frames: int = 2) -> None` ### Example ```python gba.press_a() # Press A for 2 frames gba.press_start(4) # Press Start for 4 frames gba.press_b() gba.press_select(10) ``` ``` -------------------------------- ### Exploration Focused Reward Configuration Source: https://github.com/dvruette/pygba/blob/main/_autodocs/configuration.md Rewards visiting cities and seeing Pokemon, with moderate rewards for badges and champion. ```python wrapper = PokemonEmerald( badge_reward=5.0, champion_reward=100.0, visit_city_reward=20.0, seen_pokemon_reward=1.0, caught_pokemon_reward=1.0, ) ```