> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pret/pokeemerald/llms.txt
> Use this file to discover all available pages before exploring further.

# Battle System

> Overview of the turn-based battle engine.

The battle engine is the largest subsystem in pokeemerald. It is turn-based, event-driven, and built around a central callback loop in `src/battle_main.c`. Each participant — player, opponent, link partner, Safari Zone — is managed by a dedicated **battle controller**.

## Architecture

A battle proceeds through phases managed by function pointers in `gBattlerControllerFuncs`. The top-level callback `BattleMainCB2` in `src/battle_main.c` dispatches to `gBattleMainFunc` every frame.

The global `gBattleStruct` (type `struct BattleStruct *`) holds all per-battle transient state: turn trackers, switch targets, Safari counters, arena points, and more.

## Battle controllers

Each of the up to four battler positions is served by a controller that handles input, animations, and communication. Controllers are assigned at battle start based on `gBattleTypeFlags`.

| Source file                                 | Controller role                     |
| ------------------------------------------- | ----------------------------------- |
| `src/battle_controller_player.c`            | Local human player                  |
| `src/battle_controller_opponent.c`          | AI-driven opponent                  |
| `src/battle_controller_player_partner.c`    | Multi-battle human partner          |
| `src/battle_controller_link_partner.c`      | Remote link partner                 |
| `src/battle_controller_safari.c`            | Safari Zone (no move selection)     |
| `src/battle_controller_wally.c`             | Wally tutorial battle               |
| `src/battle_controller_recorded_player.c`   | Recorded battle playback (player)   |
| `src/battle_controller_recorded_opponent.c` | Recorded battle playback (opponent) |

The shared controller infrastructure lives in `src/battle_controllers.c`.

## Battle actions

Each battler selects one action per turn. The chosen action is stored in `gChosenActionByBattler[]`.

```c theme={null}
// include/battle.h

// Battle Actions — determine what each battler does in a turn
#define B_ACTION_USE_MOVE               0
#define B_ACTION_USE_ITEM               1
#define B_ACTION_SWITCH                 2
#define B_ACTION_RUN                    3
#define B_ACTION_SAFARI_WATCH_CAREFULLY 4
#define B_ACTION_SAFARI_BALL            5
#define B_ACTION_SAFARI_POKEBLOCK       6
#define B_ACTION_SAFARI_GO_NEAR         7
#define B_ACTION_SAFARI_RUN             8
#define B_ACTION_WALLY_THROW            9
#define B_ACTION_EXEC_SCRIPT            10
#define B_ACTION_TRY_FINISH             11
#define B_ACTION_FINISHED               12
#define B_ACTION_CANCEL_PARTNER         12  // when choosing an action
#define B_ACTION_NOTHING_FAINTED        13  // when choosing an action
#define B_ACTION_NONE                   0xFF
```

## Move targeting

The `MOVE_TARGET_*` constants define which battlers a move can hit.

```c theme={null}
// include/battle.h
#define MOVE_TARGET_SELECTED         0          // player picks the target
#define MOVE_TARGET_DEPENDS          (1 << 0)   // depends on battle type
#define MOVE_TARGET_USER_OR_SELECTED (1 << 1)   // self or selected foe
#define MOVE_TARGET_RANDOM           (1 << 2)   // random opposing battler
#define MOVE_TARGET_BOTH             (1 << 3)   // both opponents
#define MOVE_TARGET_USER             (1 << 4)   // user only
#define MOVE_TARGET_FOES_AND_ALLY    (1 << 5)   // all other battlers
#define MOVE_TARGET_OPPONENTS_FIELD  (1 << 6)   // entire opposing field
```

## Battle script engine

Battle scripts are sequences of bytecode commands that drive battle flow: dealing damage, printing messages, playing animations, checking conditions, and branching. The interpreter advances `gBattlescriptCurrInstr` each frame.

<Tabs>
  <Tab title="Script files">
    ```
    data/battle_scripts_1.s   # Core battle flow scripts
    data/battle_scripts_2.s   # Item use, ability triggers, and more
    ```

    Scripts are authored using macros from `asm/macros/battle_script.inc`.
  </Tab>

  <Tab title="Command handler">
    `src/battle_script_commands.c` implements every battle script command. Each command is a C function that advances `gBattlescriptCurrInstr` when complete.

    A call stack (`struct BattleScriptsStack`, max depth 8) allows scripts to call sub-scripts and return:

    ```c theme={null}
    // include/battle.h
    struct BattleScriptsStack {
        const u8 *ptr[8];
        u8 size;
    };
    ```
  </Tab>
