Rust Programming: Start with This Simple Number Guessing Game Tutorial

Rust

Rust Programming Introduction: Getting Started

Rust is a systems programming language that has been gaining a lot of traction due to its performance, safety, and concurrency capabilities. Despite being a systems language, Rust can be very approachable for beginners. In this tutorial, we’ll walk through the process of building a simple command-line number guessing game in Rust. This guide is perfect for those who are just starting out with Rust and want to understand some of its basic concepts.

What We Will Build in Rust Programming

We will build a simple game where the computer randomly generates a secret number between 1 and 100, and the player has to guess it. The program will provide feedback on whether the guess is too low, too high, or correct. The game will continue until the player guesses the correct number.

Prerequisites

Before you start, ensure you have the following:

  • Rust Installed: If you haven’t installed Rust yet, you can do so by following the instructions on the official Rust website. You’ll be using cargo, Rust’s package manager, to manage and run your projects.

Step 1: Setting Up Your Rust Programming Environment

  1. Install Rust:
  • Rust can be installed via rustup, a command-line tool for managing Rust versions and associated tools.
  • On Unix-based systems (Linux, macOS), run the following command in your terminal: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  • On Windows, download and run the rustup-init.exe file.
  • Follow the on-screen instructions to complete the installation.
  1. Verify the Installation:
  • To ensure Rust is installed correctly, run: rustc --version
  • You should see the version number of Rust that is installed.

Step 2: Creating a New Rust Project

Now that Rust is installed, let’s create a new project.

  1. Create a New Project:
  • Use the cargo command to create a new project: cargo new guessing_game cd guessing_game
  • This command creates a new directory named guessing_game with a Cargo.toml file and a src directory containing a main.rs file.
  1. Open the Project:
  • Open the guessing_game directory in your favorite text editor or IDE. The main.rs file is where we’ll write our code.

Step 3: Writing the Number Guessing Game

Let’s dive into the code. Below is the complete code for the number guessing game:

The Code

extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1..101);
    println!("The secret number is {}", secret_number);
    loop{
    println!("Please input your guess.");
    let mut guess = String::new(); // this is a mutable variable which can be changed
    let my_number: i8 = 10; // this can not change value of this variable, or it will be an error
    io::stdin().read_line(&mut guess).expect("Failed to read line"); // this line is to read user input
    let guess : u8 = match guess.trim().parse(){
        Ok(num) => {num},
        Err(_) => continue,
    };
    println!("My Number is {}", my_number); // this line is to print my number
    println!("You guessed {}", guess); // this line is to print user input
    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        },
    }
    if guess == secret_number {
        println!("You win from if Condition!");
    }
    else {
        println!("You lose!");
    }
    }

}

Explanation

  1. Imports:
    • extern crate rand; brings in the external rand crate, which is used to generate random numbers.
    • use std::io; brings in the I/O (input/output) module from the standard library, which we will use to handle user input.
    • use std::cmp::Ordering; is used for comparing values.
    • use rand::Rng; allows us to use the random number generation capabilities provided by the rand crate.
  2. Main Function:
    • We start by printing a welcome message to the console with println!("Guess the number!");.
    • The secret number is generated using rand::thread_rng().gen_range(1..101);, which produces a random number between 1 and 100.
    • We then enter an infinite loop with loop {} to continually prompt the user for input until they guess correctly.
    • Inside the loop:
      • let mut guess = String::new(); creates a mutable string that will hold the user’s guess.
      • io::stdin().read_line(&mut guess).expect("Failed to read line"); reads the user’s input from the standard input and stores it in the guess variable.
      • let guess : u8 = match guess.trim().parse(){...}; converts the input string into a number, handling any errors that might occur if the input isn’t a valid number.
      • We then compare the user’s guess with the secret number using match guess.cmp(&secret_number), printing appropriate messages depending on whether the guess was too low, too high, or correct.
      • If the guess is correct, we break out of the loop, ending the game.
  3. Comments:
    • Throughout the code, comments explain what each part does. These comments are essential for beginners to understand the purpose of each line and block of code.

Step 4: Running Your Program

Once you’ve written the code, it’s time to run your game.

  1. Run the Game:
  • In your terminal, make sure you’re in your project directory and simply type: cargo run
  • This will compile and run your Rust program. You’ll see the message “Guess the number!” printed in your terminal.
  1. Interact with the Game:
  • Enter a guess when prompted. The program will tell you whether your guess is too low, too high, or correct.
  • The game will continue until you guess the correct number, at which point it will congratulate you and end.

Conclusion

Congratulations! You’ve successfully created a simple number guessing game in Rust. Through this tutorial, you’ve learned how to set up a Rust environment, write and run a Rust program, and use basic Rust constructs like loops, conditionals, and input/output handling.

This project is a great introduction to Rust’s syntax and capabilities. As you continue your journey with Rust, you’ll discover more advanced features and tools that make Rust a powerful language for systems programming, web development, and beyond.

Don’t stop here—keep experimenting with Rust by adding more features to this game or exploring other projects. Happy coding!

Rust programming, number guessing game, Rust tutorial, beginner Rust project, command-line game, Rust basics, coding game tutorial

Recommended Posts

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *

fourteen + twelve =