//! A tool-assisted player: plays Galaga with a simple heuristic and random //! variation, and whenever a life is lost it rewinds to an earlier //! checkpoint and tries a different future. What survives is written as an //! input movie (`galaga::movie`) that replays the run exactly from //! power-on. Usage: //! galaga-tas [--rom DIR] [--out movie.json] [--frames N] [--seed S] [--mod mods/NAME.paths] //! //! With --mod the game runs with that path mod (`galaga::paths::PathMod`), //! and the movie carries its patches. //! //! Lost life = the fighter's slot (0x31) enters state 0x08 (exploding) or //! the reserve count at 0x9820 drops (a capture); `docs/ram-map.md`. //! //! --dual: get the dual fighter the way a player does, then keep it. The //! search has three phases, read from RAM (measured 2026-10-01): 0, no //! captive: the player stands under diving bosses and spares them, and a //! capture (the reserve drops, the fighter does not explode, a captured //! fighter appears in slots 0x00-0x03, then the reserve count drops) is the //! goal, not a loss, so with --dual only explosions and phase losses count; 1, a //! captive: the player chases the boss that dives with it and shoots it, //! never firing up at a captive in formation, and losing the captive is a //! loss; 2, the dual fighter (0x9827 != 0): losing it is a loss. A //! candidate that reaches the next phase is preferred and committed through //! that moment. use std::collections::HashMap; use std::path::PathBuf; use emu_galaga::galaga::movie::{ram_crc32, ModSource, Movie}; use emu_galaga::galaga::objects::{objects, slot, state, Object}; use emu_galaga::galaga::paths::PathMod; use emu_galaga::galaga::roms::load_directory; use emu_galaga::galaga::snapshot::Snapshot; use emu_galaga::galaga::sound::Sound; use emu_galaga::galaga::video::Video; use emu_galaga::galaga::Machine; const CHECKPOINT: u64 = 30; /// How far ahead each candidate future is played before it is trusted. const LOOKAHEAD: u64 = 180; const CANDIDATES: u64 = 16; const RIGHT: u8 = 0x02; const LEFT: u8 = 0x08; const FIRE: u8 = 0x01; const START1: u8 = 0x04; /// Free play, 3 lives, bonus 20K/70K/every 70K, easy, demo sounds on. const DSW_A: u8 = 0xf7; const DSW_B: u8 = 0x90; struct Rng(u64); impl Rng { fn next(&mut self) -> u64 { // splitmix64 self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); let mut z = self.0; z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); z ^ (z >> 31) } fn below(&mut self, n: u64) -> u64 { self.next() % n } } /// The heuristic player: a plan (chase, wander, hold) re-drawn every few /// frames, bomb dodging, and fire whenever a rocket could be in the air. struct Player { rng: Rng, /// --dual: the phase (see the top), or None for plain play. dual: Option, plan_until: u64, mode: u8, target_slot: u8, wander: u8, fire_on: bool, } impl Player { fn controls(&mut self, frame: u64, playing: bool, objs: &[Object; 64]) -> [u8; 2] { if !playing { // Press start in pulses until the game is on. let start = frame >= 800 && frame % 120 < 20; return [0, if start { START1 } else { 0 }]; } let ship = objs[slot::FIGHTER as usize]; let (sx, _) = ship.center(); if frame >= self.plan_until { self.plan_until = frame + 6 + self.rng.below(30); self.mode = match self.rng.below(10) { 0..=6 => 0, // chase 7 | 8 => 1, // wander _ => 2, // hold }; self.wander = if self.rng.below(2) == 0 { LEFT } else { RIGHT }; let enemies: Vec<&Object> = objs[..0x30] .iter() .filter(|o| { matches!( o.state, state::IN_FORMATION | state::DIVING | state::ENTERING | state::HOME_ROTATING ) && o.on_screen() }) .collect(); if !enemies.is_empty() { // Prefer the lowest flying enemy half the time. let flying = enemies .iter() .filter(|o| o.state != state::IN_FORMATION) .max_by_key(|o| o.y); self.target_slot = match flying { Some(o) if self.rng.below(2) == 0 => o.slot, _ => enemies[self.rng.below(enemies.len() as u64) as usize].slot, }; } } if self.dual == Some(0) || self.dual == Some(1) { // Phase 0: stand under the lowest diving boss (its beam). // Phase 1: chase the lowest diving boss (the captive's escort). let boss = objs[0x18..0x1c] .iter() .filter(|o| o.state == state::DIVING && o.on_screen()) .max_by_key(|o| o.y); if let Some(b) = boss { self.target_slot = b.slot; self.mode = 0; } } let mut stick = match self.mode { 0 => { let (tx, _) = objs[self.target_slot as usize].center(); let jitter = self.rng.below(5) as i32 - 2; if tx + jitter > sx + 3 { RIGHT } else if tx + jitter < sx - 3 { LEFT } else { 0 } } 1 => self.wander, _ => 0, }; // Dodge: a bomb or a diving enemy close above and in line. for o in objs.iter().take(0x3c) { let threat = (slot::BOMBS.contains(&o.slot) && o.state == state::SHOT) || (o.slot < 0x30 && matches!(o.state, state::DIVING | state::ENTERING)); if !threat || !o.on_screen() { continue; } let (ox, oy) = o.center(); let dy = ship.y - oy; // The dual fighter's second ship flies 15 px to the right. let wide = if self.dual == Some(2) { 15 } else { 0 }; if (0..70).contains(&dy) && ox > sx - 14 && ox < sx + wide + 14 { stick = if ox > sx + wide / 2 { LEFT } else { RIGHT }; if sx < 20 { stick = RIGHT; } else if sx > 204 { stick = LEFT; } } } // Fire as fast as the 51xx allows: it counts a press only after two // frames down and two up (docs/custom-io.md), so press for frames // 0-1 of every 4, three times in four. if frame % 4 == 0 { self.fire_on = self.rng.below(4) != 0; } let mut fire = if frame % 4 < 2 && self.fire_on { FIRE } else { 0 }; let in_line = |o: &Object| o.on_screen() && (o.center().0 - sx).abs() < 12; match self.dual { // Spare the bosses: one of them must capture the fighter. Some(0) if objs[0x18..0x1c] .iter() .any(|o| o.state != state::FREE && in_line(o)) => { fire = 0 } // Never shoot up at a captive (or its boss) in formation. Some(1) if objs[..4] .iter() .any(|o| o.state == state::IN_FORMATION && in_line(o)) => { fire = 0 } _ => {} } [stick, fire] } } /// The --dual phase the board is in (see the top): 2 with the dual fighter, /// 1 with a captured fighter (slots 0x00-0x03 alive, or the rescued ship /// docking there), else 0; None outside play. (On the first frame of play /// the attract demo's captives and dual flag are still in RAM, cleared a /// frame later, and the reserve count is not yet set: measured.) fn phase(board: &Board) -> Option { let s = board.machine.shared.borrow(); Some(if s.ram2[0x201] != 3 || s.ram3[0x020] >= 0x10 { return None; } else if s.ram3[0x027] != 0 { 2 } else if (0..4).any(|i| s.ram1[2 * i] != state::FREE) { 1 } else { 0 }) } /// Play `player` for up to `n` frames from `frame`: how many frames passed /// before a loss (`n` if none), the inputs used, and (--dual) the frame the /// next phase began, if it did. fn rollout( board: &mut Board, player: &mut Player, frame: u64, n: u64, ) -> (u64, Vec<[u8; 2]>, Option) { let mut ins = Vec::with_capacity(n as usize); let dual = player.dual.is_some(); let mut current = if dual { phase(board).unwrap_or(0) } else { 0 }; let mut goal = None; let mut lower_for = 0; for i in 0..n { // 0x9201 game state 3 = play; 0x9820 reserve ships. let playing = board.machine.shared.borrow().ram2[0x201] == 3; let reserve_before = board.ram3(0x020); let objs = objects(&board.machine.shared.borrow()); if dual { player.dual = Some(current); } let controls = player.controls(frame + i, playing, &objs); board.machine.set_controls(controls); board.machine.run_frame(); ins.push(controls); let reserve_after = board.ram3(0x020); let exploded = board.ram1(2 * slot::FIGHTER as usize) == state::FIGHTER_EXPLODING; let captured = playing && reserve_before < 0x10 && reserve_after == reserve_before.wrapping_sub(1); if exploded { return (i, ins, goal); } if !dual { if captured { return (i, ins, goal); } continue; } // A capture costs a reserve ship without an explosion; with // --dual it is how the game goes on, and the phases judge it. The // pair's second ship (slot 0x30) exploding is a loss too. if board.ram1(2 * slot::FIGHTER_2 as usize) == state::FIGHTER_EXPLODING { return (i, ins, goal); } let Some(p) = phase(board) else { continue; }; if p > current { current = p; goal.get_or_insert(i); lower_for = 0; } else if p < current { // Lost the captive or the dual (allowing a frame or two of // hand-over between the docking slot and the dual flag). lower_for += 1; if lower_for > 2 { return (i, ins, goal); } } else { lower_for = 0; } } (n, ins, goal) } struct Board { machine: Machine, video: Video, sound: Sound, } impl Board { fn snapshot(&self) -> Snapshot { self.machine.snapshot(&self.video, &self.sound) } fn restore(&mut self, snap: &Snapshot) { self.machine .restore(snap, &mut self.video, &mut self.sound) .unwrap(); } fn ram1(&self, offset: usize) -> u8 { self.machine.shared.borrow().ram1[offset] } fn ram3(&self, offset: usize) -> u8 { self.machine.shared.borrow().ram3[offset] } } fn main() { let mut args = std::env::args().skip(1); let mut rom_dir = PathBuf::from("rom/galaga"); let mut out = PathBuf::from("movies/tas.json"); let mut frames: u64 = 72_000; let mut seed: u64 = 1; let mut path_mod: Option = None; let mut dual = false; while let Some(arg) = args.next() { let mut value = || args.next().unwrap_or_else(|| panic!("{arg} needs a value")); match arg.as_str() { "--rom" => rom_dir = PathBuf::from(value()), "--out" => out = PathBuf::from(value()), "--frames" => frames = value().parse().expect("--frames N"), "--seed" => seed = value().parse().expect("--seed S"), "--mod" => path_mod = Some(PathMod::load(std::path::Path::new(&value())).unwrap()), "--dual" => dual = true, _ => panic!("unknown argument {arg}"), } } let roms = load_directory(&rom_dir).unwrap_or_else(|e| { eprintln!("{}: {e}", rom_dir.display()); std::process::exit(2) }); let mut board = Board { machine: Machine::new(&roms), video: Video::new(&roms), sound: Sound::new(&roms), }; board.machine.set_dips(DSW_A, DSW_B); if let Some(m) = &path_mod { m.check(&roms.sub).unwrap(); m.apply(&mut board.machine).unwrap(); } let mut inputs: Vec<[u8; 2]> = Vec::new(); let mut checkpoints: Vec = Vec::new(); let mut failures: HashMap = HashMap::new(); let mut attempt: u64 = 0; let mut rewinds = 0u64; let mut stage_frames: Vec<(u8, u64)> = Vec::new(); let mut dual_frames: Vec<(u8, u64)> = Vec::new(); // Each step: from the checkpoint at `frame`, try candidate futures of // LOOKAHEAD frames and commit the first CHECKPOINT frames of the first // one that survives (or of the longest-lived one if its first segment // is safe). If no candidate survives even one segment, rewind. while (inputs.len() as u64) < frames { let frame = inputs.len() as u64; checkpoints.truncate((frame / CHECKPOINT) as usize); checkpoints.push(board.snapshot()); let here = frame / CHECKPOINT; let mut best: (u64, Vec<[u8; 2]>, Option) = (0, Vec::new(), None); for k in 0..CANDIDATES { if k > 0 { board.restore(&checkpoints[here as usize]); } let mut rng = Rng(seed ^ frame.wrapping_mul(0x9e37_79b9) ^ (k << 40) ^ (attempt << 52)); rng.next(); let mut player = Player { rng, dual: dual.then_some(0), plan_until: 0, mode: 0, target_slot: 0, wander: 0, fire_on: false, }; let (survived, ins, goal) = rollout(&mut board, &mut player, frame, LOOKAHEAD); // A safe future that reaches the next phase beats a safe one // that does not; otherwise the longest-lived. let key = |s: u64, g: Option| (s == LOOKAHEAD && g.is_some(), s); if key(survived, goal) > key(best.0, best.2) || best.1.is_empty() { best = (survived, ins, goal); } if survived == LOOKAHEAD && (!dual || goal.is_some()) { break; } } board.restore(&checkpoints[here as usize]); if best.0 >= CHECKPOINT { // Commit one segment, or through the next phase's start. let commit = match best.2 { Some(g) if best.0 == LOOKAHEAD => { ((g / CHECKPOINT + 1) * CHECKPOINT).min(LOOKAHEAD) as usize } _ => CHECKPOINT as usize, }; if let (Some(g), LOOKAHEAD) = (best.2, best.0) { eprintln!("frame {frame}: phase reached at +{g}"); } for (i, &c) in best.1[..commit].iter().enumerate() { if i > 0 && i as u64 % CHECKPOINT == 0 { checkpoints.push(board.snapshot()); } board.machine.set_controls(c); board.machine.run_frame(); inputs.push(c); } } else { // Rewind further back the more often this stretch has failed. let fails = failures.entry(here).or_insert(0); *fails += 1; let back = u64::from(*fails).min(40); if *fails > 2 { eprintln!("frame {frame}: no candidate survives, failure {fails} here, back {back} checkpoints"); } let to = here.saturating_sub(back).max(1); board.restore(&checkpoints[to as usize]); inputs.truncate((to * CHECKPOINT) as usize); attempt += 1; rewinds += 1; continue; } let stage = board.ram3(0x021); let playing = board.machine.shared.borrow().ram2[0x201] == 3; if dual && playing { let p = phase(&board).unwrap_or(0); if dual_frames.last().map(|&(q, _)| q) != Some(p) { dual_frames.retain(|&(_, f)| f < frame); dual_frames.push((p, frame)); } } if playing && stage_frames.last().map(|&(s, _)| s) != Some(stage) { stage_frames.retain(|&(_, f)| f < frame); stage_frames.push((stage, frame)); eprintln!("frame {frame:6}: stage {stage:3} ({rewinds} rewinds so far)"); } } // The movie must replay from power-on to the same board. let mut check = Machine::new(&roms); check.set_dips(DSW_A, DSW_B); if let Some(m) = &path_mod { m.apply(&mut check).unwrap(); } for &c in &inputs { check.set_controls(c); check.run_frame(); } let replay_crc = ram_crc32(&check); let search_crc = ram_crc32(&board.machine); assert_eq!( replay_crc, search_crc, "the replay from power-on differs from the searched run" ); let reached = stage_frames.last().map(|&(s, _)| s).unwrap_or(0); let lives = if dual { "losing no ship but the one captured for the dual fighter" } else { "without losing a life" }; let note = format!( "galaga-tas seed {seed}: {frames} frames, reached stage {reached} {lives}, \ {rewinds} rewinds. Stage starts (stage, frame): {stage_frames:?}" ); let note = if dual { format!("{note}. --dual phases (phase, frame): {dual_frames:?}") } else { note }; let note = match &path_mod { Some(m) => format!("{note}. Path mod: {}", m.name), None => note, }; let mut movie = Movie::from_inputs(DSW_A, DSW_B, &inputs, &board.machine, ¬e); if let Some(m) = &path_mod { movie.path_mod = Some(ModSource { name: m.name.clone(), text: m.text.clone(), }); } if let Some(dir) = out.parent() { std::fs::create_dir_all(dir).unwrap(); } std::fs::write(&out, movie.to_json()).unwrap(); println!( "{note}\nreplay verified (RAM CRC-32 {replay_crc:08x}) -> {}", out.display() ); }