Skip to main content

levels_accept/
levels_accept.rs

1//! EXP/levels (v2-c) acceptance harness: boots a zero-Rust project headless
2//! and drives two consecutive battles, printing as evidence:
3//!
4//! 1. battle 1's narration — the EXP award + level-up lines after the win
5//!    text, and the heal-the-delta pools in the harvested party state;
6//! 2. battle 2 starting from the GROWN stats (level 2, higher max HP);
7//! 3. the Start menu's Party view showing `Lv` + the EXP progress line;
8//! 4. a save round trip — level/exp resume into a fresh boot.
9//!
10//! Usage:
11//!
12//! ```sh
13//! cargo run -p dotzuki-runner --example levels_accept -- <project-dir> [shot-dir]
14//! ```
15//!
16//! The project should trigger two `startBattle` commands in a row (the
17//! acceptance patches StartTown's `script.scene` accordingly) and carry a
18//! `battle.levels` block (the scaffolded jrpg template ships one).
19
20use std::path::{Path, PathBuf};
21
22use dotzuki_engine::render::{FrameBuffer, Rgba};
23use dotzuki_engine::render_config::RenderConfig;
24use dotzuki_renderer::input::{GbButton, InputState};
25use dotzuki_runner::headless::save_png;
26use dotzuki_runner::{LoadedProject, RunnerGame, RunnerOptions, SCREEN_H, SCREEN_W};
27
28/// Draw the current frame into a PNG.
29fn snap(game: &mut RunnerGame, dir: &Option<PathBuf>, name: &str) {
30    let Some(dir) = dir else { return };
31    let mut fb = FrameBuffer::new(
32        RenderConfig::new(SCREEN_W as u32, SCREEN_H as u32),
33        Rgba::BLACK,
34    );
35    game.draw(&mut fb);
36    let path = dir.join(format!("{name}.png"));
37    save_png(&fb, &path).expect("screenshot");
38    println!("  [shot] {}", path.display());
39}
40
41fn frame(game: &mut RunnerGame, mask: u8) {
42    let mut input = InputState::new();
43    input.set_from_bitmask(mask);
44    game.update(&input);
45}
46
47fn idle(game: &mut RunnerGame, n: u32) {
48    for _ in 0..n {
49        frame(game, 0);
50    }
51}
52
53fn press_a(game: &mut RunnerGame) {
54    frame(game, GbButton::A.bit_mask());
55    idle(game, 1);
56}
57
58fn print_party(game: &RunnerGame, when: &str) {
59    let Some(party) = game.party_state() else { return };
60    println!("party state {when}:");
61    for m in party {
62        println!(
63            "  {} level {} exp {} hp {} mp {} status {:?}",
64            m.id, m.level, m.exp, m.hp, m.mp, m.status
65        );
66    }
67}
68
69fn main() {
70    let mut args = std::env::args().skip(1);
71    let dir = args.next().expect("usage: levels_accept <project-dir> [shot-dir]");
72    let shot_dir = args.next().map(PathBuf::from);
73
74    let save_file = Path::new(&dir).join(".dotzuki-save.json");
75    let project = LoadedProject::load(Path::new(&dir)).expect("load project");
76    let mut game = RunnerGame::new(
77        project,
78        RunnerOptions {
79            headless: true,
80            fresh: true,
81            write_saves: true,
82            save_file: Some(save_file.clone()),
83            // Deterministic battles: always hit, 89% variance, never crit.
84            rng_script: Some(vec![50, 100, 1]),
85            ..RunnerOptions::default()
86        },
87    )
88    .expect("boot game");
89
90    // Auto-A drives everything: dialogue pages, battle narration, and the
91    // Fight → first-skill picks. Back-to-back `startBattle` commands swap
92    // Battle→Battle INSIDE one update, so a new battle is detected by the
93    // log resetting, not just by a not-in-battle gap.
94    let mut battle_no = 0usize;
95    let mut completed = 0usize;
96    let mut last_log: Vec<String> = Vec::new();
97    let mut was_in_battle = false;
98    let mut snapped_battle = false;
99
100    for frame_no in 0..6000u32 {
101        if frame_no % 4 == 0 {
102            frame(&mut game, GbButton::A.bit_mask());
103        } else {
104            idle(&mut game, 1);
105        }
106
107        let in_battle = game.battle().is_some();
108        if in_battle {
109            let log_len = game.battle().unwrap().log().len();
110            let new_battle = !was_in_battle || log_len < last_log.len();
111            if new_battle {
112                if was_in_battle {
113                    // Seamless Battle→Battle swap: close the previous one
114                    // out (the party state is already harvested).
115                    completed += 1;
116                    println!("\nbattle {completed} log:");
117                    for line in &last_log {
118                        println!("  {line}");
119                    }
120                    print_party(&game, &format!("after battle {completed}"));
121                    println!();
122                    if completed == 2 {
123                        break;
124                    }
125                }
126                battle_no += 1;
127                let battle = game.battle().unwrap();
128                println!("battle {battle_no} starts:");
129                for c in battle.party() {
130                    println!(
131                        "  {} level {} exp {} hp {}/{} mp {}/{} atk {}",
132                        c.name, c.level, c.exp, c.hp, c.max_hp, c.mp, c.max_mp, c.attack
133                    );
134                }
135                if battle_no == 2 && !snapped_battle {
136                    snapped_battle = true;
137                    snap(&mut game, &shot_dir, "battle2-start");
138                }
139            }
140            last_log = game.battle().unwrap().log().to_vec();
141        } else if was_in_battle {
142            completed += 1;
143            println!("\nbattle {completed} log:");
144            for line in &last_log {
145                println!("  {line}");
146            }
147            print_party(&game, &format!("after battle {completed}"));
148            println!();
149            last_log.clear();
150            if completed == 2 {
151                break;
152            }
153        }
154        was_in_battle = in_battle;
155    }
156    if completed < 2 {
157        eprintln!("harness: only {completed} battle(s) completed within the frame cap");
158        std::process::exit(1);
159    }
160
161    // Dismiss the post-battle text so the scene finishes (the save is
162    // written at that stable point).
163    for _ in 0..40 {
164        if game.dialogue_text().is_none() {
165            break;
166        }
167        press_a(&mut game);
168    }
169    assert!(game.flag("SLIMES_BEATEN"), "the scene ran to its end");
170
171    // The Party view: Lv + EXP progress on the member rows.
172    frame(&mut game, GbButton::Start.bit_mask());
173    idle(&mut game, 1);
174    press_a(&mut game); // Party
175    println!("party view:");
176    for line in game.menu_lines().expect("party view open") {
177        println!("  {line}");
178    }
179    snap(&mut game, &shot_dir, "party-view");
180    frame(&mut game, GbButton::B.bit_mask());
181    idle(&mut game, 1);
182    frame(&mut game, GbButton::B.bit_mask());
183    idle(&mut game, 1);
184
185    // Save round trip: a fresh boot resumes level/exp from the save.
186    println!("\nsave round trip ({}):", save_file.display());
187    let project = LoadedProject::load(Path::new(&dir)).expect("reload project");
188    let game = RunnerGame::new(
189        project,
190        RunnerOptions {
191            headless: true,
192            save_file: Some(save_file),
193            rng_script: Some(vec![50, 100, 1]),
194            ..RunnerOptions::default()
195        },
196    )
197    .expect("boot from save");
198    print_party(&game, "resumed from the save");
199    assert!(
200        game.party_state().is_some_and(|p| p[0].level > 1),
201        "level must survive the save round trip"
202    );
203    println!("\nacceptance OK");
204}