8000 feat: death mode (-d) — end the test on the first mistake by hindriix · Pull Request #28 · jrnxf/thokr · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ Options:
language to pull words from [default: english] [possible values: english, english1k, english10k]
--pace <PACE>
ghost caret pacing at this WPM to race against
-d, --death-mode
end the test the moment you mistype a character
-h, --help
Print help
-V, --version
Expand All @@ -77,6 +79,7 @@ Options:
| `thokr -p "$(cat foo.txt)"` | custom prompt with the output of `cat foo.txt` |
| `thokr -f 4` | 4 grammatical sentences with full stops; overrides word settings |
| `thokr --pace 60` | 15 most common words with a ghost caret racing at 60 wpm |
| `thokr -d` | 15 words, but the test ends the instant you mistype a character |

_During a test you can press ← to start over or → to see a new prompt (assuming
you didn't supply a custom one)_
Expand Down
8 changes: 8 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ struct Cli {
/// ghost caret pacing at this WPM to race against
#[arg(long)]
pace: Option<u16>,

/// end the test the moment you mistype a character
#[arg(short = 'd', long = "death-mode")]
death_mode: bool,
}

struct App {
Expand Down Expand Up @@ -90,6 +94,7 @@ impl App {
let number_of_secs = cli.number_of_secs.map(|secs| secs as f64);
let mut thok = Thok::new(prompt, word_count, number_of_secs);
thok.pace_wpm = cli.pace.map(f64::from);
thok.death_mode = cli.death_mode;
thok
}

Expand Down Expand Up @@ -139,6 +144,9 @@ impl App {
fn save_if_finished(&mut self) {
if self.thok.has_finished() {
self.thok.calc_results();
if self.thok.died() {
return;
}
if let Err(error) = history::append(&self.thok) {
self.save_error.get_or_insert(error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
source: src/ui.rs
expression: "draw(&died_in_death_mode(\"the quick brx\"), 80, 24)"
---








💀

expected 'o', pressed 'x'

the quick brown fox jumps over the lazy dog

2 words, 12 chars, 2.5s






(r)etry / (n)ew / (esc)ape



................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
.......................................a........................................
................................................................................
............................bbbbbbbbbbbbbbbbbbbbbbbbb...........................
................................................................................
...................ccccccccccddeffgggggggggggggggggggggggggggg..................
................................................................................
.............................ggggggggggggggggggggggg............................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
.....hhhhhhhhhhhhhhhhhhhhhhhhhh.................................................
................................................................................
................................................................................

a = fg Red, BOLD
b = fg Reset, BOLD
c = fg Green, BOLD
d = fg Green, BOLD | UNDERLINED
e = fg Red, BOLD | UNDERLINED | REVERSED
f = fg Reset, BOLD | DIM | UNDERLINED
g = fg Reset, BOLD | DIM
h = fg Reset, ITALIC
cursor = None
52 changes: 51 additions & 1 deletion src/thok.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub struct Thok {
pub accuracy: f64,
pub std_dev: f64,
pub pace_wpm: Option<f64>,
/// End the test the instant an incorrect character is typed.
pub death_mode: bool,
ticks: u32,
}

Expand All @@ -54,6 +56,7 @@ impl Thok {
std_dev: 0.0,
pace_wpm: None,
ticks: 0,
death_mode: false,
}
}

Expand Down Expand Up @@ -178,9 +181,16 @@ impl Thok {
}

pub fn has_finished(&self) -> bool {
self.input.len() == self.char_count()
self.died()
|| self.input.len() == self.char_count()
|| self.seconds_remaining.is_some_and(|secs| secs <= 0.0)
}

/// Death mode ends the test on the first mistake, ahead of the usual
/// length and timer rules. A run that ends this way is not a result.
pub fn died(&self) -> bool {
self.death_mode && self.input.iter().any(|i| i.outcome == Outcome::Incorrect)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -260,6 +270,46 @@ mod tests {
assert!(thok.has_finished());
}

#[test]
fn death_mode_finishes_on_first_mistake() {
let mut thok = Thok::new("hello world".to_string(), 2, None);
thok.death_mode = true;
thok.write('h');
thok.write('e');
assert!(!thok.has_finished(), "correct typing keeps the test alive");
thok.write('x'); // expected 'l'
assert!(thok.has_finished(), "a mistake ends a death-mode test");
}

#[test]
fn died_only_after_a_mistake_in_death_mode() {
let mut thok = Thok::new("hello".to_string(), 1, None);
thok.death_mode = true;
thok.write('h');
assert!(!thok.died());
thok.write('x');
assert!(thok.died());

let mut off = Thok::new("hello".to_string(), 1, None);
off.write('x');
assert!(!off.died(), "a mistake only kills a death-mode test");
}

#[test]
fn death_mode_off_tolerates_mistakes() {
let mut thok = Thok::new("hello".to_string(), 1, None);
thok.write('x');
assert!(!thok.has_finished());
}

#[test]
fn death_mode_beats_a_running_timer() {
let mut thok = Thok::new("hello".to_string(), 1, Some(10.0));
thok.death_mode = true;
thok.write('x');
assert!(thok.has_finished());
}

#[test]
fn calc_results_accuracy() {
let mut thok = Thok::typed("hello", "hellx", None, &[100, 300, 500, 700, 900]);
Expand Down
166 changes: 164 additions & 2 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::thok::{Outcome, Thok};
use ratatui::{
Frame,
buffer::Buffer,
layout::{Alignment, Constraint, Layout, Position, Rect},
layout::{Alignment, Constraint, Flex, Layout, Position, Rect},
style::{Color, Modifier, Style},
symbols::Marker,
text::{Line, Span},
Expand All @@ -17,6 +17,11 @@ use std::ops::Range;
const HORIZONTAL_MARGIN: u16 = 5;
const VERTICAL_MARGIN: u16 = 2;

/// Most prompt lines the death screen shows, around the line it ended on, and
/// how many of them come before it.
const DEATH_VISIBLE_LINES: usize = 3;
const DEATH_LEAD: usize = 1;

const BOLD: Style = Style::new().add_modifier(Modifier::BOLD);
const CORRECT: Style = BOLD.fg(Color::Green);
const INCORRECT: Style = BOLD.fg(Color::Red);
Expand All @@ -33,7 +38,10 @@ pub fn draw(frame: &mut Frame, thok: &Thok) {

/// Returns where the cursor belongs; the results screen has none.
fn render(thok: &Thok, area: Rect, buf: &mut Buffer) -> Option<Position> {
if thok.has_finished() {
if thok.died() {
render_death(thok, area, buf);
None
} else if thok.has_finished() {
render_results(thok, area, buf);
None
} else {
Expand Down Expand Up @@ -374,6 +382,125 @@ fn render_results(thok: &Thok, area: Rect, buf: &mut Buffer) {
.render(legend_area, buf);
}

/// The screen after a death-mode run ends on a mistake: what went wrong,
/// the prompt around it and how far the run got.
fn render_death(thok: &Thok, area: Rect, buf: &mut Buffer) {
// the run ends on its first mistake, so that is the last key
let dead_at = thok.input.len().saturating_sub(1);
let expected = thok.prompt_chars[dead_at];
let pressed = thok.input[dead_at].char;

let max_chars_per_line = area.width.saturating_sub(HORIZONTAL_MARGIN * 2).max(1);
let wrapped = layout::wrap_chars(&thok.prompt_chars, max_chars_per_line);
let death_line = layout::char_cell(&wrapped, dead_at).map_or(0, |(line_no, _)| line_no);
let shown = wrapped.len().min(DEATH_VISIBLE_LINES);
let first = death_line
.saturating_sub(DEATH_LEAD)
.min(wrapped.len() - shown);
let lines = &wrapped[first..first + shown];

// the word that was being typed, spaces excluded
let word_start = thok.prompt_chars[..dead_at]
.iter()
.rposition(|&c| c == ' ')
.map_or(0, |i| i + 1);
let word_end = thok.prompt_chars[dead_at..]
.iter()
.position(|&c| c == ' ')
.map_or(thok.prompt_chars.len(), |i| dead_at + i);

let text: Vec<Line> = lines
.iter()
.map(|line| {
let mut spans: Vec<Span> = Vec::new();
for idx in line.clone() {
let char = thok.prompt_chars[idx];
let style = if idx == dead_at {
INCORRECT.add_modifier(Modifier::REVERSED)
} else if idx < dead_at {
CORRECT
} else {
UNTYPED
};
let style = if (word_start..word_end).contains(&idx) {
style.add_modifier(Modifier::UNDERLINED)
} else {
style
};
match spans.last_mut() {
Some(span) if span.style == style => span.content.to_mut().push(char),
_ => spans.push(Span::styled(String::from(char), style)),
}
}
Line::from(spans)
})
.collect();

let words = thok.prompt_chars[..word_start]
.iter()
.filter(|&&c| c == ' ')
.count();
// the block is centred on the screen, the key hints sit bottom left as
// on the results screen
let [content_area, legend_area] = Layout::vertical([Constraint::Min(0), Constraint::Length(1)])
.horizontal_margin(HORIZONTAL_MARGIN)
.vertical_margin(VERTICAL_MARGIN)
.areas(area);
let [title_area, _, what_area, _, prompt_area, _, stats_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(text.len() as u16),
Constraint::Length(1),
Constraint::Length(1),
])
.flex(Flex::Center)
.areas(content_area);

let centered = Alignment::Center;
Paragraph::new(Span::styled("\u{1F480}", INCORRECT))
.alignment(centered)
.render(title_area, buf);
Paragraph::new(Span::styled(
format!(
"expected {}, pressed {}",
show_key(expected),
show_key(pressed)
),
BOLD,
))
.alignment(centered)
.render(what_area, buf);
Paragraph::new(text)
.alignment(centered)
.render(prompt_area, buf);
let word_count = if words == 1 { "word" } else { "words" };
Paragraph::new(Span::styled(
format!(
"{words} {word_count}, {dead_at} chars, {:.1}s",
thok.elapsed_secs
),
UNTYPED,
))
.alignment(centered)
.render(stats_area, buf);
Paragraph::new(Span::styled(
"(r)etry / (n)ew / (esc)ape",
Style::new().add_modifier(Modifier::ITALIC),
))
.render(legend_area, buf);
}

/// A key as the death screen names it: a space would be invisible.
fn show_key(c: char) -> String {
if c == ' ' {
"space".to_string()
} else {
format!("'{c}'")
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -934,4 +1061,39 @@ mod tests {
let thok = Thok::new(String::new(), 0, None);
insta::assert_snapshot!(draw(&thok, 80, 24));
}

fn died_in_death_mode(typed: &str) -> Thok {
let mut thok = Thok::typed(PROMPT, typed, None, &[]);
thok.death_mode = true;
thok.elapsed_secs = 2.5;
thok
}

#[test]
fn death_screen_after_a_mistake_in_death_mode() {
insta::assert_snapshot!(draw(&died_in_death_mode("the quick brx"), 80, 24));
}

#[test]
fn death_screen_names_a_mistyped_space() {
let screen = screen_text(&buffer(&died_in_death_mode("the quick brown foxx"), 80, 24));
assert!(screen.contains("\u{1F480}"));
assert!(screen.contains("expected space, pressed 'x'"));
}

#[test]
fn a_clean_death_mode_run_gets_the_normal_results_screen() {
let mut thok = Thok::typed(PROMPT, PROMPT, None, &[]);
thok.death_mode = true;
let screen = screen_text(&buffer(&thok, 80, 24));
assert!(!screen.contains("\u{1F480}"));
assert!(screen.contains("wpm"));
}

#[test]
fn a_mistake_outside_death_mode_gets_the_normal_results_screen() {
let thok = Thok::typed(PROMPT, PROMPT.replacen('q', "x", 1).as_str(), None, &[]);
let screen = screen_text(&buffer(&thok, 80, 24));
assert!(!screen.contains("\u{1F480}"));
}
}
Loading
Loading
0