1use colored::Colorize;
28use std::fs;
29use std::io::{self, Write};
30use std::path::PathBuf;
31use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
32
33pub const GAME_DURATION: Duration = Duration::from_secs(60);
39
40pub const ATTEMPT_LIMIT: Duration = Duration::from_secs(3);
42
43pub const BONUS_WINDOW: Duration = Duration::from_secs(1);
45
46pub const CORRECT_POINTS: i32 = 10;
48
49pub const BONUS_POINTS: i32 = 5;
51
52pub const PENALTY: i32 = 2;
54
55pub const POLL_TIMEOUT: Duration = Duration::from_millis(50);
57
58pub const MAX_SCORES: usize = 5;
60
61pub const SCORE_DIR: &str = ".limitless";
63
64pub const SCORE_FILE: &str = "arcade_scores.json";
66
67pub const ARCADE_WIDTH: usize = 60;
74
75const INNER_WIDTH: usize = ARCADE_WIDTH - 4;
77
78pub 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
110pub struct ArcadeResult {
111 pub score: i32,
113 pub snippets_completed: u32,
115 pub mistakes: u32,
117 pub chars_typed: u32,
119 pub wpm: u32,
121 pub duration_seconds: u32,
123 pub rank: Option<usize>,
125 pub is_new_high_score: bool,
127}
128
129pub 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
152fn 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
158fn remaining_secs(duration: Duration, elapsed: Duration) -> u32 {
160 duration.saturating_sub(elapsed).as_secs() as u32
161}
162
163mod shuffle {
164 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
189pub 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
210fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum GameKey {
226 Char(char),
228 Enter,
230 Backspace,
232 Esc,
234 CtrlC,
236 Unknown,
238}
239
240pub trait GameKeyReader {
242 fn read_key(&mut self, timeout: Duration) -> Option<GameKey>;
245}
246
247pub 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
264fn 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
284pub trait GameWriter {
286 fn write(&mut self, text: &str);
288 fn flush(&mut self) -> io::Result<()>;
290 fn clear_screen(&mut self);
292}
293
294const CLEAR_ANSI: &str = "\x1b[2J\x1b[H";
296
297pub 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
314pub trait GameClock {
316 fn now(&mut self) -> Instant;
318}
319
320pub struct SystemGameClock;
322
323impl GameClock for SystemGameClock {
324 fn now(&mut self) -> Instant {
325 Instant::now()
326 }
327}
328
329#[derive(Debug, Clone)]
332pub struct StepClock {
333 t: Instant,
334}
335
336impl StepClock {
337 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
356struct 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#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum StatusLine {
379 Hint,
381 Error(String),
383 Success(String),
385}
386
387#[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
406pub 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
463pub 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
495fn 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#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
597pub struct ArcadeScoreboard {
598 pub scores: Vec<u32>,
600}
601
602impl ArcadeScoreboard {
603 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 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 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 pub fn top_score(&self) -> u32 {
634 self.scores.first().copied().unwrap_or(0)
635 }
636
637 pub fn top5(&self) -> Vec<u32> {
639 self.scores[..self.scores.len().min(MAX_SCORES)].to_vec()
640 }
641
642 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
652pub fn is_new_high_score(score: i32, previous_top: u32) -> bool {
655 score.max(0) as u32 > previous_top
656}
657
658pub fn score_file_path() -> PathBuf {
660 PathBuf::from(SCORE_DIR).join(SCORE_FILE)
661}
662
663fn 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
817pub 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
857pub fn run_arcade() {
859 run_typing_game();
860}
861
862#[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 #[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 #[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 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 assert_eq!(wpm_now(100, Duration::from_secs(60)), 20);
1015 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 assert_eq!(board.record(5), None);
1036 assert_eq!(board.top5(), vec![50, 40, 30, 20, 10]);
1037 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 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 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 let mut keys = keys_for("qeturn null;");
1163 keys.push(GameKey::Char('s')); 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 let mut keys = keys_for("return nullX");
1177 keys.push(GameKey::Char('r')); keys.extend(keys_for("return null;"));
1179 let (result, _) = run_game(keys, "return null;");
1180
1181 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 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 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); }
1224 }
1225 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 #[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 sleep(Duration::from_millis(5));
1279 loaded.save(&path).expect("save again");
1280 assert_eq!(ArcadeScoreboard::load(&path), loaded);
1281 }
1282}