</Tabs>

## Battle AI

The AI runs scripts from `data/battle_ai_scripts.s` and scores each move candidate.

| Source file                       | Role                                                                       |
| --------------------------------- | -------------------------------------------------------------------------- |
| `src/battle_ai_script_commands.c` | Implements AI script commands; populates `score[]` for each candidate move |
| `src/battle_ai_switch_items.c`    | Decides whether the AI should switch Pokémon or use an item on its turn    |

```c theme={null}
// include/battle.h
struct AI_ThinkingStruct {
    u8  aiState;
    u8  movesetIndex;
    u16 moveConsidered;
    s8  score[MAX_MON_MOVES];  // score for each of the 4 moves
    u32 funcResult;
    u32 aiFlags;
    u8  aiAction;
    u8  aiLogicId;
    u8  simulatedRNG[MAX_MON_MOVES];
};
```

`aiFlags` is loaded from trainer data and enables optional behaviors such as smart switching and item use prediction.

## Battle animations

Every visual effect during a move is handled by animation source files organized by elemental type. Animation scripts live in `data/battle_anim_scripts.s`; the coordinator is `src/battle_anim.c`.

<CardGroup cols={2}>
  <Card title="src/battle_anim_fire.c" icon="flame">
    Fire-type move visual effects.
  </Card>

  <Card title="src/battle_anim_water.c" icon="droplet">
    Water-type move visual effects.
  </Card>

  <Card title="src/battle_anim_electric.c" icon="zap">
    Electric-type move visual effects.
  </Card>

  <Card title="src/battle_anim_ice.c" icon="snowflake">
    Ice-type move visual effects.
  </Card>

  <Card title="src/battle_anim_psychic.c" icon="eye">
    Psychic-type move visual effects.
  </Card>

  <Card title="src/battle_anim_ghost.c" icon="ghost">
    Ghost-type move visual effects.
  </Card>

  <Card title="src/battle_anim_mon_movement.c" icon="move">
    Pokémon sprite movement during animations.
  </Card>

  <Card title="src/battle_anim_status_effects.c" icon="heart-pulse">
    Status condition visual effects.
  </Card>
</CardGroup>

Additional animation files: `battle_anim_dragon.c`, `battle_anim_bug.c`, `battle_anim_dark.c`, `battle_anim_fight.c`, `battle_anim_flying.c`, `battle_anim_ground.c`, `battle_anim_normal.c`, `battle_anim_poison.c`, `battle_anim_rock.c`, `battle_anim_throw.c`, `battle_anim_effects_1.c`, `battle_anim_effects_2.c`, `battle_anim_effects_3.c`.

## Battle Frontier

Each Battle Frontier facility has its own source file implementing facility-specific rules, party generation, and streak recording.

<CardGroup cols={2}>
  <Card title="Battle Arena" icon="shield">
    `src/battle_arena.c` — three-turn judge-scored battles; awards Mind and Skill points.
  </Card>

  <Card title="Battle Dome" icon="building">
    `src/battle_dome.c` — tournament bracket with scouting; uses `BATTLE_TYPE_DOME`.
  </Card>

  <Card title="Battle Factory" icon="industry">
    `src/battle_factory.c` — rental Pokémon battles with post-round swapping.
  </Card>

  <Card title="Battle Palace" icon="chess-rook">
    `src/battle_palace.c` — AI selects moves based on nature; player has no direct move control.
  </Card>

  <Card title="Battle Pike" icon="sword">
    `src/battle_pike.c` — series of rooms with randomized encounters, trainers, and healing.
  </Card>

  <Card title="Battle Pyramid" icon="triangle">
    `src/battle_pyramid.c` — ascending floors with restricted items and darkness.
  </Card>

  <Card title="Battle Tower" icon="tower-observation">
    `src/battle_tower.c` — streak-based single and multi battles with BP rewards.
  </Card>
</CardGroup>

<Note>
  The `BATTLE_TYPE_FRONTIER` composite flag ORs together all seven facility flags: `BATTLE_TYPE_BATTLE_TOWER`, `BATTLE_TYPE_DOME`, `BATTLE_TYPE_PALACE`, `BATTLE_TYPE_ARENA`, `BATTLE_TYPE_FACTORY`, `BATTLE_TYPE_PIKE`, and `BATTLE_TYPE_PYRAMID`.
</Note>
