aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 6fbd3e0ecb02725cfeb2f71628379b8f693e47a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Import necessary crates
use crossterm::{
    event::{self, KeyCode, KeyEvent},
    terminal::{disable_raw_mode, enable_raw_mode},
};
use rand::Rng;
use std::{
    fs,
    io::{self},
    path::Path,
    sync::{Arc, Mutex},
    time::Instant,
};
use tui::{
    backend::{Backend, CrosstermBackend},
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Span, Spans},
    widgets::Paragraph,
    Frame, Terminal,
};

// Define the possible states of the application
#[derive(Debug, Clone, Copy, PartialEq)]
enum State {
    MainMenu,
    TypingGame,
    EndScreen,
}

// Struct to hold the application state
struct App {
    time_taken: u64,
    input_string: String,
    timer: Option<Instant>,
    state: State,
    should_exit: bool,
    sentences: Vec<String>,
    current_sentence_index: usize,
}

impl App {
    // Constructor to create a new instance of the application
    fn new() -> Result<Self, io::Error> {
        let sentences = read_sentences("sentences.txt")?;
        let current_sentence_index = rand::thread_rng().gen_range(0..sentences.len());
        let app = App {
            time_taken: 0,
            input_string: String::new(),
            timer: None,
            state: State::MainMenu,
            should_exit: false,
            sentences,
            current_sentence_index,
        };
        Ok(app)
    }

    // Reset the game to its initial state
    fn reset(&mut self) {
        let current_sentence_index = rand::thread_rng().gen_range(0..self.sentences.len());
        self.current_sentence_index = current_sentence_index;
        self.time_taken = 0;
        self.input_string.clear();
        self.timer = None;
        self.state = State::TypingGame;
    }

    // Get the current sentence the user needs to type
    fn current_sentence(&self) -> &str {
        if let Some(sentence) = self.sentences.get(self.current_sentence_index) {
            sentence
        } else {
            "No sentence available"
        }
    }

    // Start the timer
    fn start_timer(&mut self) {
        if self.timer.is_none() {
            self.timer = Some(Instant::now());
        }
    }

    // Update the timer
    fn update_timer(&mut self) {
        if let Some(timer) = self.timer {
            self.time_taken = timer.elapsed().as_secs();
        }
    }

    // Calculate and return the current typing speed (Words Per Minute)
    fn update_wpm(&self) -> f64 {
        let time_elapsed = self.time_taken as f64;
        if time_elapsed == 0.0 {
            0.0
        } else {
            let wpm = (self.input_string.split_whitespace().count() as f64) / (time_elapsed / 60.0);
            if wpm.is_nan() {
                0.0
            } else {
                wpm
            }
        }
    }
}

// Function to read sentences from a file
fn read_sentences(filename: &str) -> Result<Vec<String>, io::Error> {
    if !Path::new(filename).exists() {
        return Err(io::Error::new(io::ErrorKind::NotFound, "File not found"));
    }

    let contents = fs::read_to_string(filename)?;
    let sentences: Vec<String> = contents.lines().map(|s| s.to_string()).collect();
    Ok(sentences)
}

// Function to draw the typing game UI
fn draw_typing_game(f: &mut Frame<CrosstermBackend<std::io::Stdout>>, chunk: Rect, app: &mut App) {
    let wpm = app.update_wpm();
    let time_used = app.time_taken as f64;

    let mut colored_text: Vec<Span> = Vec::new();

    // Iterate over each character in the current sentence and color it based on user input
    for (index, c) in app.current_sentence().chars().enumerate() {
        let color = if let Some(input_char) = app.input_string.chars().nth(index) {
            if c == input_char {
                Color::Green
            } else {
                Color::Red
            }
        } else {
            Color::Gray
        };

        let span = Span::styled(c.to_string(), Style::default().fg(color));
        colored_text.push(span);
    }

    // Create text to be displayed
    let text = vec![
        Spans::from(Span::styled(
            "Type the following sentence:",
            Style::default().add_modifier(Modifier::BOLD),
        )),
        colored_text.into(),
        Spans::from(Span::styled(format!("WPM: {:.2}", wpm), Style::default())),
        Spans::from(Span::styled(
            format!("Time: {:.1} seconds", time_used),
            Style::default(),
        )),
    ];

    // Render the widget
    f.render_widget(Paragraph::new(text).alignment(Alignment::Center), chunk);

    app.update_timer();
}

// Function to handle user input events
async fn input_handler(event: KeyEvent, app: &mut App, _event_tx: Arc<Mutex<()>>) {
    match event.code {
        KeyCode::Char(c) => {
            if app.timer.is_none() {
                app.timer = Some(Instant::now());
            }
            app.input_string.push(c);
        }
        KeyCode::Backspace => {
            app.input_string.pop();
        }
        KeyCode::Esc => {
            app.should_exit = true;
        }
        KeyCode::Enter => match app.state {
            State::MainMenu => {
                app.state = State::TypingGame;
                app.start_timer();
                app.input_string.clear();
            }
            State::TypingGame => {
                if app.input_string.trim() == app.current_sentence().trim() {
                    app.state = State::EndScreen;
                    app.update_timer();
                }
            }
            State::EndScreen => {
                app.reset();
            }
        },
        _ => {}
    }
}

// Include test module
#[cfg(test)]
mod test;

#[tokio::main]
async fn main() -> Result<(), io::Error> {
    // Enable raw mode for terminal input
    enable_raw_mode()?;

    // Print current working directory
    println!("Current working directory: {:?}", std::env::current_dir());

    // Create a new instance of the App
    let mut app = App::new().unwrap();

    // Initialize the terminal backend
    let stdout = io::stdout();
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Clear the terminal and hide the cursor
    terminal.clear()?;
    terminal.hide_cursor()?;

    // Main event loop
    loop {
        // Get the terminal size
        if let Ok(size) = terminal.backend().size() {
            // Define layout for the UI
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .margin(2)
                .constraints([
                    Constraint::Min(3),
                    Constraint::Percentage(70),
                    Constraint::Min(3),
                ])
                .split(size);

            // Draw UI based on app state
            terminal.draw(|f| match app.state {
                State::MainMenu => {
                    let main_menu = vec![
                        Spans::from(Span::styled("Welcome to typerpunk!", Style::default())),
                        Spans::from(Span::styled("Press Enter to Start", Style::default())),
                        Spans::from(Span::styled("Press Esc to Quit", Style::default())),
                    ];
                    f.render_widget(
                        Paragraph::new(main_menu).alignment(Alignment::Center),
                        chunks[0],
                    );
                }
                State::TypingGame => {
                    draw_typing_game(f, chunks[1], &mut app);
                }
                State::EndScreen => {
                    let wpm = app.update_wpm();
                    let time_taken = app.time_taken as f64;
                    let end_screen = vec![
                        Spans::from(Span::styled("Game Over!", Style::default())),
                        Spans::from(Span::styled(
                            format!("Words Per Minute: {:.2}", wpm),
                            Style::default(),
                        )),
                        Spans::from(Span::styled(
                            format!("Time Taken: {:.1} seconds", time_taken),
                            Style::default(),
                        )),
                        Spans::from(Span::styled("Press Enter to Play Again", Style::default())),
                        Spans::from(Span::styled("Press Esc to Quit", Style::default())),
                    ];
                    f.render_widget(
                        Paragraph::new(end_screen).alignment(Alignment::Center),
                        chunks[1],
                    );
                }
            })?;

            // Handle input events
            if let event::Event::Key(event) = event::read()? {
                input_handler(event, &mut app, Arc::new(Mutex::new(()))).await;
            }

            // Check if the app should exit
            if app.should_exit {
                break;
            }
        }
    }

    // Cleanup: Show cursor, disable raw mode, and clear only the game UI
    terminal.show_cursor()?;
    disable_raw_mode()?;
    let size = terminal.backend().size().unwrap();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(2)
        .constraints([
            Constraint::Min(3),
            Constraint::Percentage(70),
            Constraint::Min(3),
        ])
        .split(size);
    terminal
        .draw(|f| f.render_widget(Paragraph::new("").alignment(Alignment::Center), chunks[1]))?;

    // Manually clear the terminal before exiting
    println!("\x1B[2J\x1B[1;1H");

    Ok(())
}