DEV Community

Cover image for Tutorial: Random Number - Guessing Game in Rust 🦀🔢
Eleftheria Batsou
Eleftheria Batsou

Posted on • Originally published at eleftheriabatsou.hashnode.dev on

Tutorial: Random Number - Guessing Game in Rust 🦀🔢

Hello everyone and welcome back to my blog. Today I will show you how to code a "Number guessing game" using Rust.

By the end of this tutorial, you'll not only have a fun challenging game but also:

  • You'll learn how to generate random numbers for user-guessing

  • You'll learn the basics like loops and input in Rust

Don't forget you can find all the code on my GitHub profile, there will be a link for this project at the end of this article.

Image description

Code the Game

Open your favorite code editor, type in the terminal cargo new your-project-name and let's start!

Firstly, we need to import the standard library for input use std::io::stdin;, as we will need the user to input a number. Then, inside the main() we're going to create a loop and we'll name it: outer_loop , this is going to be a looping structure. Let's also declare a variable: let _number: u32 = 10; with a value of 10. This is the value that the user should guess. Finally, we're asking the user to pick a number: println!("Pick a number (1 to 15) >>>");

Note: You may be thinking that this is a random number guessing game but we just gave _number a static number... Wait for it! We'll change it to a random number in a bit 🤓.

So far we have:

fn main() {

    '_outer_loop: loop {

        let _number: u32 = 10;

        println!("Pick a number (1 to 15) >>>");
    }
Enter fullscreen mode Exit fullscreen mode

But, as we mentioned above, it'd be more interesting to generate a random number. So the user will guess a new number each time they run our game.

Let's continue coding...

After showing the message Pick a number (1 to 15) >>> we need to store the user's number. So, we're going to have another loop and declare a new mutable variable that's going to contain the new empty string. We also want to pass a reference where we're going to store the string, and that's why we've imported it above the standard input library. The standard input is going to read the line .

        let mut line = String::new();
        let _input = stdin().read_line(&mut line); 
Enter fullscreen mode Exit fullscreen mode

Time to define our guess. 😊

let guess: Option = input.ok().mapor(None, || line.trim().parse().ok());

In the above line of code, the ok() means that the reader is at the end of the line of the input the user entered. After this we have mapor: this is going to return the default value or apply functions to a value.

So we're going to take the line and we're going to trim it and parse that string in order to be an integer value (line.trim().parse().ok() ) so we can compare between the user's guess and the predefined number so the data types can be compatible for comparison.

Now, we can continue with matching the _guess. (And this is why needed the Option.)

match _guess{
            None => println!("enter a number..."),
            Some(n) if n == _number => {
                println!("Bravo! You guessed it!");
                break '_outer_loop;
            }
            .
            .
            .
        }
Enter fullscreen mode Exit fullscreen mode
  • If the input is None, we're going to print a line that says enter a number, and if some number is entered, then we're going to compare between the user's input and the number that's predefined (which is still 10, but wait for it...).

  • If the user guessed the correct number, then we're going to print a line that says Bravo, you guessed it!. And we're going to break out of the loop. That's why we defined above the _outer_loop.

  • If the user's input is less than the number that's predefined, we're going to print Too low, and if it's higher, we're going to print Too high and if anything else, we're going to throw an error and the loop will continue.

            Some(n) if n < _number => println!("Too low"),
            Some(n) if n > _number => println!("Too high"),
            Some(_) => println!("Error!")
Enter fullscreen mode Exit fullscreen mode

You can now run the program with cargo run but every time you play the game the _number will be 10. Let's fix that. 👇

Random Number Generator

The first thing we need is to import the random range dependency. We'll need to go to cargo.toml and include this rand = "0.8.3" in [dependencies].

[dependencies]
rand = "0.8.3"
Enter fullscreen mode Exit fullscreen mode

And in main.rs we'll include use rand::Rng;

Now, instead of having this predefined number 10, we're going to create a dynamic one.

// let _number: u32 = 10;
let _number: i32 = rand::thread_rng().gen_range(1..=15)
Enter fullscreen mode Exit fullscreen mode

This _number will be of integer 32 instead of unassigned 32. Note: If you have defined your variable i32, then you will need to define the Option also i32, and vice versa. Now this integer has access to thread_rng inside the random package that gen_range from 1 to 15.

Let's run the program...

Run It

Use cargo run to run the program.

Conclusion

That was our simple rust game. Feel free to experiment with rand, integer and unsigned numbers.

Check the code here.

Random Number - Guessing Game in Rust

This is a fun little game in rust. The program generates a random number from 1 to 15 and the user tries to guess it. The program gives it hints if the user's input is too low or too high. The user can play as many times as they want.

randomgenrrator

Run it with cargo run

Tutorial | Show your love on X/Twitter here | Credits and original idea here.






Happy Rust Coding! 🤞🦀


👋 Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

🥰 If you liked this article, consider sharing it.

🔗 All links | X | LinkedIn

Top comments (0)