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.
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) >>>");
}
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);
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;
}
.
.
.
}
If the input is
None
, we're going to print a line that saysenter 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 still10
, 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 tobreak
out of theloop
. 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 printToo low
, and if it's higher, we're going to printToo 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!")
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"
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)
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.
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.
Top comments (0)