From dd3d78153609e56cf633a430559346d78e48132c Mon Sep 17 00:00:00 2001 From: sgoudham Date: Tue, 11 Jan 2022 00:37:02 +0000 Subject: [PATCH] Add guessing game --- guessing_game/Cargo.toml | 9 +++++++++ guessing_game/src/main.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 guessing_game/Cargo.toml create mode 100644 guessing_game/src/main.rs diff --git a/guessing_game/Cargo.toml b/guessing_game/Cargo.toml new file mode 100644 index 0000000..cc63f6f --- /dev/null +++ b/guessing_game/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.8.3" diff --git a/guessing_game/src/main.rs b/guessing_game/src/main.rs new file mode 100644 index 0000000..250a8fe --- /dev/null +++ b/guessing_game/src/main.rs @@ -0,0 +1,35 @@ +use std::cmp::Ordering; +use std::io; +use rand::Rng; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1..101); + + loop { + println!("Please input your guess:"); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue + }; + + println!("You guessed -> {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +}