use colored::Colorize;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
pub const GAME_DURATION: Duration = Duration::from_secs(60);
pub const ATTEMPT_LIMIT: Duration = Duration::from_secs(3);
pub const BONUS_WINDOW: Duration = Duration::from_secs(1);
pub const CORRECT_POINTS: i32 = 10;
pub const BONUS_POINTS: i32 = 5;
pub const PENALTY: i32 = 2;
pub const POLL_TIMEOUT: Duration = Duration::from_millis(50);
pub const MAX_SCORES: usize = 5;
pub const SCORE_DIR: &str = ".limitless";
pub const SCORE_FILE: &str = "arcade_scores.json";
pub const ARCADE_WIDTH: usize = 60;
const INNER_WIDTH: usize = ARCADE_WIDTH - 4;
pub const SNIPPETS: &[&str] = &[
"const x = 5;",
"let arr = [];",
"if (x > 0) { }",
"function hello() { }",
"for (let i = 0; i < 10; i++) { }",
"return null;",
"await fetch(\"/api\");",
"throw new Error(\"fail\");",
"Promise.all([]);",
"console.log(\"debug\");",
"[...array]",
"{ key: \"value\" }",
"x === y",
"try { } catch { }",
"export default App;",
];
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ArcadeResult {
pub score: i32,
pub snippets_completed: u32,
pub mistakes: u32,
pub chars_typed: u32,
pub wpm: u32,
pub duration_seconds: u32,
pub rank: Option<usize>,
pub is_new_high_score: bool,
}
pub fn score_attempt(correct: bool, under_1_second: bool) -> i32 {
if !correct {
return -PENALTY;
}
CORRECT_POINTS + if under_1_second { BONUS_POINTS } else { 0 }
}
fn wpm_now(chars_typed: u32, elapsed: Duration) -> u32 {
let seconds = elapsed.as_secs_f64().max(1.0);
((chars_typed as f64 / 5.0) / seconds * 60.0).round() as u32
}
fn remaining_secs(duration: Duration, elapsed: Duration) -> u32 {
duration.saturating_sub(elapsed).as_secs() as u32
}
mod shuffle {
pub struct XorShift {
state: u64,
}
impl XorShift {
pub fn new(seed: u64) -> Self {
Self {
state: seed.max(1),
}
}
pub fn next_u64(&mut self) -> u64 {
let mut x = self.state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.state = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
}
}
pub fn shuffled_with(seed: u64) -> Vec<String> {
let mut rng = shuffle::XorShift::new(seed);
let mut items: Vec<String> = SNIPPETS.iter().map(|s| (*s).to_string()).collect();
let n = items.len();
for i in (1..n).rev() {
let j = (rng.next_u64() % (i as u64 + 1)) as usize;
items.swap(i, j);
}
items
}
fn fresh_snippet_order() -> Vec<String> {
let seed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0x5EED);
shuffled_with(seed)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GameKey {
Char(char),
Enter,
Backspace,
Esc,
CtrlC,
Unknown,
}
pub trait GameKeyReader {
fn read_key(&mut self, timeout: Duration) -> Option<GameKey>;
}
pub struct TerminalGameKeyReader;
impl GameKeyReader for TerminalGameKeyReader {
fn read_key(&mut self, timeout: Duration) -> Option<GameKey> {
loop {
if !crossterm::event::poll(timeout).unwrap_or(false) {
return None;
}
match crossterm::event::read() {
Ok(crossterm::event::Event::Key(event)) => return Some(game_key_from_crossterm(event)),
_ => continue,
}
}
}
}
fn game_key_from_crossterm(event: crossterm::event::KeyEvent) -> GameKey {
if event
.modifiers
.contains(crossterm::event::KeyModifiers::CONTROL)
&& event.code == crossterm::event::KeyCode::Char('c')
{
return GameKey::CtrlC;
}
match event.code {
crossterm::event::KeyCode::Char(' ') => GameKey::Char(' '),
crossterm::event::KeyCode::Char(c) => GameKey::Char(c),
crossterm::event::KeyCode::Enter => GameKey::Enter,
crossterm::event::KeyCode::Backspace => GameKey::Backspace,
crossterm::event::KeyCode::Esc => GameKey::Esc,
_ => GameKey::Unknown,
}
}
pub trait GameWriter {
fn write(&mut self, text: &str);
fn flush(&mut self) -> io::Result<()>;
fn clear_screen(&mut self);
}
const CLEAR_ANSI: &str = "\x1b[2J\x1b[H";
pub struct StdoutGameWriter;
impl GameWriter for StdoutGameWriter {
fn write(&mut self, text: &str) {
let _ = io::stdout().write_all(text.as_bytes());
}
fn flush(&mut self) -> io::Result<()> {
io::stdout().flush()
}
fn clear_screen(&mut self) {
let _ = io::stdout().write_all(CLEAR_ANSI.as_bytes());
}
}
pub trait GameClock {
fn now(&mut self) -> Instant;
}
pub struct SystemGameClock;
impl GameClock for SystemGameClock {
fn now(&mut self) -> Instant {
Instant::now()
}
}
#[derive(Debug, Clone)]
pub struct StepClock {
t: Instant,
}
impl StepClock {
pub fn new() -> Self {
Self { t: Instant::now() }
}
}
impl Default for StepClock {
fn default() -> Self {
Self::new()
}
}
impl GameClock for StepClock {
fn now(&mut self) -> Instant {
self.t += POLL_TIMEOUT;
self.t
}
}
struct RawModeGuard;
impl RawModeGuard {
fn enable() -> io::Result<Self> {
crossterm::terminal::enable_raw_mode()?;
Ok(Self)
}
}
impl Drop for RawModeGuard {
fn drop(&mut self) {
let _ = crossterm::terminal::disable_raw_mode();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StatusLine {
Hint,
Error(String),
Success(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
Typing,
AwaitChoice,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
Border,
Title,
Plain,
Dim,
Snip,
Score,
Error,
Pass,
}
pub fn render_frame_plain(
snippet: &str,
typed: &str,
score: i32,
secs_left: u32,
wpm: u32,
status: &StatusLine,
) -> String {
render_frame(snippet, typed, score, secs_left, wpm, status, false)
}
fn render_frame(
snippet: &str,
typed: &str,
score: i32,
secs_left: u32,
wpm: u32,
status: &StatusLine,
colored: bool,
) -> String {
let status_row = match status {
StatusLine::Hint => (
RowStyle::Dim,
box_row(" Type it exactly · Backspace to fix · Ctrl+C to quit"),
),
StatusLine::Error(msg) => (RowStyle::Error, box_row(&format!("✗ {msg}"))),
StatusLine::Success(msg) => (RowStyle::Pass, box_row(&format!("✓ {msg}"))),
};
let rows: Vec<(RowStyle, String)> = vec![
(RowStyle::Border, border_line(true)),
(RowStyle::Title, box_row("⚔️ SYNTAXBREAKER ARCADE GAME")),
(RowStyle::Border, separator_line()),
(RowStyle::Plain, box_row("")),
(RowStyle::Dim, box_row("Type the code snippet:")),
(RowStyle::Snip, box_row(snippet)),
(RowStyle::Plain, box_row("")),
(RowStyle::Plain, box_row(&format!("Your input: {typed}_"))),
(RowStyle::Plain, box_row("")),
status_row,
(RowStyle::Plain, box_row("")),
(
RowStyle::Score,
box_row(&format!("Score: {score} | Time: {secs_left}s | WPM: {wpm}")),
),
(RowStyle::Border, border_line(false)),
];
let mut out = String::new();
for (style, row) in rows {
out.push_str(&paint(row, style, colored));
out.push('\n');
}
out
}
pub fn render_scoreboard(board: &ArcadeScoreboard) -> String {
let mut out = String::new();
out.push_str(&format!("{}\n", "🏆 TOP 5 SCORES".bold().cyan()));
if board.scores.is_empty() {
out.push_str(&format!(
" {} — be the first!\n",
"No scores yet".yellow()
));
}
for (i, score) in board.top5().iter().enumerate() {
let medal = match i {
0 => "🥇",
1 => "🥈",
2 => "🥉",
_ => " ",
};
out.push_str(&format!(" {medal} {}. {score}\n", i + 1));
}
out
}
fn render_game_over(result: &ArcadeResult, board: &ArcadeScoreboard) -> String {
let mut rows = vec![
(RowStyle::Border, border_line(true)),
(RowStyle::Title, box_row("🕹 SYNTAXBREAKER — GAME OVER")),
(RowStyle::Border, separator_line()),
(RowStyle::Plain, box_row("")),
(
RowStyle::Score,
box_row(&format!("Score: {} | WPM: {}", result.score, result.wpm)),
),
(
RowStyle::Plain,
box_row(&format!(
"Snippets: {} | Mistakes: {} | Duration: {}s",
result.snippets_completed, result.mistakes, result.duration_seconds
)),
),
];
if result.is_new_high_score {
rows.push((
RowStyle::Pass,
box_row(&format!(
"🏆 NEW HIGH SCORE! (rank #{} on the board)",
result.rank.unwrap_or(1)
)),
));
}
rows.push((RowStyle::Plain, box_row("")));
rows.push((RowStyle::Dim, box_row("High scores (top 5):")));
if board.scores.is_empty() {
rows.push((RowStyle::Plain, box_row(" — none yet —")));
}
for (i, score) in board.top5().iter().enumerate() {
let medal = match i {
0 => "🥇",
1 => "🥈",
2 => "🥉",
_ => " ",
};
rows.push((RowStyle::Plain, box_row(&format!(" {medal} {}. {score}", i + 1))));
}
rows.push((RowStyle::Border, border_line(false)));
let mut out = String::new();
for (style, row) in rows {
out.push_str(&paint(row, style, true));
out.push('\n');
}
out
}
fn paint(row: String, style: RowStyle, colored: bool) -> String {
if !colored {
return row;
}
match style {
RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
RowStyle::Dim => row.dimmed().to_string(),
RowStyle::Snip => row.cyan().bold().to_string(),
RowStyle::Score => row.normal().to_string(),
RowStyle::Error => row.red().to_string(),
RowStyle::Pass => row.green().bold().to_string(),
RowStyle::Plain => row.normal().to_string(),
}
}
fn border_line(top: bool) -> String {
let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
format!("{left}{}{right}", "─".repeat(ARCADE_WIDTH - 2))
}
fn separator_line() -> String {
format!("├{}┤", "─".repeat(ARCADE_WIDTH - 2))
}
fn box_row(content: &str) -> String {
format!("│ {} │", pad(content))
}
fn pad(content: &str) -> String {
let used = content.chars().count();
format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
}
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct ArcadeScoreboard {
pub scores: Vec<u32>,
}
impl ArcadeScoreboard {
pub fn load(path: &std::path::Path) -> Self {
match fs::read_to_string(path) {
Ok(raw) => serde_json::from_str::<ArcadeScoreboard>(&raw)
.map(|mut b| {
b.normalize();
b
})
.unwrap_or_default(),
Err(_) => Self::default(),
}
}
pub fn save(&self, path: &std::path::Path) -> io::Result<()> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
fs::write(path, serde_json::to_string_pretty(self)?)
}
pub fn normalize(&mut self) {
self.scores.sort_unstable_by(|a, b| b.cmp(a));
self.scores.truncate(MAX_SCORES);
}
pub fn top_score(&self) -> u32 {
self.scores.first().copied().unwrap_or(0)
}
pub fn top5(&self) -> Vec<u32> {
self.scores[..self.scores.len().min(MAX_SCORES)].to_vec()
}
pub fn record(&mut self, score: i32) -> Option<usize> {
let score = score.max(0) as u32;
self.scores.push(score);
self.normalize();
self.scores.iter().position(|&s| s == score).map(|i| i + 1)
}
}
pub fn is_new_high_score(score: i32, previous_top: u32) -> bool {
score.max(0) as u32 > previous_top
}
pub fn score_file_path() -> PathBuf {
PathBuf::from(SCORE_DIR).join(SCORE_FILE)
}
fn play_game(
reader: &mut dyn GameKeyReader,
writer: &mut dyn GameWriter,
clock: &mut dyn GameClock,
snippets: &[String],
duration: Duration,
) -> ArcadeResult {
if snippets.is_empty() {
return ArcadeResult::default();
}
let started = clock.now();
let mut idx = 0usize;
let mut snippet: &str = &snippets[0];
let mut typed = String::new();
let mut attempt_start = started;
let mut score: i32 = 0;
let mut completed = 0u32;
let mut mistakes = 0u32;
let mut chars_typed = 0u32;
let mut status = StatusLine::Hint;
let mut phase = Phase::Typing;
let mut last_left = u32::MAX;
let mut dirty = true;
let mut quit = false;
while !quit {
let now = clock.now();
let elapsed = now.duration_since(started);
if elapsed >= duration {
break;
}
let secs_left = remaining_secs(duration, elapsed);
if dirty || secs_left != last_left {
writer.clear_screen();
writer.write(&render_frame(snippet, &typed, score, secs_left, wpm_now(chars_typed, elapsed), &status, true));
let _ = writer.flush();
last_left = secs_left;
dirty = false;
}
match reader.read_key(POLL_TIMEOUT) {
None => {
if phase == Phase::Typing && now.duration_since(attempt_start) >= ATTEMPT_LIMIT {
score -= PENALTY;
status = StatusLine::Error(format!(
"Timeout −{PENALTY} points · [R]etry [S]kip"
));
phase = Phase::AwaitChoice;
dirty = true;
}
}
Some(GameKey::CtrlC) => {
quit = true;
}
Some(GameKey::Esc) if phase == Phase::Typing => {
quit = true;
}
Some(GameKey::Char(c)) if phase == Phase::AwaitChoice => {
if c.eq_ignore_ascii_case(&'r') {
typed.clear();
attempt_start = clock.now();
status = StatusLine::Hint;
phase = Phase::Typing;
dirty = true;
} else if c.eq_ignore_ascii_case(&'s') {
advance_snippet(&mut idx, &mut snippet, snippets);
typed.clear();
attempt_start = clock.now();
status = StatusLine::Hint;
phase = Phase::Typing;
dirty = true;
}
}
Some(GameKey::Enter | GameKey::Char(' ')) if phase == Phase::AwaitChoice => {
advance_snippet(&mut idx, &mut snippet, snippets);
typed.clear();
attempt_start = clock.now();
status = StatusLine::Hint;
phase = Phase::Typing;
dirty = true;
}
Some(GameKey::Char(c)) => {
typed.push(c);
chars_typed = chars_typed.saturating_add(1);
let pos = typed.chars().count() - 1;
if typed.chars().nth(pos) != snippet.chars().nth(pos) {
mistakes = mistakes.saturating_add(1);
score -= PENALTY;
}
if typed.chars().count() == snippet.chars().count() {
let attempt_elapsed = clock.now().duration_since(attempt_start);
if typed == snippet {
let under_1s = attempt_elapsed < BONUS_WINDOW;
score += score_attempt(true, under_1s);
completed = completed.saturating_add(1);
status = StatusLine::Success(format!(
"+{} points!",
score_attempt(true, under_1s)
));
advance_snippet(&mut idx, &mut snippet, snippets);
typed.clear();
attempt_start = clock.now();
phase = Phase::Typing;
} else {
status =
StatusLine::Error("Mismatch · [R]etry [S]kip".to_string());
phase = Phase::AwaitChoice;
}
dirty = true;
} else {
dirty = true;
}
}
Some(GameKey::Backspace) => {
typed.pop();
dirty = true;
}
_ => {}
}
}
let now = clock.now();
let elapsed = now.duration_since(started);
ArcadeResult {
score,
snippets_completed: completed,
mistakes,
chars_typed,
wpm: wpm_now(chars_typed, elapsed),
duration_seconds: elapsed.as_secs() as u32,
rank: None,
is_new_high_score: false,
}
}
fn advance_snippet<'a>(idx: &mut usize, snippet: &mut &'a str, snippets: &'a [String]) {
*idx = (*idx + 1) % snippets.len();
*snippet = &snippets[*idx];
}
pub fn run_typing_game() -> ArcadeResult {
let _guard = RawModeGuard::enable().ok();
let mut reader = TerminalGameKeyReader;
let mut writer = StdoutGameWriter;
let path = score_file_path();
let board = ArcadeScoreboard::load(&path);
let previous_top = board.top_score();
writer.write("⚔️ SYNTAXBREAKER\n");
writer.write(&render_scoreboard(&board));
writer.write("\nGet ready — the game starts now!\n");
let _ = writer.flush();
let snippets = fresh_snippet_order();
let mut clock = SystemGameClock;
let result = play_game(&mut reader, &mut writer, &mut clock, &snippets, GAME_DURATION);
drop(_guard);
let mut board = ArcadeScoreboard::load(&path);
let mut result = result;
result.rank = board.record(result.score);
result.is_new_high_score = is_new_high_score(result.score, previous_top);
let _ = board.save(&path);
let _ = io::stdout().write_all(CLEAR_ANSI.as_bytes());
let _ = io::stdout().write_all(render_game_over(&result, &board).as_bytes());
let _ = io::stdout().flush();
result
}
pub fn run_arcade() {
run_typing_game();
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::VecDeque;
struct TempDir(PathBuf);
impl TempDir {
fn new(prefix: &str) -> Self {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let path = std::env::temp_dir().join(format!(
"{}_arcade_{}_{}",
prefix,
std::process::id(),
nanos
));
fs::create_dir_all(&path).expect("create temp dir");
Self(path)
}
fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[derive(Debug, Clone)]
struct MockGameKeyReader {
keys: VecDeque<GameKey>,
}
impl MockGameKeyReader {
fn new(keys: Vec<GameKey>) -> Self {
Self { keys: keys.into() }
}
}
impl GameKeyReader for MockGameKeyReader {
fn read_key(&mut self, _timeout: Duration) -> Option<GameKey> {
self.keys.pop_front()
}
}
#[derive(Debug, Clone, Default)]
struct CapturingGameWriter {
output: String,
clears: usize,
}
impl GameWriter for CapturingGameWriter {
fn write(&mut self, text: &str) {
self.output.push_str(text);
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
fn clear_screen(&mut self) {
self.clears += 1;
self.output.push_str(CLEAR_ANSI);
}
}
fn keys_for(text: &str) -> Vec<GameKey> {
text.chars().map(GameKey::Char).collect()
}
fn run_game(keys: Vec<GameKey>, snippet: &str) -> (ArcadeResult, CapturingGameWriter) {
let polls = (keys.len() + 4) as u64;
run_game_until(keys, snippet, Duration::from_millis(polls * POLL_TIMEOUT.as_millis() as u64))
}
fn run_game_until(
keys: Vec<GameKey>,
snippet: &str,
duration: Duration,
) -> (ArcadeResult, CapturingGameWriter) {
let mut reader = MockGameKeyReader::new(keys);
let mut writer = CapturingGameWriter::default();
let mut clock = StepClock::new();
let snippets = vec![snippet.to_string()];
let result = play_game(&mut reader, &mut writer, &mut clock, &snippets, duration);
(result, writer)
}
#[test]
fn snippet_database_contains_all_expected_entries() {
let expected = [
"const x = 5;",
"let arr = [];",
"if (x > 0) { }",
"function hello() { }",
"for (let i = 0; i < 10; i++) { }",
"return null;",
"await fetch(\"/api\");",
"throw new Error(\"fail\");",
"Promise.all([]);",
"console.log(\"debug\");",
"[...array]",
"{ key: \"value\" }",
"x === y",
"try { } catch { }",
"export default App;",
];
for snippet in expected {
assert!(SNIPPETS.contains(&snippet), "missing {snippet:?}");
}
assert_eq!(SNIPPETS.len(), 15);
}
#[test]
fn shuffle_is_deterministic_and_permutes() {
let a = shuffled_with(42);
let b = shuffled_with(42);
let c = shuffled_with(1);
assert_eq!(a, b);
assert_ne!(a, c);
let mut sorted: Vec<String> = a.clone();
sorted.sort_unstable();
let mut stock = SNIPPETS.to_vec();
stock.sort_unstable();
assert_eq!(sorted, stock, "shuffle must not drop or add snippets");
}
#[test]
fn score_attempt_respects_rules() {
assert_eq!(score_attempt(true, true), 15, "base + bonus");
assert_eq!(score_attempt(true, false), 10, "base only");
assert_eq!(score_attempt(false, true), -2, "still wrong fast");
assert_eq!(score_attempt(false, false), -2);
}
#[test]
fn wpm_formula_counts_words_per_minute() {
assert_eq!(wpm_now(100, Duration::from_secs(60)), 20);
assert_eq!(wpm_now(60, Duration::from_secs(60)), 12);
assert_eq!(wpm_now(0, Duration::ZERO), 0);
}
#[test]
fn remaining_seconds_clamps_at_zero() {
assert_eq!(remaining_secs(Duration::from_secs(60), Duration::from_secs(45)), 15);
assert_eq!(remaining_secs(Duration::from_secs(60), Duration::from_secs(61)), 0);
}
#[test]
fn leaderboard_keeps_top_five_descending() {
let mut board = ArcadeScoreboard::default();
for score in [10, 40, 20, 50, 30] {
board.record(score);
}
assert_eq!(board.top5(), vec![50, 40, 30, 20, 10]);
assert_eq!(board.top_score(), 50);
assert_eq!(board.record(5), None);
assert_eq!(board.top5(), vec![50, 40, 30, 20, 10]);
assert_eq!(board.record(45), Some(2));
assert_eq!(board.top5(), vec![50, 45, 40, 30, 20]);
}
#[test]
fn leaderboard_round_trips_to_disk() {
let dir = TempDir::new("roundtrip");
let path = dir.path().join(SCORE_FILE);
let mut board = ArcadeScoreboard::default();
board.record(35);
board.record(99);
board.save(&path).expect("save board");
let loaded = ArcadeScoreboard::load(&path);
assert_eq!(loaded, board);
assert!(path.parent().unwrap().is_dir());
}
#[test]
fn leaderboard_load_missing_file_is_empty() {
let dir = TempDir::new("missing");
let board = ArcadeScoreboard::load(&dir.path().join("nope.json"));
assert_eq!(board.top5(), Vec::<u32>::new());
}
#[test]
fn leaderboard_normalizes_on_load() {
let dir = TempDir::new("normalize");
let path = dir.path().join(SCORE_FILE);
fs::write(&path, r#"{"scores":[3,100,7,2,9,88]}"#).unwrap();
let board = ArcadeScoreboard::load(&path);
assert_eq!(board.top5(), vec![100, 88, 9, 7, 3]);
}
#[test]
fn new_high_score_only_when_beating_previous_top() {
assert!(is_new_high_score(10, 0), "first game counts");
assert!(is_new_high_score(50, 30));
assert!(!is_new_high_score(30, 30), "ties are not new records");
assert!(!is_new_high_score(10, 30));
assert!(!is_new_high_score(-4, 3), "negative scores never win");
}
#[test]
fn frame_renders_all_layers() {
let frame = render_frame_plain(
"const x = 5;",
"const x = 5",
21,
45,
12,
&StatusLine::Hint,
);
assert!(frame.contains("⚔️ SYNTAXBREAKER ARCADE GAME"));
assert!(frame.contains("const x = 5;"));
assert!(frame.contains("Your input: const x = 5_"));
assert!(frame.contains("Score: 21 | Time: 45s | WPM: 12"));
assert!(frame.contains("Type it exactly"));
}
#[test]
fn frame_shows_error_status_with_retry_skip() {
let frame = render_frame_plain(
"const x = 5;",
"",
-2,
58,
0,
&StatusLine::Error("Mismatch · [R]etry [S]kip".into()),
);
assert!(frame.contains("✗ Mismatch · [R]etry [S]kip"));
}
#[test]
fn every_frame_line_is_exactly_box_width() {
for status in [
StatusLine::Hint,
StatusLine::Error("Mismatch".into()),
StatusLine::Success("+15 points!".into()),
] {
let frame = render_frame_plain(
"for (let i = 0; i < 10; i++) { }",
"for (let i = 0; i < 10;",
30,
30,
25,
&status,
);
for line in frame.lines() {
assert_eq!(
line.chars().count(),
ARCADE_WIDTH,
"off-width row: {line:?}"
);
}
}
}
#[test]
fn scoreboard_renders_top_scores_with_medals() {
let mut board = ArcadeScoreboard::default();
for s in [50, 40, 30, 20, 10] {
board.record(s);
}
let out = render_scoreboard(&board);
assert!(out.contains("🏆 TOP 5 SCORES"));
assert!(out.contains("1. 50"));
assert!(out.contains("5. 10"));
assert!(out.contains("🥇"));
}
#[test]
fn game_correct_snippet_scores_with_fast_bonus() {
let (result, _) = run_game(keys_for("const x = 5;"), "const x = 5;");
assert_eq!(result.score, 15, "10 base + 5 speed bonus");
assert_eq!(result.snippets_completed, 1);
assert_eq!(result.mistakes, 0);
assert_eq!(result.chars_typed, 12);
}
#[test]
fn game_wrong_character_penalizes_and_offers_skip() {
let mut keys = keys_for("qeturn null;");
keys.push(GameKey::Char('s')); let (result, writer) = run_game(keys, "return null;");
assert_eq!(result.mistakes, 1);
assert_eq!(result.score, -2, "one wrong character costs PENALTY");
assert_eq!(result.snippets_completed, 0);
assert!(writer.output.contains("[R]etry [S]kip"));
}
#[test]
fn game_retry_lets_you_fix_the_attempt() {
let mut keys = keys_for("return nullX");
keys.push(GameKey::Char('r')); keys.extend(keys_for("return null;"));
let (result, _) = run_game(keys, "return null;");
assert_eq!(result.score, -2 + 10 + 5);
assert_eq!(result.mistakes, 1, "the first mistake is still counted");
assert_eq!(result.snippets_completed, 1);
}
#[test]
fn game_timeout_penalizes_after_three_seconds() {
let (result, writer) = run_game_until(vec![], "const x = 5;", Duration::from_secs(5));
assert_eq!(result.score, -2, "single timeout penalty");
assert_eq!(result.snippets_completed, 0);
assert!(writer.output.contains("Timeout"));
}
#[test]
fn game_ctrl_c_quits_immediately() {
let (result, _) = run_game(vec![GameKey::CtrlC], "const x = 5;");
assert_eq!(result.score, 0);
assert_eq!(result.snippets_completed, 0);
assert_eq!(result.duration_seconds, 0, "quit before a full second");
}
#[test]
fn game_empty_input_completes_no_snippets() {
let (result, writer) = run_game(vec![], "const x = 5;");
assert_eq!(result.score, 0);
assert_eq!(result.snippets_completed, 0);
assert!(writer.clears > 0, "screen was cleared between frames");
}
#[test]
fn game_typed_past_speed_window_loses_bonus() {
let snippet = "x === y";
let mut keys = Vec::new();
for c in snippet.chars() {
keys.push(GameKey::Char(c));
for _ in 0..22 {
keys.push(GameKey::Unknown); }
}
let (result, _) = run_game_until(keys, snippet, Duration::from_secs(8));
assert_eq!(result.score, 10, "base points, no speed bonus");
assert_eq!(result.snippets_completed, 1);
}
#[test]
fn arcade_result_default_is_zeroed() {
let result = ArcadeResult::default();
assert_eq!(result.score, 0);
assert_eq!(result.snippets_completed, 0);
assert_eq!(result.wpm, 0);
assert_eq!(result.rank, None);
assert!(!result.is_new_high_score);
let path = score_file_path();
assert_eq!(path.parent().unwrap().to_string_lossy(), SCORE_DIR);
assert_eq!(path.file_name().unwrap(), SCORE_FILE);
}
#[test]
fn test_typing_game_scoring() {
assert_eq!(score_attempt(true, true), CORRECT_POINTS + BONUS_POINTS);
assert_eq!(score_attempt(true, false), CORRECT_POINTS);
assert_eq!(score_attempt(false, false), -PENALTY);
assert_eq!(score_attempt(false, true), -PENALTY);
assert!(is_new_high_score(10, 0), "first game counts");
assert!(is_new_high_score(30, 10));
assert!(!is_new_high_score(10, 10), "ties are not records");
assert!(!is_new_high_score(5, 30));
}
#[test]
fn test_high_score_persistence() {
use std::thread::sleep;
use std::time::Duration;
let dir = TempDir::new("named_scores");
let path = dir.path().join(SCORE_FILE);
let mut board = ArcadeScoreboard::default();
board.record(25);
board.record(80);
board.record(40);
assert_eq!(board.record(10), Some(4), "10 ranks 4th on a 3-score board");
board.save(&path).expect("save board");
let loaded = ArcadeScoreboard::load(&path);
assert_eq!(loaded, board, "round-trip must preserve the board");
assert_eq!(loaded.top5(), vec![80, 40, 25, 10]);
assert_eq!(loaded.top_score(), 80);
assert_eq!(loaded.scores.len(), 4);
sleep(Duration::from_millis(5));
loaded.save(&path).expect("save again");
assert_eq!(ArcadeScoreboard::load(&path), loaded);
}
}