Programming a Guessing Game - Using RUST
A simple guess-the-number game. The online book of RUST (https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html) recommends it.
The program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit
Setting up a new project
We use $cargo new <project_name> to create a new project
Lets's not get the code in
use std::io
fn main() {
? ? println!("Welcome! guess the number ...");
? ? println!("Please input your guess.");
? ? let mut guess = String::new();
? ? io::stdin()
? ? ? ? .read_line(&mut guess)
? ? ? ? .expect("Failed to read line");
? ?
? ? println!("You guessed: {guess}" );
}
Explanation
Let's test this!
(base) ?? guessing_game git:(master) ? cargo run
? ?Compiling guessing_game v0.1.0 (/mnt/c/workspace/RUST/guessing_game)
? ? Finished dev [unoptimized + debuginfo] target(s) in 6.57s
? ? ?Running `target/debug/guessing_game`
Welcome! guess the number ...
Please input your guess.
10
You guessed: 10
Looks good. Now let's generate a random secret number. This is done via a RUST dependency called Crate. Crate stores all source code of RUST for other programs to use and has to be explicitly included as a dependency in the Cargo.toml file.
This file can be found under the project folder.
Update the file to include the dependency
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
Trigger the build to include the dependencies
?? guessing_game git:(master) ? cargo run
? ?Compiling guessing_game v0.1.0 (/mnt/c/workspace/RUST/guessing_game)
? ? Finished dev [unoptimized + debuginfo] target(s) in 6.57s
? ? ?Running `target/debug/guessing_game`
Welcome! guess the number ...
Please input your guess.
? Downloaded libc v0.2.139
? Downloaded getrandom v0.2.8
? Downloaded cfg-if v1.0.0
? Downloaded 7 crates (824.7 KB) in 1.72s
? ?Compiling libc v0.2.139
? ?Compiling cfg-if v1.0.0
? ?Compiling ppv-lite86 v0.2.17
? ?Compiling getrandom v0.2.8
? ?Compiling rand_core v0.6.4
? ?Compiling rand_chacha v0.3.1
? ?Compiling rand v0.8.5
? ?Compiling guessing_game v0.1.0 (/mnt/c/workspace/RUST/guessing_game)
? ? Finished dev [unoptimized + debuginfo] target(s) in 58.48sn
You would have noticed a Cargo.lock file by now. This ensures the packages and dependencies for this project are freezers for reproducibility. This also helps during code versioning.
Now lets include them into the function
use std::io;
use rand::Rng;
fn main() {
? ? let secret_number = rand::thread_rng().gen_range(1..=100);
? ? println!("Welcome! guess the number ...");
? ? println!("Please input your guess.");
? ? let mut guess = String::new();
? ? println!("The secret number is: {secret_number}");
? ? io::stdin()
? ? ? ? .read_line(&mut guess)
? ? ? ? .expect("Failed to read line");
? ?
? ? println!("You guessed: {guess}" );
}
The code gets a bit more interesting now
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
? ? let secret_number = rand::thread_rng().gen_range(1..=100);
? ? println!("Welcome! guess the number ...");
? ? println!("Please input your guess.");
? ? let mut guess = String::new();
? ?
? ? io::stdin()
? ? ? ? .read_line(&mut guess)
? ? ? ? .expect("Failed to read line");
? ?
? ? println!("You guessed: {guess}" );
? ? let guess: u32 = guess.trim().parse().expect("Please type a number!");
? ? match guess.cmp(&secret_number) {
? ? ? ? Ordering::Less => println!("Too small!"),
? ? ? ? Ordering::Greater => println!("Too big!"),
? ? ? ? Ordering::Equal => println!("You win!"),
? ? }
? ? // println!("The secret number is: {secret_number}");
}
Let's compile and test the execution
(base) ?? guessing_game git:(master) ? cargo run
? ?Compiling guessing_game v0.1.0 (/mnt/c/workspace/RUST/guessing_game)
? ? Finished dev [unoptimized + debuginfo] target(s) in 12.57s
? ? ?Running `target/debug/guessing_game`
Welcome! guess the number ...
Please input your guess.
78
You guessed: 78
Too big!
Also, note that we initially received the input from the user as a string. RUST will not be able to compare a string to an integer. Hence we have typecasted the string to int
let guess: u32 = guess.trim().parse().expect("Please type a number!");
Here is the final piece of the code with some additions
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}