Greetings, code sorcerers! On Day 10 of my #100DaysOfCode Rust saga, I summoned a magical project β a number-guessing game! π§ββοΈβ¨ Let's unravel the secrets and unveil the new spells I've learned.
The Ritual of Randomness π²
In the heart of the code incantation lies the mysterious rand crate, a tool for conjuring random numbers. The gen_range method, like a wand, whispers enchantments to summon a number between 1 and 100.
let random_number: u8 = rand::thread_rng().gen_range(1..=100); Dancing with User Input ππΊ
The mystical dance with user input begins! A loop enchants the user to guess the lucky number, showcasing the art of spellbinding user interactions.
let mut user_input = String::new(); io::stdin() .read_line(&mut user_input) .expect("Failed to read the input, please try again"); Weaving the Threads of Logic π§΅
The incantation of logic ensures that only valid guesses are considered. A match spell checks the user's input, transforming mistakes into graceful prompts.
match user_input.trim().parse() { Ok(num) if num >= 1 && num <= 100 => num, _ => { println!("Please enter a valid number between 1 and 100!"); continue; } }; Dueling with the Enigmatic Ordering π€Ί
The duel with Ordering unfolds β a mystical confrontation between user input and the elusive lucky number.
match user_input.cmp(&random_number) { Ordering::Less => println!("The lucky number is greater than you have entered!"), Ordering::Greater => println!("The lucky number is smaller than you have entered!"), Ordering::Equal => { // Victory! println!("You guessed the correct number in {} guesses", no_of_guesses); break; } } Final Code
use rand::Rng; use std::cmp::Ordering; use std::io; use std::time::Duration; fn main() { let random_number: u8 = rand::thread_rng().gen_range(1..=100); let mut no_of_guesses: u8 = 0; loop { let mut user_input = String::new(); no_of_guesses += 1; println!("Guess the lucky number between 1 and 100..."); io::stdin() .read_line(&mut user_input) .expect("Failed to read the input, please try again"); let user_input: u8 = match user_input.trim().parse() { Ok(num) if num >= 1 && num <= 100 => num, _ => { println!("Please enter a valid number between 1 and 100!"); continue; } }; match user_input.cmp(&random_number) { Ordering::Less => println!("The lucky number is greater than you have entered!"), Ordering::Greater => println!("The lucky number is smaller than you have entered!"), Ordering::Equal => { println!("The lucky number is {}", random_number); println!( "You guessed the correct number in {} guesses", no_of_guesses ); break; } } } std::thread::sleep(Duration::from_secs(2)); } A Lesson in Perpetual Learning π
As the project concludes, I reflect on the undeniable truth in the realm of coding β learning is a journey with endless paths. There are myriad ways to achieve the same result, each unveiling a new facet of the magical world of programming.
Embrace the magic, my fellow sorcerers! ππ»β¨
Top comments (0)