Skip to content

Build your first environment ​

Build a small counter environment with a complete manifest and source file. Each action advances one simulation tick. You will save a snapshot, repeat a step, and verify that replay returns to the same state.

You need: Rust 1.91 or newer. These examples use Bevy 0.18.1 and the published experimental release 0.0.4.

Prefer to explore first?

Run the repository example without copying any code. To control a running game from another process, follow HTTP and the CLI.

1. Create a small Rust project ​

sh
cargo new my-agent-game
cd my-agent-game

Replace Cargo.toml with:

toml
[package]
name = "my-agent-game"
version = "0.1.0"
edition = "2024"
rust-version = "1.91"

[dependencies]
bevy = { version = "=0.18.1", default-features = false, features = ["std", "bevy_log", "bevy_state", "serialize"] }
bevy_agent_core = "=0.0.4"
bevy_agent_runner = "=0.0.4"
bevy_agent_snapshot = "=0.0.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"

There is no umbrella bevy_agent package. The runner composes core, snapshots, and replay; the other dependencies expose types you use directly. Keep companion crate versions pinned to the same exact release.

2. Add the complete environment ​

Replace src/main.rs with this example. It is the same source shipped with bevy_agent_runner, so the guide and runnable example stay together.

rs
use bevy::prelude::*;
use bevy_agent_core::{
    AgentAction, AgentActionKind, AgentControlAppExt, AgentReset, AgentResetSet, AgentSet,
    AgentTick, EnvironmentChecksum, Observation, ObservationMode, SimClock, StableHasher,
    default_checksum,
};
use bevy_agent_runner::{AgentApp, AgentControlPlugins, AgentEnvironment, ResetOptions};
use bevy_agent_snapshot::{SnapshotAppExt, SnapshotType};
use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Resource, Clone, Default, Serialize, Deserialize)]
struct Counter(u64);

impl SnapshotType for Counter {
    const TYPE_ID: &'static str = "counter.value";
    const SCHEMA_VERSION: u32 = 1;
}

fn build_app() -> App {
    let mut app = App::new();
    app.add_plugins(MinimalPlugins)
        .add_plugins(AgentControlPlugins::default())
        .init_resource::<Counter>()
        .set_snapshot_metadata("counter", env!("CARGO_PKG_VERSION"))
        .set_supported_actions([AgentActionKind::Noop])
        .set_supported_observation_modes([ObservationMode::Hybrid])
        .insert_observation_extractor(|world, _mode| Observation::Domain {
            tick: world.resource::<SimClock>().tick,
            value: json!({ "count": world.resource::<Counter>().0 }),
        })
        .insert_checksum_extractor(checksum)
        .add_systems(AgentReset, reset_counter.in_set(AgentResetSet::Game))
        .add_systems(AgentTick, increment_counter.in_set(AgentSet::Simulation));
    app.register_required_snapshot_resource::<Counter>()
        .expect("counter snapshot identity is valid");
    app.set_observation_schema(json!({
        "type": "object",
        "additionalProperties": false,
        "required": ["kind", "tick", "value"],
        "properties": {
            "kind": { "const": "Domain" },
            "tick": { "type": "integer", "minimum": 0 },
            "value": {
                "type": "object",
                "additionalProperties": false,
                "required": ["count"],
                "properties": { "count": { "type": "integer", "minimum": 0 } }
            }
        }
    }))
    .expect("counter observation schema is valid");
    app
}

fn reset_counter(mut counter: ResMut<Counter>) {
    counter.0 = 0;
}

fn increment_counter(mut counter: ResMut<Counter>) {
    counter.0 += 1;
}

fn checksum(world: &mut World) -> EnvironmentChecksum {
    let core = default_checksum(world);
    let mut hasher = StableHasher::new();
    hasher.write_json(&json!({
        "core": core.hash,
        "count": world.resource::<Counter>().0,
    }));
    EnvironmentChecksum {
        tick: core.tick,
        hash: hasher.finish_hash(),
    }
}

fn main() -> anyhow::Result<()> {
    let mut env = AgentApp::new(build_app)?;
    env.reset(ResetOptions::default())?;
    env.step(AgentAction::Noop)?;
    let snapshot = env.snapshot()?;
    let first = env.step(AgentAction::Noop)?;
    env.restore(snapshot.snapshot_id)?;
    let repeated = env.step(AgentAction::Noop)?;
    assert_eq!(first.checksum, repeated.checksum);
    assert_eq!(env.world().resource::<Counter>().0, 2);
    env.restore_tick(1)?;
    assert_eq!(env.world().resource::<Counter>().0, 1);
    println!("Snapshot restore and replay matched; counter is back at tick 1.");
    Ok(())
}

The setup has four responsibilities:

  • State: Counter is the authoritative gameplay resource. Its stable SnapshotType identity makes it serializable and restorable.
  • Input: the environment declares Noop as a supported action. This simple game increments the counter on every controlled tick.
  • Output: the observation exposes the counter value; the checksum covers both core state and the counter.
  • Schedules: reset initializes the episode, and AgentTick changes gameplay. Ordinary render frames do not advance this counter.

3. Run it ​

sh
cargo run

Expected output:

text
Snapshot restore and replay matched; counter is back at tick 1.

The assertions prove that restoring a snapshot and repeating the same action produces the same checksum, then restore_tick(1) reconstructs the earlier state. A checksum is a consistency check over your declared state; it does not prove arbitrary games deterministic across platforms.

4. Understand the result ​

The example deliberately uses Noop: the counter advances because the simulation ticks, even when the client requests no movement. An action is input to the game; the game decides its effect.

OperationTickCounterWhat you learned
Reset00Reset establishes the episode's initial state
Step, then save11A snapshot captures registered state at this tick
Step22The next action produces a checksum
Restore saved state11Restore replaces state without a gameplay tick
Repeat the step22The checksum matches the first transition
Restore tick 111History can reconstruct a recorded point

Try changing the increment from 1 to 2 and updating the counter assertions in main. Then follow Testing and reproducibility to turn the same contract into automated tests. To accept meaningful commands instead of Noop, continue with Actions and observations.

Run the repository example ​

If you want the example without creating a new project:

sh
git clone https://github.com/briansunter/bevy-agent.git
cd bevy-agent
cargo run -p bevy_agent_runner --example counter --locked

The repository also contains a complete platformer with movement, collisions, coins, rewards, terminal conditions, and capture:

sh
cargo run -p sample_platformer --example agent_play --locked

sample_platformer stays in the repository. It is not a crates.io package.

Where to go next ​

Personal Mac mini builds

On the pinned personal Mac mini, run build-storage-check before native builds and use cargo-storage from the canonical worktree, as described in the contributing guide. Other hosts use ordinary Cargo commands.

Released under MIT or Apache-2.0.