Advertisement
Guest User

Untitled

a guest
Aug 27th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.67 KB | None | 0 0
  1. extern crate rand;
  2. use rand::{thread_rng, Rng};
  3. use rand::rngs::ThreadRng;
  4.  
  5. use std::io::{self, Write};
  6. use std::time::{Duration, Instant};
  7.  
  8. struct Question {
  9.     query: String,
  10.     answer: String,
  11. }
  12.  
  13. impl Question {
  14.     fn new(rng: &mut ThreadRng) -> Self {
  15.         let x = rng.gen_range(1, 12);
  16.         let y = rng.gen_range(1, 12);
  17.  
  18.         let query = format!("What is {} x {}?", x, y);
  19.         // no need to parse user guess and handle non-integer input
  20.         // if we just compare two strings for equality.
  21.         let answer = (x * y).to_string();
  22.  
  23.         return Question {
  24.             query,
  25.             answer,
  26.         }
  27.     }
  28. }
  29.  
  30. fn main() {
  31.     let time_limit = Duration::from_secs(30);
  32.     let mut score = 0;
  33.     let mut rng = thread_rng();
  34.  
  35.     println!("Speedy Multiplication Quiz!");
  36.     println!("Try to answer as many questions as you can in 30 seconds.");
  37.  
  38.     let instant = Instant::now();
  39.     while instant.elapsed() <= time_limit {
  40.         let question = Question::new(&mut rng);
  41.         print!("{}\n> ", question.query);
  42.         // flush output stream - needed to ensure output emitted immediately
  43.         io::stdout().flush().unwrap();
  44.  
  45.         let mut guess = String::new();
  46.         io::stdin().read_line(&mut guess)
  47.             .expect("Failed to read line");
  48.         guess.pop(); // get rid of trailing newline character
  49.  
  50.         if guess == question.answer {
  51.             println!("Correct!");
  52.             score += 1;
  53.         } else {
  54.             println!("Sorry, it was actually {}!", question.answer);
  55.         }
  56.     }
  57.     println!("Bzzzt! Times up!");
  58.     println!("Congratulations, you got a score of {}!", score);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement