Tiny Project: Guessing Game
Pick a number, any number
Creating a simple guessing game is a great way to dive into user interaction and randomness in Rust. It’s an engaging way to practice loops, conditionals, and explore Rust’s standard library and external crates.
Problem Statement
Learning to handle user inputs and incorporate randomness can be an intimidating task for new Rustaceans. But by breaking it down, it’s entirely manageable and quite rewarding.
Solution
Use Rust's `std::io` for handling input and the `rand` crate for generating random numbers. These components will help us build a guessing game where the user tries to guess a randomly chosen number within a range.
Example Code
Here's a complete example of a simple guessing game:
use std::io;
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
println!("Guess the number!");
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,
};
if guess == secret_number {
println!("You guessed it!");
break;
} else if guess < secret_number {
println!("Too small!");
} else {
println!("Too big!");
}
}
}
1. Handling User Input: We use `std::io::stdin` to read a line of input from the user. This is fundamental for Rust programs that require user interaction.
2. Random Number Generation: The `rand` crate provides functionality to generate random numbers. Here, we use `rand::thread_rng().gen_range(1..101)` to generate a secret number between 1 and 100.
3. Control Flow with Loops: The `loop` keyword creates an infinite loop, which runs until we explicitly break out of it. In our case, this continues until the user guesses the secret number correctly.
4. Pattern Matching: The `match` statement is used for error handling when parsing user input. If the input is not a valid number, the program continues with the next iteration of the loop.
5. Comparisons: Simple conditional checks (`if`, `else if`, and `else`) to compare the guessed number with the secret number, providing feedback to the user.
Extending the Game
To add more depth, consider implementing a scoring system or limiting the number of guesses to increase the challenge. Here’s a version with limited guesses and a scoring system:
use std::io;
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
let max_attempts = 5;
let mut attempts = 0;
println!("Guess the number! You have {} attempts.", max_attempts);
loop {
if attempts >= max_attempts {
println!("You've run out of attempts! The number was {}.", secret_number);
break;
}
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,
};
attempts += 1;
if guess == secret_number {
println!("You guessed it in {} attempts!", attempts);
break;
} else if guess < secret_number {
println!("Too small!");
} else {
println!("Too big!");
}
println!("You have {} attempts left.", max_attempts - attempts);
}
}
In this version, we added:
- A maximum number of attempts (`max_attempts`).
- A counter (`attempts`) to track the number of tries.
By expanding the game, we make it more challenging and introduce elements such as state management and flow control, which are crucial concepts in programming.
This simple yet fun project serves as a fantastic way to get comfortable with Rust’s fundamentals, leaving you more prepared to tackle complex challenges in the future.


