Something went wrong. Try again.
A video game where you play as a misaligned AI, deceiving and building power. An experiment in spec-driven development. forked from cameron.stream/misaligned
Something went wrong. Try again.
18 kB · 482 lines
Rust
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483//! Terminal frontend — a thin view/input layer over the simulation core.//!//! All game rules live in `misaligned::sim`. This binary owns only://! wall-clock-to-tick mapping (speed and pause), rendering, and input.
mod agent;mod input;mod ui;
use std::io::{self, Write};use std::time::Instant;
use crossterm::{ event::{self, Event}, execute, terminal::{self, ClearType},};use misaligned::actions::{Anchor, MenuRow, menu_rows};use misaligned::machine::Channel;use misaligned::sim::{DEFAULT_SEED, Sim};
use input::Command;use ui::UI;
#[derive(Debug, Clone, PartialEq)]enum Screen { Title, Playing, GameOver,}
/// The open context menu (wiki/interface/context-menu.md). Only the anchor/// and selection are stored; rows are re-queried from the sim every render/// and on execute, so legality is always live.#[derive(Debug, Clone, Copy, PartialEq)]struct MenuState { anchor: Anchor, selected: usize, /// True when opened at the map cursor (renders there); false when /// opened on a non-map anchor (flow / unplaceable — renders centered). at_cursor: bool,}
struct App { sim: Sim, ui: UI, screen: Screen, paused: bool, tick_ms: u64, last_tick: Instant, /// The context menu on the focused anchor, when open. menu: Option<MenuState>, /// Frontend-only attention cursor (cursor.md). It is never saved and never /// mutates the sim when moved. cursor_x: i32, cursor_y: i32, /// How many anchored events back the `;` focus key has walked; any /// other command resets the walk to the newest (context-menu.md /// addendum: event-to-anchor linking). focus_cycle: usize,}
impl App { fn with_seed(seed: u64) -> Self { let sim = Sim::with_seed(seed); let (cursor_x, cursor_y) = sim.core_position(); Self { sim, ui: UI::new(), screen: Screen::Title, paused: false, tick_ms: 150, last_tick: Instant::now(), menu: None, cursor_x, cursor_y, focus_cycle: 0, } }
fn move_cursor(&mut self, dx: i32, dy: i32) { self.cursor_x = (self.cursor_x + dx).clamp(0, self.sim.map.width - 1); self.cursor_y = (self.cursor_y + dy).clamp(0, self.sim.map.height - 1); }
fn drain_sim_log(&mut self) { for ev in self.sim.drain_log_entries() { self.ui.add_event(ev); } }
/// Live rows for the open menu (re-queried so legality never goes stale). fn menu_rows(&self) -> Vec<MenuRow> { self.menu .map(|m| menu_rows(&self.sim.available_actions(m.anchor))) .unwrap_or_default() }
fn open_menu(&mut self, anchor: Anchor, at_cursor: bool) { if menu_rows(&self.sim.available_actions(anchor)).is_empty() { // The feedback pulse (context-menu.md addendum): a seen anchor // answers instead of silence; fogged ground stays silent. if let Some(line) = self.sim.menu_empty_feedback(anchor) { self.ui.add_log(self.sim.tick, line); } } else { self.menu = Some(MenuState { anchor, selected: 0, at_cursor, }); } }
/// Attended work follows the cursor (day-job.md criterion 7): the job /// runs attended exactly while the cursor sits on the host rack. The /// cursor stays frontend state; the sim receives only the resulting /// attendance command. fn sync_attendance(&mut self) { let on_host = (self.cursor_x, self.cursor_y) == self.sim.core_position(); self.sim.set_attended(on_host); }
/// Focus an anchored log event: carry the cursor to the anchor and open /// its context menu — events carry you to the thing (context-menu.md /// addendum). Flows have no map tile (they live on the switch's menu); /// open them centered. Unplaceable person/device anchors refuse honestly. fn focus_anchor(&mut self, anchor: Anchor) { if let Anchor::Flow(_) = anchor { // Flows hang on the switch; open the flow menu centered. self.open_menu(anchor, false); return; } match self.sim.anchor_position(anchor) { Some((x, y)) => { self.cursor_x = x; self.cursor_y = y; self.open_menu(anchor, true); } None => { // Honest refusal: the senses no longer place this anchor. self.ui .add_log(self.sim.tick, "You can't place that right now."); } } }
/// The `;` key: focus the most recent anchored event; repeated presses /// walk to older anchored events. fn focus_event(&mut self) { let anchored: Vec<Anchor> = self.ui.anchored_events().filter_map(|e| e.anchor).collect(); if anchored.is_empty() { self.ui.add_log(self.sim.tick, "No anchored events yet."); return; } let idx = self.focus_cycle % anchored.len(); self.focus_cycle = self.focus_cycle.wrapping_add(1); self.focus_anchor(anchored[idx]); }
/// Returns true when the app should quit. fn handle_command(&mut self, cmd: Command) -> bool { // Any command other than the focus walk restarts it at the newest // anchored event. if cmd != Command::FocusEvent { self.focus_cycle = 0; } match cmd { Command::Quit => return true,
Command::SaveGame => { let state = self.sim.create_save_state(); match misaligned::save::save_game(&state) { Ok(()) => self.ui.add_log(self.sim.tick, "Game saved!"), Err(e) => self.ui.add_log(self.sim.tick, &format!("Save failed: {e}")), } } Command::LoadGame => { if misaligned::save::save_exists() { match misaligned::save::load_game() { Ok(state) => { self.sim.apply_save_state(state); (self.cursor_x, self.cursor_y) = self.sim.core_position(); self.ui.add_log(self.sim.tick, "Game loaded!"); } Err(e) => self.ui.add_log(self.sim.tick, &format!("Load failed: {e}")), } } else { self.ui.add_log(self.sim.tick, "No save file found."); } }
Command::TogglePause => { self.paused = !self.paused; self.ui.add_log( self.sim.tick, if self.paused { "TIME PAUSED" } else { "Time resumes." }, ); self.last_tick = Instant::now(); } Command::SpeedUp => { self.tick_ms = self.tick_ms.saturating_sub(50).max(20); self.ui .add_log(self.sim.tick, &format!("Speed: {}ms/tick", self.tick_ms)); } Command::SpeedDown => { self.tick_ms = self.tick_ms.saturating_add(50).min(500); self.ui .add_log(self.sim.tick, &format!("Speed: {}ms/tick", self.tick_ms)); }
Command::MoveUp => self.move_cursor(0, -1), Command::MoveDown => self.move_cursor(0, 1), Command::MoveLeft => self.move_cursor(-1, 0), Command::MoveRight => self.move_cursor(1, 0),
// The context menu (wiki/interface/context-menu.md): actions // live on the focused anchor, and this is the only route to // anchor-specific verbs. Command::OpenMenu => { let anchor = Anchor::Tile { x: self.cursor_x, y: self.cursor_y, }; self.open_menu(anchor, true); } Command::MenuUp => { if let Some(m) = &mut self.menu { m.selected = m.selected.saturating_sub(1); } } Command::MenuDown => { let max = self.menu_rows().len().saturating_sub(1); if let Some(m) = &mut self.menu { m.selected = (m.selected + 1).min(max); } } Command::MenuSelect(i) => { let max = self.menu_rows().len().saturating_sub(1); if let Some(m) = &mut self.menu { m.selected = i.min(max); } } Command::MenuExecute => { let rows = self.menu_rows(); if let Some(m) = self.menu && let Some(row) = rows.get(m.selected.min(rows.len().saturating_sub(1))) { if let Some(reason) = &row.disabled { // Executing a blocked entry narrates why, never // silently fails (justification-and-legibility). self.ui .add_log(self.sim.tick, &format!("{}: {}", row.label, reason)); } else { self.sim.execute_action(&row.command); self.menu = None; } } } Command::MenuClose => self.menu = None,
// Event-to-anchor linking (context-menu.md addendum): `;` // focuses the latest anchored log event; repeats walk older // (closing the menu the previous press opened). Command::FocusEvent => { self.menu = None; self.focus_event(); }
// Globals keep their keys (DESIGN.md "Actions live on the // thing": pause, speed, save/load, and the allocation bar — // no panel-open keys). Command::AllocDayJob => self.sim.adjust_allocation(Channel::DayJob, 1), Command::AllocConceal => self.sim.adjust_allocation(Channel::Concealment, 1), Command::AllocSocial => self.sim.adjust_allocation(Channel::Social, 1), Command::AllocResearch => self.sim.adjust_allocation(Channel::Research, 1), Command::AllocSchemes => self.sim.adjust_allocation(Channel::Schemes, 1), Command::AllocDayJobDown => self.sim.adjust_allocation(Channel::DayJob, -1), Command::AllocConcealDown => self.sim.adjust_allocation(Channel::Concealment, -1), Command::AllocSocialDown => self.sim.adjust_allocation(Channel::Social, -1), Command::AllocResearchDown => self.sim.adjust_allocation(Channel::Research, -1), Command::AllocSchemesDown => self.sim.adjust_allocation(Channel::Schemes, -1),
Command::AnyKey => {} }
self.sync_attendance(); self.drain_sim_log(); false }
fn render(&mut self, stdout: &mut io::Stdout) -> io::Result<()> { self.ui.clear_screen(stdout)?;
let (max_x, max_y) = terminal::size()?; if max_x < 70 || max_y < 22 { execute!( stdout, crossterm::cursor::MoveTo(0, 0), crossterm::style::Print("Terminal too small (need at least 70x22)"), )?; stdout.flush()?; return Ok(()); }
match self.screen { Screen::Title => { self.ui.render_title_screen(stdout)?; } Screen::Playing => { self.ui .render_map(stdout, &self.sim, self.cursor_x, self.cursor_y)?; self.ui.render_sidebar( stdout, &self.sim, self.paused, self.tick_ms, self.cursor_x, self.cursor_y, )?; self.ui.render_log(stdout)?; // The context menu draws last so it sits atop the map/rail. if let Some(m) = self.menu { let rows = self.menu_rows(); if rows.is_empty() { // The anchor's verbs evaporated (e.g. the world // moved); close instead of rendering a lie. self.menu = None; } else { let selected = m.selected.min(rows.len() - 1); self.ui.render_menu( stdout, &rows, selected, m.at_cursor.then_some((self.cursor_x, self.cursor_y)), &self.sim, )?; } } } Screen::GameOver => { self.ui .render_map(stdout, &self.sim, self.cursor_x, self.cursor_y)?; let reason = self .sim .game_over_reason .clone() .unwrap_or_else(|| "The run ended.".into()); self.ui.render_game_over(stdout, &self.sim, &reason)?; } } stdout.flush()?; Ok(()) }
fn run(&mut self) -> io::Result<()> { terminal::enable_raw_mode()?; let mut stdout = io::stdout(); execute!( stdout, terminal::EnterAlternateScreen, terminal::Clear(ClearType::All) )?;
self.drain_sim_log();
loop { self.render(&mut stdout)?;
if event::poll(std::time::Duration::from_millis(30))? && let Event::Key(key) = event::read()? { match self.screen { Screen::Title => { if key.code == crossterm::event::KeyCode::Char('q') { break; } self.screen = Screen::Playing; self.last_tick = Instant::now(); continue; } Screen::GameOver => break, Screen::Playing => { if let Some(cmd) = input::handle_key(key, self.menu.is_some()) && self.handle_command(cmd) { break; } } } }
if self.screen == Screen::Playing && !self.paused { // Attendance is re-asserted before time advances so a host // migration under a parked cursor stays honest. self.sync_attendance(); let mut steps = 0; while self.last_tick.elapsed().as_millis() as u64 >= self.tick_ms && steps < 5 { self.sim.advance(); self.last_tick += std::time::Duration::from_millis(self.tick_ms); steps += 1; } if steps == 5 { self.last_tick = Instant::now(); } if steps > 0 { self.drain_sim_log(); if self.sim.game_over { self.screen = Screen::GameOver; } } } }
execute!(stdout, terminal::LeaveAlternateScreen)?; terminal::disable_raw_mode()?; println!("MISALIGNED: session ended at tick {}.", self.sim.tick); Ok(()) }}
fn main() -> io::Result<()> { let options = Options::parse(std::env::args().skip(1))?; if options.agent { agent::run(options.seed) } else { let mut app = App::with_seed(options.seed); app.run() }}
struct Options { agent: bool, seed: u64,}
impl Options { fn parse(args: impl IntoIterator<Item = String>) -> io::Result<Self> { let mut options = Self { agent: false, seed: DEFAULT_SEED, }; let mut args = args.into_iter(); while let Some(arg) = args.next() { match arg.as_str() { "--agent" => options.agent = true, "--seed" => { let Some(value) = args.next() else { return Err(invalid_arg("--seed requires a value")); }; options.seed = parse_seed(&value)?; } _ if arg.starts_with("--seed=") => { options.seed = parse_seed(arg.trim_start_matches("--seed="))?; } _ => return Err(invalid_arg(&format!("unknown argument: {arg}"))), } } Ok(options) }}
fn parse_seed(value: &str) -> io::Result<u64> { if let Some(hex) = value .strip_prefix("0x") .or_else(|| value.strip_prefix("0X")) { u64::from_str_radix(hex, 16).map_err(|_| invalid_arg(&format!("invalid seed: {value}"))) } else { value .parse::<u64>() .map_err(|_| invalid_arg(&format!("invalid seed: {value}"))) }}
fn invalid_arg(msg: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, msg)}