DEV Community

Cover image for Day 10: Rustic Riddles - Unleashing the Number Guessing Game ๐ŸŽฒ
Aniket Botre
Aniket Botre

Posted on

Day 10: Rustic Riddles - Unleashing the Number Guessing Game ๐ŸŽฒ

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);
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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;
    }
};
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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! ๐Ÿš€๐Ÿ’ปโœจ

RustLang #ProgrammingMagic #LearningIsEndless #CodeWizardry #Day10

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs