Advertisement
cwchen

[Rust] Secret Number game demo

Aug 22nd, 2017
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.56 KB | None | 0 0
  1. // Call rand package for random number generation
  2. extern crate rand;
  3.  
  4. use std::io;
  5. use std::io::Write;
  6. use rand::Rng;
  7.  
  8. fn main() {
  9.     // Set the limit of answer
  10.     const MAX: u32 = 100;
  11.     const MIN: u32 = 1;
  12.  
  13.     // Set the limit of user input
  14.     let mut upper = MAX;
  15.     let mut lower = MIN;
  16.  
  17.     // Get a random number between MIN and MAX
  18.     let answer = rand::thread_rng().gen_range(MIN, MAX + 1);
  19.  
  20.     loop {
  21.         // Prompt for user input
  22.         print!("Input a number ({}-{}):", lower, upper);
  23.         // Flush standard out
  24.         let _ = io::stdout().flush();
  25.  
  26.         // Receive user input
  27.         let mut input = String::new();
  28.         io::stdin()
  29.             .read_line(&mut input)
  30.             .expect("Failed to read from stdin");
  31.  
  32.         // Parse integer
  33.         let guess = match input.trim().parse::<u32>() {
  34.             Ok(n) => n,
  35.             Err(_) => {
  36.                 println!("Not a valid number");
  37.                 continue;
  38.             }
  39.         };
  40.  
  41.         // Check the range of the guess
  42.         if guess < lower || guess > upper {
  43.             println!("The number should be between {} and {}",
  44.                      lower, upper);
  45.             continue;
  46.         }
  47.  
  48.         // Check whether the guess is correct
  49.         if guess == answer {
  50.             println!("You got it!");
  51.             break;
  52.         } else if guess > answer {
  53.             println!("Too large");
  54.             upper = guess;
  55.         } else {  // guess < answer
  56.             println!("Too small");
  57.             lower = guess;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement