Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate rand;
- use rand::{thread_rng, Rng};
- use rand::rngs::ThreadRng;
- use std::io::{self, Write};
- use std::time::{Duration, Instant};
- struct Question {
- query: String,
- answer: String,
- }
- impl Question {
- fn new(rng: &mut ThreadRng) -> Self {
- let x = rng.gen_range(1, 12);
- let y = rng.gen_range(1, 12);
- let query = format!("What is {} x {}?", x, y);
- // no need to parse user guess and handle non-integer input
- // if we just compare two strings for equality.
- let answer = (x * y).to_string();
- return Question {
- query,
- answer,
- }
- }
- }
- fn main() {
- let time_limit = Duration::from_secs(30);
- let mut score = 0;
- let mut rng = thread_rng();
- println!("Speedy Multiplication Quiz!");
- println!("Try to answer as many questions as you can in 30 seconds.");
- let instant = Instant::now();
- while instant.elapsed() <= time_limit {
- let question = Question::new(&mut rng);
- print!("{}\n> ", question.query);
- // flush output stream - needed to ensure output emitted immediately
- io::stdout().flush().unwrap();
- let mut guess = String::new();
- io::stdin().read_line(&mut guess)
- .expect("Failed to read line");
- guess.pop(); // get rid of trailing newline character
- if guess == question.answer {
- println!("Correct!");
- score += 1;
- } else {
- println!("Sorry, it was actually {}!", question.answer);
- }
- }
- println!("Bzzzt! Times up!");
- println!("Congratulations, you got a score of {}!", score);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement