Skip to main content

limitless_cli/modules/
arcade.rs

1//! **SyntaxBreaker** — a zero-dependency terminal typing game.
2//!
3//! You get 60 seconds to type code snippets as fast as you can. Type each
4//! snippet exactly (case-sensitive); it auto-submits once you have typed the
5//! full length. Speed earns the bonus, mistakes cost points, and a timeout
6//! on any single snippet forces a retry-or-skip decision.
7//!
8//! The module is self-contained: terminal access goes through a small
9//! [`GameKeyReader`] / [`GameWriter`] abstraction (backed by `crossterm`,
10//! which is already a crate dependency) so the whole game loop is
11//! unit-testable with [`MockGameKeyReader`], [`CapturingGameWriter`] and a
12//! stepped [`GameClock`].
13//!
14//! High scores live in `.limitless/arcade_scores.json` (top 5, descending).
15//!
16//! ```
17//! use limitless_cli::modules::arcade::score_attempt;
18//!
19//! // Correct scrape, fast = 10 points + 5 bonus.
20//! assert_eq!(score_attempt(true, true), 15);
21//! // Correct but slow = base points only.
22//! assert_eq!(score_attempt(true, false), 10);
23//! // Missed attempt = flat penalty.
24//! assert_eq!(score_attempt(false, false), -2);
25//! ```
26
27use colored::Colorize;
28use std::fs;
29use std::io::{self, Write};
30use std::path::PathBuf;
31use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
32
33// ---------------------------------------------------------------------------
34// Game constants / rules
35// ---------------------------------------------------------------------------
36
37/// How long one full game lasts.
38pub const GAME_DURATION: Duration = Duration::from_secs(60);
39
40/// A single snippet must be completed within this window.
41pub const ATTEMPT_LIMIT: Duration = Duration::from_secs(3);
42
43/// Completing faster than this earns the speed bonus.
44pub const BONUS_WINDOW: Duration = Duration::from_secs(1);
45
46/// Points for a correctly typed snippet.
47pub const CORRECT_POINTS: i32 = 10;
48
49/// Extra points when a snippet is completed in under [`BONUS_WINDOW`].
50pub const BONUS_POINTS: i32 = 5;
51
52/// Points lost per wrong character (and for a timed-out attempt).
53pub const PENALTY: i32 = 2;
54
55/// How long the key reader waits for a key before the loop re-checks clocks.
56pub const POLL_TIMEOUT: Duration = Duration::from_millis(50);
57
58/// Max scores kept on the leaderboard.
59pub const MAX_SCORES: usize = 5;
60
61/// Directory (under the current working directory) holding game data.
62pub const SCORE_DIR: &str = ".limitless";
63
64/// Score file name inside [`SCORE_DIR`].
65pub const SCORE_FILE: &str = "arcade_scores.json";
66
67/// Fixed-width box used for every game frame.
68///
69/// ```
70/// use limitless_cli::modules::arcade::ARCADE_WIDTH;
71/// assert_eq!(ARCADE_WIDTH, 60);
72/// ```
73pub const ARCADE_WIDTH: usize = 60;
74
75/// Inner text width between the two vertical frame bars.
76const INNER_WIDTH: usize = ARCADE_WIDTH - 4;
77
78/// The snippet database the game draws from.
79pub const SNIPPETS: &[&str] = &[
80    "const x = 5;",
81    "let arr = [];",
82    "if (x > 0) { }",
83    "function hello() { }",
84    "for (let i = 0; i < 10; i++) { }",
85    "return null;",
86    "await fetch(\"/api\");",
87    "throw new Error(\"fail\");",
88    "Promise.all([]);",
89    "console.log(\"debug\");",
90    "[...array]",
91    "{ key: \"value\" }",
92    "x === y",
93    "try { } catch { }",
94    "export default App;",
95];
96
97// ---------------------------------------------------------------------------
98// Game result
99// ---------------------------------------------------------------------------
100
101/// Summary of one finished game, before it is written to the leaderboard.
102///
103/// ```
104/// use limitless_cli::modules::arcade::ArcadeResult;
105/// let result = ArcadeResult::default();
106/// assert_eq!(result.score, 0);
107/// assert!(result.rank.is_none());
108/// ```
109#[derive(Debug, Clone, PartialEq, Eq, Default)]
110pub struct ArcadeResult {
111    /// Total points (bonuses included, penalties subtracted).
112    pub score: i32,
113    /// Snippets typed correctly.
114    pub snippets_completed: u32,
115    /// Wrong characters pressed (each one carries [`PENALTY`]).
116    pub mistakes: u32,
117    /// Total forward characters typed.
118    pub chars_typed: u32,
119    /// Gross words-per-minute over the whole game.
120    pub wpm: u32,
121    /// Seconds actually played (cuts short on Ctrl+C).
122    pub duration_seconds: u32,
123    /// 1-based position on the persisted leaderboard when it made the top 5.
124    pub rank: Option<usize>,
125    /// Whether this game beat the previous best score.
126    pub is_new_high_score: bool,
127}
128
129// ---------------------------------------------------------------------------
130// Scoring
131// ---------------------------------------------------------------------------
132
133/// Scores one completed attempt.
134///
135/// - Correct and under 1 second → 10 points + 5 bonus.
136/// - Correct otherwise → 10 points.
137/// - Wrong / timed-out attempt → −2 points.
138///
139/// ```
140/// use limitless_cli::modules::arcade::{score_attempt, BONUS_POINTS, CORRECT_POINTS, PENALTY};
141/// assert_eq!(score_attempt(true, true), CORRECT_POINTS + BONUS_POINTS);
142/// assert_eq!(score_attempt(true, false), CORRECT_POINTS);
143/// assert_eq!(score_attempt(false, false), -PENALTY);
144/// ```
145pub fn score_attempt(correct: bool, under_1_second: bool) -> i32 {
146    if !correct {
147        return -PENALTY;
148    }
149    CORRECT_POINTS + if under_1_second { BONUS_POINTS } else { 0 }
150}
151
152/// Gross WPM from typing statistics: `(chars / 5) / minutes`.
153fn wpm_now(chars_typed: u32, elapsed: Duration) -> u32 {
154    let seconds = elapsed.as_secs_f64().max(1.0);
155    ((chars_typed as f64 / 5.0) / seconds * 60.0).round() as u32
156}
157
158/// Whole seconds still left in a game, clamped at zero.
159fn remaining_secs(duration: Duration, elapsed: Duration) -> u32 {
160    duration.saturating_sub(elapsed).as_secs() as u32
161}
162
163mod shuffle {
164    //! Tiny deterministic PRNG — the game adds no external dependencies.
165
166    /// `xorshift64*` generator, seeded from the wall clock at startup.
167    pub struct XorShift {
168        state: u64,
169    }
170
171    impl XorShift {
172        pub fn new(seed: u64) -> Self {
173            Self {
174                state: seed.max(1),
175            }
176        }
177
178        pub fn next_u64(&mut self) -> u64 {
179            let mut x = self.state;
180            x ^= x >> 12;
181            x ^= x << 25;
182            x ^= x >> 27;
183            self.state = x;
184            x.wrapping_mul(0x2545_F491_4F6C_DD1D)
185        }
186    }
187}
188
189/// Shuffles the snippet pool with `seed` so every game draws a fresh order.
190///
191/// ```
192/// use limitless_cli::modules::arcade::shuffled_with;
193/// let a = shuffled_with(42);
194/// let b = shuffled_with(42);
195/// let c = shuffled_with(1);
196/// assert_eq!(a, b, "same seed ⇒ same order");
197/// assert_ne!(a, c, "different seed ⇒ different order");
198/// ```
199pub fn shuffled_with(seed: u64) -> Vec<String> {
200    let mut rng = shuffle::XorShift::new(seed);
201    let mut items: Vec<String> = SNIPPETS.iter().map(|s| (*s).to_string()).collect();
202    let n = items.len();
203    for i in (1..n).rev() {
204        let j = (rng.next_u64() % (i as u64 + 1)) as usize;
205        items.swap(i, j);
206    }
207    items
208}
209
210/// The real game's snippet order, seeded from the wall clock.
211fn fresh_snippet_order() -> Vec<String> {
212    let seed = SystemTime::now()
213        .duration_since(UNIX_EPOCH)
214        .map(|d| d.as_nanos() as u64)
215        .unwrap_or(0x5EED);
216    shuffled_with(seed)
217}
218
219// ---------------------------------------------------------------------------
220// Terminal abstractions
221// ---------------------------------------------------------------------------
222
223/// A normalized key press the game understands.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum GameKey {
226    /// A printable character (space arrives here too).
227    Char(char),
228    /// Enter / return key.
229    Enter,
230    /// Backspace / delete.
231    Backspace,
232    /// Escape key.
233    Esc,
234    /// Ctrl+C — quits the game immediately.
235    CtrlC,
236    /// Any other key we intentionally ignore.
237    Unknown,
238}
239
240/// Abstraction over the terminal so the game can be driven by mock input.
241pub trait GameKeyReader {
242    /// Blocks up to `timeout`, returning the next key or `None` on expiration.
243    /// `None` also marks end-of-input for mocked readers.
244    fn read_key(&mut self, timeout: Duration) -> Option<GameKey>;
245}
246
247/// Key reader backed by a real terminal via the `crossterm` crate.
248pub struct TerminalGameKeyReader;
249
250impl GameKeyReader for TerminalGameKeyReader {
251    fn read_key(&mut self, timeout: Duration) -> Option<GameKey> {
252        loop {
253            if !crossterm::event::poll(timeout).unwrap_or(false) {
254                return None;
255            }
256            match crossterm::event::read() {
257                Ok(crossterm::event::Event::Key(event)) => return Some(game_key_from_crossterm(event)),
258                _ => continue,
259            }
260        }
261    }
262}
263
264/// Maps a crossterm key event onto [`GameKey`]. In raw mode Ctrl+C arrives
265/// as CONTROL + `c` and is mapped back to a quit signal.
266fn game_key_from_crossterm(event: crossterm::event::KeyEvent) -> GameKey {
267    if event
268        .modifiers
269        .contains(crossterm::event::KeyModifiers::CONTROL)
270        && event.code == crossterm::event::KeyCode::Char('c')
271    {
272        return GameKey::CtrlC;
273    }
274    match event.code {
275        crossterm::event::KeyCode::Char(' ') => GameKey::Char(' '),
276        crossterm::event::KeyCode::Char(c) => GameKey::Char(c),
277        crossterm::event::KeyCode::Enter => GameKey::Enter,
278        crossterm::event::KeyCode::Backspace => GameKey::Backspace,
279        crossterm::event::KeyCode::Esc => GameKey::Esc,
280        _ => GameKey::Unknown,
281    }
282}
283
284/// Abstraction over the output stream so the game can capture its frames.
285pub trait GameWriter {
286    /// Buffers `text` for display.
287    fn write(&mut self, text: &str);
288    /// Flushes buffered text to the real output.
289    fn flush(&mut self) -> io::Result<()>;
290    /// Clears the whole terminal and homes the cursor.
291    fn clear_screen(&mut self);
292}
293
294/// ANSI sequence that wipes the screen and moves to (1,1).
295const CLEAR_ANSI: &str = "\x1b[2J\x1b[H";
296
297/// Writer backed by the real standard output.
298pub struct StdoutGameWriter;
299
300impl GameWriter for StdoutGameWriter {
301    fn write(&mut self, text: &str) {
302        let _ = io::stdout().write_all(text.as_bytes());
303    }
304
305    fn flush(&mut self) -> io::Result<()> {
306        io::stdout().flush()
307    }
308
309    fn clear_screen(&mut self) {
310        let _ = io::stdout().write_all(CLEAR_ANSI.as_bytes());
311    }
312}
313
314/// Output stream for the game; `now` returns the current instant.
315pub trait GameClock {
316    /// The current time. Called once per loop iteration and once per read.
317    fn now(&mut self) -> Instant;
318}
319
320/// Clock backed by the real system time.
321pub struct SystemGameClock;
322
323impl GameClock for SystemGameClock {
324    fn now(&mut self) -> Instant {
325        Instant::now()
326    }
327}
328
329/// Deterministic test clock: each `now()` call advances by [`POLL_TIMEOUT`],
330/// modelling one poll interval passing on a real machine.
331#[derive(Debug, Clone)]
332pub struct StepClock {
333    t: Instant,
334}
335
336impl StepClock {
337    /// Creates a clock that starts at "now".
338    pub fn new() -> Self {
339        Self { t: Instant::now() }
340    }
341}
342
343impl Default for StepClock {
344    fn default() -> Self {
345        Self::new()
346    }
347}
348
349impl GameClock for StepClock {
350    fn now(&mut self) -> Instant {
351        self.t += POLL_TIMEOUT;
352        self.t
353    }
354}
355
356/// Restores the terminal to cooked mode when dropped, even on early returns.
357struct RawModeGuard;
358
359impl RawModeGuard {
360    fn enable() -> io::Result<Self> {
361        crossterm::terminal::enable_raw_mode()?;
362        Ok(Self)
363    }
364}
365
366impl Drop for RawModeGuard {
367    fn drop(&mut self) {
368        let _ = crossterm::terminal::disable_raw_mode();
369    }
370}
371
372// ---------------------------------------------------------------------------
373// Frame rendering
374// ---------------------------------------------------------------------------
375
376/// One line of the status area inside the game box.
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum StatusLine {
379    /// Shown while a snippet is being typed (modest, dim guidance).
380    Hint,
381    /// Shown after a failed attempt; asks for retry or skip.
382    Error(String),
383    /// Shown right after a correct attempt.
384    Success(String),
385}
386
387/// What the player is currently expected to do.
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389enum Phase {
390    Typing,
391    AwaitChoice,
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395enum RowStyle {
396    Border,
397    Title,
398    Plain,
399    Dim,
400    Snip,
401    Score,
402    Error,
403    Pass,
404}
405
406/// Renders one full frame of the game (ANSI-free).
407pub fn render_frame_plain(
408    snippet: &str,
409    typed: &str,
410    score: i32,
411    secs_left: u32,
412    wpm: u32,
413    status: &StatusLine,
414) -> String {
415    render_frame(snippet, typed, score, secs_left, wpm, status, false)
416}
417
418fn render_frame(
419    snippet: &str,
420    typed: &str,
421    score: i32,
422    secs_left: u32,
423    wpm: u32,
424    status: &StatusLine,
425    colored: bool,
426) -> String {
427    let status_row = match status {
428        StatusLine::Hint => (
429            RowStyle::Dim,
430            box_row("   Type it exactly · Backspace to fix · Ctrl+C to quit"),
431        ),
432        StatusLine::Error(msg) => (RowStyle::Error, box_row(&format!("✗ {msg}"))),
433        StatusLine::Success(msg) => (RowStyle::Pass, box_row(&format!("✓ {msg}"))),
434    };
435
436    let rows: Vec<(RowStyle, String)> = vec![
437        (RowStyle::Border, border_line(true)),
438        (RowStyle::Title, box_row("⚔️  SYNTAXBREAKER ARCADE GAME")),
439        (RowStyle::Border, separator_line()),
440        (RowStyle::Plain, box_row("")),
441        (RowStyle::Dim, box_row("Type the code snippet:")),
442        (RowStyle::Snip, box_row(snippet)),
443        (RowStyle::Plain, box_row("")),
444        (RowStyle::Plain, box_row(&format!("Your input: {typed}_"))),
445        (RowStyle::Plain, box_row("")),
446        status_row,
447        (RowStyle::Plain, box_row("")),
448        (
449            RowStyle::Score,
450            box_row(&format!("Score: {score}  |  Time: {secs_left}s  |  WPM: {wpm}")),
451        ),
452        (RowStyle::Border, border_line(false)),
453    ];
454
455    let mut out = String::new();
456    for (style, row) in rows {
457        out.push_str(&paint(row, style, colored));
458        out.push('\n');
459    }
460    out
461}
462
463/// The little leaderboard shown before a game starts.
464///
465/// ```
466/// use limitless_cli::modules::arcade::{render_scoreboard, ArcadeScoreboard};
467/// let mut board = ArcadeScoreboard::default();
468/// board.record(40);
469/// board.record(15);
470/// let out = render_scoreboard(&board);
471/// assert!(out.contains("1. 40"));
472/// assert!(out.contains("2. 15"));
473/// ```
474pub fn render_scoreboard(board: &ArcadeScoreboard) -> String {
475    let mut out = String::new();
476    out.push_str(&format!("{}\n", "🏆 TOP 5 SCORES".bold().cyan()));
477    if board.scores.is_empty() {
478        out.push_str(&format!(
479            "   {} — be the first!\n",
480            "No scores yet".yellow()
481        ));
482    }
483    for (i, score) in board.top5().iter().enumerate() {
484        let medal = match i {
485            0 => "🥇",
486            1 => "🥈",
487            2 => "🥉",
488            _ => "  ",
489        };
490        out.push_str(&format!("   {medal} {}. {score}\n", i + 1));
491    }
492    out
493}
494
495/// End-of-game summary: the final tally plus the updated leaderboard.
496fn render_game_over(result: &ArcadeResult, board: &ArcadeScoreboard) -> String {
497    let mut rows = vec![
498        (RowStyle::Border, border_line(true)),
499        (RowStyle::Title, box_row("🕹  SYNTAXBREAKER — GAME OVER")),
500        (RowStyle::Border, separator_line()),
501        (RowStyle::Plain, box_row("")),
502        (
503            RowStyle::Score,
504            box_row(&format!("Score: {}  |  WPM: {}", result.score, result.wpm)),
505        ),
506        (
507            RowStyle::Plain,
508            box_row(&format!(
509                "Snippets: {}  |  Mistakes: {}  |  Duration: {}s",
510                result.snippets_completed, result.mistakes, result.duration_seconds
511            )),
512        ),
513    ];
514
515    if result.is_new_high_score {
516        rows.push((
517            RowStyle::Pass,
518            box_row(&format!(
519                "🏆 NEW HIGH SCORE! (rank #{} on the board)",
520                result.rank.unwrap_or(1)
521            )),
522        ));
523    }
524
525    rows.push((RowStyle::Plain, box_row("")));
526    rows.push((RowStyle::Dim, box_row("High scores (top 5):")));
527    if board.scores.is_empty() {
528        rows.push((RowStyle::Plain, box_row("   — none yet —")));
529    }
530    for (i, score) in board.top5().iter().enumerate() {
531        let medal = match i {
532            0 => "🥇",
533            1 => "🥈",
534            2 => "🥉",
535            _ => "  ",
536        };
537        rows.push((RowStyle::Plain, box_row(&format!("   {medal} {}. {score}", i + 1))));
538    }
539    rows.push((RowStyle::Border, border_line(false)));
540
541    let mut out = String::new();
542    for (style, row) in rows {
543        out.push_str(&paint(row, style, true));
544        out.push('\n');
545    }
546    out
547}
548
549fn paint(row: String, style: RowStyle, colored: bool) -> String {
550    if !colored {
551        return row;
552    }
553    match style {
554        RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
555        RowStyle::Dim => row.dimmed().to_string(),
556        RowStyle::Snip => row.cyan().bold().to_string(),
557        RowStyle::Score => row.normal().to_string(),
558        RowStyle::Error => row.red().to_string(),
559        RowStyle::Pass => row.green().bold().to_string(),
560        RowStyle::Plain => row.normal().to_string(),
561    }
562}
563
564fn border_line(top: bool) -> String {
565    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
566    format!("{left}{}{right}", "─".repeat(ARCADE_WIDTH - 2))
567}
568
569fn separator_line() -> String {
570    format!("├{}┤", "─".repeat(ARCADE_WIDTH - 2))
571}
572
573fn box_row(content: &str) -> String {
574    format!("│ {} │", pad(content))
575}
576
577fn pad(content: &str) -> String {
578    let used = content.chars().count();
579    format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
580}
581
582// ---------------------------------------------------------------------------
583// High-score persistence
584// ---------------------------------------------------------------------------
585
586/// Serialized top-5 leaderboard stored in `arcade_scores.json`.
587///
588/// ```
589/// use limitless_cli::modules::arcade::{ArcadeScoreboard, MAX_SCORES};
590/// let mut board = ArcadeScoreboard::default();
591/// board.record(30);
592/// board.record(50);
593/// assert_eq!(board.top5(), vec![50, 30]);
594/// assert!(board.scores.len() <= MAX_SCORES);
595/// ```
596#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
597pub struct ArcadeScoreboard {
598    /// All recorded scores, kept descending and capped at [`MAX_SCORES`].
599    pub scores: Vec<u32>,
600}
601
602impl ArcadeScoreboard {
603    /// Loads the board from `path`; missing/corrupt files yield an empty board.
604    pub fn load(path: &std::path::Path) -> Self {
605        match fs::read_to_string(path) {
606            Ok(raw) => serde_json::from_str::<ArcadeScoreboard>(&raw)
607                .map(|mut b| {
608                    b.normalize();
609                    b
610                })
611                .unwrap_or_default(),
612            Err(_) => Self::default(),
613        }
614    }
615
616    /// Persists the board to `path`, creating parent directories as needed.
617    pub fn save(&self, path: &std::path::Path) -> io::Result<()> {
618        if let Some(parent) = path.parent() {
619            if !parent.as_os_str().is_empty() {
620                fs::create_dir_all(parent)?;
621            }
622        }
623        fs::write(path, serde_json::to_string_pretty(self)?)
624    }
625
626    /// Sorts descending, keeps the top [`MAX_SCORES`].
627    pub fn normalize(&mut self) {
628        self.scores.sort_unstable_by(|a, b| b.cmp(a));
629        self.scores.truncate(MAX_SCORES);
630    }
631
632    /// The current best score (0 when empty).
633    pub fn top_score(&self) -> u32 {
634        self.scores.first().copied().unwrap_or(0)
635    }
636
637    /// Top-5 scores, descending.
638    pub fn top5(&self) -> Vec<u32> {
639        self.scores[..self.scores.len().min(MAX_SCORES)].to_vec()
640    }
641
642    /// Inserts `score` on the board. Returns its 1-based rank when it stays
643    /// in the top 5, or `None` when it falls off (or is clamped to zero).
644    pub fn record(&mut self, score: i32) -> Option<usize> {
645        let score = score.max(0) as u32;
646        self.scores.push(score);
647        self.normalize();
648        self.scores.iter().position(|&s| s == score).map(|i| i + 1)
649    }
650}
651
652/// Whether `score` beats the previous best, i.e. every score strictly above
653/// `previous_top` deserves the 🏆 banner (the very first game counts).
654pub fn is_new_high_score(score: i32, previous_top: u32) -> bool {
655    score.max(0) as u32 > previous_top
656}
657
658/// Where the leaderboard lives: `.limitless/arcade_scores.json` in the CWD.
659pub fn score_file_path() -> PathBuf {
660    PathBuf::from(SCORE_DIR).join(SCORE_FILE)
661}
662
663// ---------------------------------------------------------------------------
664// Game loop
665// ---------------------------------------------------------------------------
666
667/// The testable game core. Runs `duration` seconds, drawing frames to
668/// `writer` and consuming keys from `reader`, with time supplied by `clock`.
669///
670/// The returned [`ArcadeResult`] carries the raw statistics; high-score
671/// ranking is applied afterwards by the caller.
672fn play_game(
673    reader: &mut dyn GameKeyReader,
674    writer: &mut dyn GameWriter,
675    clock: &mut dyn GameClock,
676    snippets: &[String],
677    duration: Duration,
678) -> ArcadeResult {
679    if snippets.is_empty() {
680        return ArcadeResult::default();
681    }
682
683    let started = clock.now();
684    let mut idx = 0usize;
685    let mut snippet: &str = &snippets[0];
686    let mut typed = String::new();
687    let mut attempt_start = started;
688
689    let mut score: i32 = 0;
690    let mut completed = 0u32;
691    let mut mistakes = 0u32;
692    let mut chars_typed = 0u32;
693
694    let mut status = StatusLine::Hint;
695    let mut phase = Phase::Typing;
696    let mut last_left = u32::MAX;
697    let mut dirty = true;
698    let mut quit = false;
699
700    while !quit {
701        let now = clock.now();
702        let elapsed = now.duration_since(started);
703        if elapsed >= duration {
704            break;
705        }
706
707        let secs_left = remaining_secs(duration, elapsed);
708        if dirty || secs_left != last_left {
709            writer.clear_screen();
710            writer.write(&render_frame(snippet, &typed, score, secs_left, wpm_now(chars_typed, elapsed), &status, true));
711            let _ = writer.flush();
712            last_left = secs_left;
713            dirty = false;
714        }
715
716        match reader.read_key(POLL_TIMEOUT) {
717            None => {
718                if phase == Phase::Typing && now.duration_since(attempt_start) >= ATTEMPT_LIMIT {
719                    score -= PENALTY;
720                    status = StatusLine::Error(format!(
721                        "Timeout −{PENALTY} points · [R]etry  [S]kip"
722                    ));
723                    phase = Phase::AwaitChoice;
724                    dirty = true;
725                }
726            }
727            Some(GameKey::CtrlC) => {
728                quit = true;
729            }
730            Some(GameKey::Esc) if phase == Phase::Typing => {
731                quit = true;
732            }
733            Some(GameKey::Char(c)) if phase == Phase::AwaitChoice => {
734                if c.eq_ignore_ascii_case(&'r') {
735                    typed.clear();
736                    attempt_start = clock.now();
737                    status = StatusLine::Hint;
738                    phase = Phase::Typing;
739                    dirty = true;
740                } else if c.eq_ignore_ascii_case(&'s') {
741                    advance_snippet(&mut idx, &mut snippet, snippets);
742                    typed.clear();
743                    attempt_start = clock.now();
744                    status = StatusLine::Hint;
745                    phase = Phase::Typing;
746                    dirty = true;
747                }
748            }
749            Some(GameKey::Enter | GameKey::Char(' ')) if phase == Phase::AwaitChoice => {
750                advance_snippet(&mut idx, &mut snippet, snippets);
751                typed.clear();
752                attempt_start = clock.now();
753                status = StatusLine::Hint;
754                phase = Phase::Typing;
755                dirty = true;
756            }
757            Some(GameKey::Char(c)) => {
758                typed.push(c);
759                chars_typed = chars_typed.saturating_add(1);
760                let pos = typed.chars().count() - 1;
761                if typed.chars().nth(pos) != snippet.chars().nth(pos) {
762                    mistakes = mistakes.saturating_add(1);
763                    score -= PENALTY;
764                }
765
766                if typed.chars().count() == snippet.chars().count() {
767                    let attempt_elapsed = clock.now().duration_since(attempt_start);
768                    if typed == snippet {
769                        let under_1s = attempt_elapsed < BONUS_WINDOW;
770                        score += score_attempt(true, under_1s);
771                        completed = completed.saturating_add(1);
772                        status = StatusLine::Success(format!(
773                            "+{} points!",
774                            score_attempt(true, under_1s)
775                        ));
776                        advance_snippet(&mut idx, &mut snippet, snippets);
777                        typed.clear();
778                        attempt_start = clock.now();
779                        phase = Phase::Typing;
780                    } else {
781                        status =
782                            StatusLine::Error("Mismatch · [R]etry  [S]kip".to_string());
783                        phase = Phase::AwaitChoice;
784                    }
785                    dirty = true;
786                } else {
787                    dirty = true;
788                }
789            }
790            Some(GameKey::Backspace) => {
791                typed.pop();
792                dirty = true;
793            }
794            _ => {}
795        }
796    }
797
798    let now = clock.now();
799    let elapsed = now.duration_since(started);
800    ArcadeResult {
801        score,
802        snippets_completed: completed,
803        mistakes,
804        chars_typed,
805        wpm: wpm_now(chars_typed, elapsed),
806        duration_seconds: elapsed.as_secs() as u32,
807        rank: None,
808        is_new_high_score: false,
809    }
810}
811
812fn advance_snippet<'a>(idx: &mut usize, snippet: &mut &'a str, snippets: &'a [String]) {
813    *idx = (*idx + 1) % snippets.len();
814    *snippet = &snippets[*idx];
815}
816
817// ---------------------------------------------------------------------------
818// Public entry points
819// ---------------------------------------------------------------------------
820
821/// Plays a full 60-second game on the real terminal, then persists and ranks
822/// the score, printing the final tally and leaderboard.
823pub fn run_typing_game() -> ArcadeResult {
824    let _guard = RawModeGuard::enable().ok();
825
826    let mut reader = TerminalGameKeyReader;
827    let mut writer = StdoutGameWriter;
828
829    let path = score_file_path();
830    let board = ArcadeScoreboard::load(&path);
831    let previous_top = board.top_score();
832
833    writer.write("⚔️  SYNTAXBREAKER\n");
834    writer.write(&render_scoreboard(&board));
835    writer.write("\nGet ready — the game starts now!\n");
836    let _ = writer.flush();
837
838    let snippets = fresh_snippet_order();
839    let mut clock = SystemGameClock;
840    let result = play_game(&mut reader, &mut writer, &mut clock, &snippets, GAME_DURATION);
841
842    drop(_guard);
843
844    let mut board = ArcadeScoreboard::load(&path);
845    let mut result = result;
846    result.rank = board.record(result.score);
847    result.is_new_high_score = is_new_high_score(result.score, previous_top);
848    let _ = board.save(&path);
849
850    let _ = io::stdout().write_all(CLEAR_ANSI.as_bytes());
851    let _ = io::stdout().write_all(render_game_over(&result, &board).as_bytes());
852    let _ = io::stdout().flush();
853
854    result
855}
856
857/// CLI entry point behind `limit arcade`.
858pub fn run_arcade() {
859    run_typing_game();
860}
861
862// ---------------------------------------------------------------------------
863// Tests
864// ---------------------------------------------------------------------------
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869    use std::collections::VecDeque;
870
871    struct TempDir(PathBuf);
872
873    impl TempDir {
874        fn new(prefix: &str) -> Self {
875            let nanos = SystemTime::now()
876                .duration_since(UNIX_EPOCH)
877                .map(|d| d.as_nanos())
878                .unwrap_or(0);
879            let path = std::env::temp_dir().join(format!(
880                "{}_arcade_{}_{}",
881                prefix,
882                std::process::id(),
883                nanos
884            ));
885            fs::create_dir_all(&path).expect("create temp dir");
886            Self(path)
887        }
888
889        fn path(&self) -> &std::path::Path {
890            &self.0
891        }
892    }
893
894    impl Drop for TempDir {
895        fn drop(&mut self) {
896            let _ = fs::remove_dir_all(&self.0);
897        }
898    }
899
900    /// Mock key reader that replays keys then returns `None` forever.
901    #[derive(Debug, Clone)]
902    struct MockGameKeyReader {
903        keys: VecDeque<GameKey>,
904    }
905
906    impl MockGameKeyReader {
907        fn new(keys: Vec<GameKey>) -> Self {
908            Self { keys: keys.into() }
909        }
910    }
911
912    impl GameKeyReader for MockGameKeyReader {
913        fn read_key(&mut self, _timeout: Duration) -> Option<GameKey> {
914            self.keys.pop_front()
915        }
916    }
917
918    /// Captures every frame/clear/leaderboard write for assertions.
919    #[derive(Debug, Clone, Default)]
920    struct CapturingGameWriter {
921        output: String,
922        clears: usize,
923    }
924
925    impl GameWriter for CapturingGameWriter {
926        fn write(&mut self, text: &str) {
927            self.output.push_str(text);
928        }
929
930        fn flush(&mut self) -> io::Result<()> {
931            Ok(())
932        }
933
934        fn clear_screen(&mut self) {
935            self.clears += 1;
936            self.output.push_str(CLEAR_ANSI);
937        }
938    }
939
940    fn keys_for(text: &str) -> Vec<GameKey> {
941        text.chars().map(GameKey::Char).collect()
942    }
943
944    fn run_game(keys: Vec<GameKey>, snippet: &str) -> (ArcadeResult, CapturingGameWriter) {
945        // End the game a few polls after the last key so leftover idle time
946        // never triggers a trailing per-snippet timeout in these tests.
947        let polls = (keys.len() + 4) as u64;
948        run_game_until(keys, snippet, Duration::from_millis(polls * POLL_TIMEOUT.as_millis() as u64))
949    }
950
951    fn run_game_until(
952        keys: Vec<GameKey>,
953        snippet: &str,
954        duration: Duration,
955    ) -> (ArcadeResult, CapturingGameWriter) {
956        let mut reader = MockGameKeyReader::new(keys);
957        let mut writer = CapturingGameWriter::default();
958        let mut clock = StepClock::new();
959        let snippets = vec![snippet.to_string()];
960        let result = play_game(&mut reader, &mut writer, &mut clock, &snippets, duration);
961        (result, writer)
962    }
963
964    #[test]
965    fn snippet_database_contains_all_expected_entries() {
966        let expected = [
967            "const x = 5;",
968            "let arr = [];",
969            "if (x > 0) { }",
970            "function hello() { }",
971            "for (let i = 0; i < 10; i++) { }",
972            "return null;",
973            "await fetch(\"/api\");",
974            "throw new Error(\"fail\");",
975            "Promise.all([]);",
976            "console.log(\"debug\");",
977            "[...array]",
978            "{ key: \"value\" }",
979            "x === y",
980            "try { } catch { }",
981            "export default App;",
982        ];
983        for snippet in expected {
984            assert!(SNIPPETS.contains(&snippet), "missing {snippet:?}");
985        }
986        assert_eq!(SNIPPETS.len(), 15);
987    }
988
989    #[test]
990    fn shuffle_is_deterministic_and_permutes() {
991        let a = shuffled_with(42);
992        let b = shuffled_with(42);
993        let c = shuffled_with(1);
994        assert_eq!(a, b);
995        assert_ne!(a, c);
996        let mut sorted: Vec<String> = a.clone();
997        sorted.sort_unstable();
998        let mut stock = SNIPPETS.to_vec();
999        stock.sort_unstable();
1000        assert_eq!(sorted, stock, "shuffle must not drop or add snippets");
1001    }
1002
1003    #[test]
1004    fn score_attempt_respects_rules() {
1005        assert_eq!(score_attempt(true, true), 15, "base + bonus");
1006        assert_eq!(score_attempt(true, false), 10, "base only");
1007        assert_eq!(score_attempt(false, true), -2, "still wrong fast");
1008        assert_eq!(score_attempt(false, false), -2);
1009    }
1010
1011    #[test]
1012    fn wpm_formula_counts_words_per_minute() {
1013        // 100 characters in 60 seconds → 20 words → 20 WPM.
1014        assert_eq!(wpm_now(100, Duration::from_secs(60)), 20);
1015        // 60 characters in 60 seconds → 12 WPM.
1016        assert_eq!(wpm_now(60, Duration::from_secs(60)), 12);
1017        assert_eq!(wpm_now(0, Duration::ZERO), 0);
1018    }
1019
1020    #[test]
1021    fn remaining_seconds_clamps_at_zero() {
1022        assert_eq!(remaining_secs(Duration::from_secs(60), Duration::from_secs(45)), 15);
1023        assert_eq!(remaining_secs(Duration::from_secs(60), Duration::from_secs(61)), 0);
1024    }
1025
1026    #[test]
1027    fn leaderboard_keeps_top_five_descending() {
1028        let mut board = ArcadeScoreboard::default();
1029        for score in [10, 40, 20, 50, 30] {
1030            board.record(score);
1031        }
1032        assert_eq!(board.top5(), vec![50, 40, 30, 20, 10]);
1033        assert_eq!(board.top_score(), 50);
1034        // A sixth mediocre score never pushes in.
1035        assert_eq!(board.record(5), None);
1036        assert_eq!(board.top5(), vec![50, 40, 30, 20, 10]);
1037        // A sixth great score bumps rank 5.
1038        assert_eq!(board.record(45), Some(2));
1039        assert_eq!(board.top5(), vec![50, 45, 40, 30, 20]);
1040    }
1041
1042    #[test]
1043    fn leaderboard_round_trips_to_disk() {
1044        let dir = TempDir::new("roundtrip");
1045        let path = dir.path().join(SCORE_FILE);
1046        let mut board = ArcadeScoreboard::default();
1047        board.record(35);
1048        board.record(99);
1049        board.save(&path).expect("save board");
1050        let loaded = ArcadeScoreboard::load(&path);
1051        assert_eq!(loaded, board);
1052        // save() should have created the parent directory implicitly.
1053        assert!(path.parent().unwrap().is_dir());
1054    }
1055
1056    #[test]
1057    fn leaderboard_load_missing_file_is_empty() {
1058        let dir = TempDir::new("missing");
1059        let board = ArcadeScoreboard::load(&dir.path().join("nope.json"));
1060        assert_eq!(board.top5(), Vec::<u32>::new());
1061    }
1062
1063    #[test]
1064    fn leaderboard_normalizes_on_load() {
1065        let dir = TempDir::new("normalize");
1066        let path = dir.path().join(SCORE_FILE);
1067        fs::write(&path, r#"{"scores":[3,100,7,2,9,88]}"#).unwrap();
1068        let board = ArcadeScoreboard::load(&path);
1069        assert_eq!(board.top5(), vec![100, 88, 9, 7, 3]);
1070    }
1071
1072    #[test]
1073    fn new_high_score_only_when_beating_previous_top() {
1074        assert!(is_new_high_score(10, 0), "first game counts");
1075        assert!(is_new_high_score(50, 30));
1076        assert!(!is_new_high_score(30, 30), "ties are not new records");
1077        assert!(!is_new_high_score(10, 30));
1078        assert!(!is_new_high_score(-4, 3), "negative scores never win");
1079    }
1080
1081    #[test]
1082    fn frame_renders_all_layers() {
1083        let frame = render_frame_plain(
1084            "const x = 5;",
1085            "const x = 5",
1086            21,
1087            45,
1088            12,
1089            &StatusLine::Hint,
1090        );
1091        assert!(frame.contains("⚔️  SYNTAXBREAKER ARCADE GAME"));
1092        assert!(frame.contains("const x = 5;"));
1093        assert!(frame.contains("Your input: const x = 5_"));
1094        assert!(frame.contains("Score: 21  |  Time: 45s  |  WPM: 12"));
1095        assert!(frame.contains("Type it exactly"));
1096    }
1097
1098    #[test]
1099    fn frame_shows_error_status_with_retry_skip() {
1100        let frame = render_frame_plain(
1101            "const x = 5;",
1102            "",
1103            -2,
1104            58,
1105            0,
1106            &StatusLine::Error("Mismatch · [R]etry  [S]kip".into()),
1107        );
1108        assert!(frame.contains("✗ Mismatch · [R]etry  [S]kip"));
1109    }
1110
1111    #[test]
1112    fn every_frame_line_is_exactly_box_width() {
1113        for status in [
1114            StatusLine::Hint,
1115            StatusLine::Error("Mismatch".into()),
1116            StatusLine::Success("+15 points!".into()),
1117        ] {
1118            let frame = render_frame_plain(
1119                "for (let i = 0; i < 10; i++) { }",
1120                "for (let i = 0; i < 10;",
1121                30,
1122                30,
1123                25,
1124                &status,
1125            );
1126            for line in frame.lines() {
1127                assert_eq!(
1128                    line.chars().count(),
1129                    ARCADE_WIDTH,
1130                    "off-width row: {line:?}"
1131                );
1132            }
1133        }
1134    }
1135
1136    #[test]
1137    fn scoreboard_renders_top_scores_with_medals() {
1138        let mut board = ArcadeScoreboard::default();
1139        for s in [50, 40, 30, 20, 10] {
1140            board.record(s);
1141        }
1142        let out = render_scoreboard(&board);
1143        assert!(out.contains("🏆 TOP 5 SCORES"));
1144        assert!(out.contains("1. 50"));
1145        assert!(out.contains("5. 10"));
1146        assert!(out.contains("🥇"));
1147    }
1148
1149    #[test]
1150    fn game_correct_snippet_scores_with_fast_bonus() {
1151        // "const x = 5;" is 12 chars typed in ~12 polls (600ms) → < 1s.
1152        let (result, _) = run_game(keys_for("const x = 5;"), "const x = 5;");
1153        assert_eq!(result.score, 15, "10 base + 5 speed bonus");
1154        assert_eq!(result.snippets_completed, 1);
1155        assert_eq!(result.mistakes, 0);
1156        assert_eq!(result.chars_typed, 12);
1157    }
1158
1159    #[test]
1160    fn game_wrong_character_penalizes_and_offers_skip() {
1161        // Only the first char differs ('q' vs 'r'); the rest match.
1162        let mut keys = keys_for("qeturn null;");
1163        keys.push(GameKey::Char('s')); // skip after the mismatch
1164        let (result, writer) = run_game(keys, "return null;");
1165
1166        assert_eq!(result.mistakes, 1);
1167        assert_eq!(result.score, -2, "one wrong character costs PENALTY");
1168        assert_eq!(result.snippets_completed, 0);
1169        assert!(writer.output.contains("[R]etry  [S]kip"));
1170    }
1171
1172    #[test]
1173    fn game_retry_lets_you_fix_the_attempt() {
1174        // Finish the wrong attempt (only the last letter off), then retry
1175        // and type it perfectly on the second go.
1176        let mut keys = keys_for("return nullX");
1177        keys.push(GameKey::Char('r')); // retry
1178        keys.extend(keys_for("return null;"));
1179        let (result, _) = run_game(keys, "return null;");
1180
1181        // Start at −2 for the one mistake, then +10 base +5 fast bonus.
1182        assert_eq!(result.score, -2 + 10 + 5);
1183        assert_eq!(result.mistakes, 1, "the first mistake is still counted");
1184        assert_eq!(result.snippets_completed, 1);
1185    }
1186
1187    #[test]
1188    fn game_timeout_penalizes_after_three_seconds() {
1189        // No keys at all: the attempt must time out once, then the game ends
1190        // before a second 3s window can elapse.
1191        let (result, writer) = run_game_until(vec![], "const x = 5;", Duration::from_secs(5));
1192        assert_eq!(result.score, -2, "single timeout penalty");
1193        assert_eq!(result.snippets_completed, 0);
1194        assert!(writer.output.contains("Timeout"));
1195    }
1196
1197    #[test]
1198    fn game_ctrl_c_quits_immediately() {
1199        let (result, _) = run_game(vec![GameKey::CtrlC], "const x = 5;");
1200        assert_eq!(result.score, 0);
1201        assert_eq!(result.snippets_completed, 0);
1202        assert_eq!(result.duration_seconds, 0, "quit before a full second");
1203    }
1204
1205    #[test]
1206    fn game_empty_input_completes_no_snippets() {
1207        let (result, writer) = run_game(vec![], "const x = 5;");
1208        assert_eq!(result.score, 0);
1209        assert_eq!(result.snippets_completed, 0);
1210        assert!(writer.clears > 0, "screen was cleared between frames");
1211    }
1212
1213    #[test]
1214    fn game_typed_past_speed_window_loses_bonus() {
1215        // Space out the keystrokes with leftover polls so the attempt takes
1216        // longer than 1s but shorter than the 3s limit.
1217        let snippet = "x === y";
1218        let mut keys = Vec::new();
1219        for c in snippet.chars() {
1220            keys.push(GameKey::Char(c));
1221            for _ in 0..22 {
1222                keys.push(GameKey::Unknown); // ~1.1s of dead time total
1223            }
1224        }
1225        // Last forward char judgement should land past the window.
1226        let (result, _) = run_game_until(keys, snippet, Duration::from_secs(8));
1227        assert_eq!(result.score, 10, "base points, no speed bonus");
1228        assert_eq!(result.snippets_completed, 1);
1229    }
1230
1231    #[test]
1232    fn arcade_result_default_is_zeroed() {
1233        let result = ArcadeResult::default();
1234        assert_eq!(result.score, 0);
1235        assert_eq!(result.snippets_completed, 0);
1236        assert_eq!(result.wpm, 0);
1237        assert_eq!(result.rank, None);
1238        assert!(!result.is_new_high_score);
1239        let path = score_file_path();
1240        assert_eq!(path.parent().unwrap().to_string_lossy(), SCORE_DIR);
1241        assert_eq!(path.file_name().unwrap(), SCORE_FILE);
1242    }
1243
1244    // --- Named coverage tests ----------------------------------------------
1245
1246    #[test]
1247    fn test_typing_game_scoring() {
1248        assert_eq!(score_attempt(true, true), CORRECT_POINTS + BONUS_POINTS);
1249        assert_eq!(score_attempt(true, false), CORRECT_POINTS);
1250        assert_eq!(score_attempt(false, false), -PENALTY);
1251        assert_eq!(score_attempt(false, true), -PENALTY);
1252        assert!(is_new_high_score(10, 0), "first game counts");
1253        assert!(is_new_high_score(30, 10));
1254        assert!(!is_new_high_score(10, 10), "ties are not records");
1255        assert!(!is_new_high_score(5, 30));
1256    }
1257
1258    #[test]
1259    fn test_high_score_persistence() {
1260        use std::thread::sleep;
1261        use std::time::Duration;
1262        let dir = TempDir::new("named_scores");
1263        let path = dir.path().join(SCORE_FILE);
1264        let mut board = ArcadeScoreboard::default();
1265        board.record(25);
1266        board.record(80);
1267        board.record(40);
1268        assert_eq!(board.record(10), Some(4), "10 ranks 4th on a 3-score board");
1269
1270        board.save(&path).expect("save board");
1271        let loaded = ArcadeScoreboard::load(&path);
1272        assert_eq!(loaded, board, "round-trip must preserve the board");
1273        assert_eq!(loaded.top5(), vec![80, 40, 25, 10]);
1274        assert_eq!(loaded.top_score(), 80);
1275        assert_eq!(loaded.scores.len(), 4);
1276
1277        // Re-saving from a fresh load must normalize identically.
1278        sleep(Duration::from_millis(5));
1279        loaded.save(&path).expect("save again");
1280        assert_eq!(ArcadeScoreboard::load(&path), loaded);
1281    }
1282}