Programming a Guessing Game - Using RUST
https://www.google.com/imgres?imgurl=https%3A%2F%2Fgames4esl.com%2Fwp-content%2Fuploads%2FGuessing-Game-Pic-full.png&imgrefurl=https%3A%2F%2Fgames4esl.com%2Fguessing-games-for-kids%2F&tbnid=NkPwHnvlg_Y_TM&vet=12ahUKEwjCz92ZodH8AhWmndgFHZKGB5EQMygBegU

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.

#rust #RustADay #rustlang

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

No alt text provided for this image

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

  1. use std::io; > The IO library is used for receiving standard input and output operations. It comes as part of the std library
  2. fn main() > This is the entry point function
  3. println! > prints a string onto the screen
  4. let mut guess = String::new(); > Let is used for variable declaration. In RUST variables are immutable by default. The mut keyword makes the variable mutable. String::new() creates a new instance of an empty string and binds it to the variable
  5. io::stdin().read_line(&mut guess) > The io library extends to use
  6. stdin() to get user input. The read_line($mut guess) will read users' input and pass it into the mutable variable. The & indicates this argument is a reference. This enables multiple calls without having to copy data. This will help reduce redundancy.
  7. .expect("Failed to read line"); > This is to handle exceptions , in case :)
  8. The read_line() or for the fact any function call will return a callback. This callback result is either ok or an error. The expect() method is an instance of this result and can be used to handle exceptions when the result turns out to err. Without the except() the build issues a warning during the compilation

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.

No alt text provided for this image

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}" );


}

        

  • use rand::Rng; > This brings the Rng library into the scope
  • let secret_number = rand::thread_rng().gen_range(1, 101); > the thread_rng() is a function where the scope is restricted to this thread. The gen_range() generated a random number.

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}");


}

        

  • use std::cmp::Ordering; > This is used for performing the comparison. The different results are equal, lesser and greater.
  • match guess.cmp(&secret_number) > match will compare the outcome of the cmp with the Ordering and emits the result. guess.cmp(&secret_number) is used to compare the two numbers.

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;
            }
        }
    }
}        

  • The loop{} will run infinitely for anything that's within it.
  • The typecasting of the input has been handled with an ok() and err()
  • We can break this loop anywhere. Here we are breaking the loop when the user wins the game.

This concludes this mini-project.

要查看或添加评论,请登录

Raj Arun的更多文章

  • Immutable Variables vs Constant in RUST

    Immutable Variables vs Constant in RUST

    Variables are immutable in Rust and so are constants. If so, why do we have them both and what is the purpose? Let's…

    1 条评论
  • Rust's Build & Package Manager - Cargo

    Rust's Build & Package Manager - Cargo

    #RustADay Cargo is Rust build and package manager If Rust is all installed and up without any issues, you can check for…

  • The traits of a leader are not inborn but built

    The traits of a leader are not inborn but built

    Frame of reference Over the years, I have constantly observed how a family member is introduced to our visitors. I have…

社区洞察

其他会员也浏览了