title: Rust-01-猜数字游戏
date: 2024/04/08
tags:

  • Rust
    categories:
  • 笔记

猜数字游戏

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

/**
 * The main function of the program.
 * It starts the game by printing a welcome message, generating a secret number, and then entering a loop where it prompts the user to guess the number.
 * It continues to loop until the user guesses the correct number.
 */
fn main() {
    println!("Guess the number!");

    /**
     * Generates a secret number between 1 and 100 (inclusive) using the `rand::thread_rng().gen_range(1..101)` function.
     * This number will be the target that the user will try to guess.
     */
    let secret_number = rand::thread_rng().gen_range(1..101);

    /**
     * The main game loop. It will continue to run until the user guesses the correct number.
     */
    loop {
        println!("Enter your guess: ");

        /**
         * Reads a line of input from the user.
         * If the input cannot be read, the program will panic with the message "Failed to read line".
         */
        let mut guess = String::new();
        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        /**
         * Parses the user's input into a u32 integer.
         * If the input cannot be parsed, the program will skip the current iteration of the loop and continue to the next one.
         */
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        /**
         * Compares the user's guess with the secret number.
         * If the guess is less than the secret number, it prints "Too small!".
         * If the guess is greater than the secret number, it prints "Too big!".
         * If the guess is equal to the secret number, it prints "You got it!" and breaks out of the loop.
         */
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You got it!");
                break;
            }
        }
    }
}
文章作者: Billy
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 billy blog
笔记 Rust
喜欢就支持一下吧