Logo

dev-resources.site

for different kinds of informations.

Day 10: Rustic Riddles - Unleashing the Number Guessing Game 🎲

Published at
1/10/2024
Categories
rust
learning
100daysofcode
self
Author
aniket_botre
Categories
4 categories in total
rust
open
learning
open
100daysofcode
open
self
open
Author
12 person written this
aniket_botre
open
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

self Article's
30 articles in total
Favicon
Self hosted supabase setup with Authelia and Caddy
Favicon
Microsoft Certification Courses
Favicon
Hello World!
Favicon
Embracing Self-Care: Your Path to Wellness
Favicon
self, Self, and Self.self in Swift
Favicon
Day 14: Rust's Symphony of Generics and Traits – Crafting Code for the Real World 🌐🚀
Favicon
Day 13: Rust Enums – Unleashing the Power of Variants! 💪🦀
Favicon
Day 12: Navigating the Rustic Terrain of Struct Methods 🏞️
Favicon
Day 10: Rustic Riddles - Unleashing the Number Guessing Game 🎲
Favicon
Day 7: Unleashing Functions in Rust 🚀
Favicon
Day 5: Mastering Rust's Conditionals and Match Expressions
Favicon
Mindful Practices that help me get out of my own head and my way
Favicon
What Weightlifting Has Taught Me About Systems Engineering
Favicon
The Mindset Shift that Transform My Long-Term Outlook
Favicon
Embracing the Power of Being Second
Favicon
The 9-to-5 Scholar: Completing MIT OCW CSE with a Full time Job
Favicon
2022 retro, and what's up
Favicon
Find Prime Number in C++
Favicon
Top 6 Sites para Encontrar, Gerar, Criar e Compartilhar Memes
Favicon
Day-2 of Machine Learning
Favicon
The worst piece of life advice I ever received
Favicon
Como saber e validar o dígito verificador do RG (Registro Geral)
Favicon
Como descobrir qual a espécie de planta por foto?
Favicon
Orientação a objetos baseada em protótipos parte 2
Favicon
Top ways to become a self taught developer
Favicon
Why Polywork?
Favicon
Become a better front-end developer
Favicon
"Sophie's World in Ruby"
Favicon
Melhores Sites para Encontrar Estágios do Brasil
Favicon
Melhores Sites de Emprego do Brasil

Featured ones: