반응형

Rust, 숫자 퀴즈 

 

글. 수알치 오상문 

 

참조: https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html

 

소스 코드는 참조에 나오는 코드를 약간 수정했습니다. 전체 진행 사항을 참조 글을 살펴보세요. 

 

 

cargo new guessing_game

cd guessing_game

 

 

[ Cargo.toml 파일 내용 ]

[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"

[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"

 

[ main.rs 소스 코드 내용 ]

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

fn main() {
    println!("Guess the number!");
    let answer = rand::thread_rng().gen_range(1..=100);
    let mut chance = 5;  // 도전 기회

    loop {
        println!("Please input your guess.");
        let mut guess = String::new();

        // io::stdin().read_line(&mut guess).expect("Failed to read line");
        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        // let guess: u32 = guess.trim().parse().expect("Please type a number!");
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };      
        println!("You guessed: {}", guess);
        chance -= 1;

        /*
        if answer == guess {
            println!("That's correct!");
        } else {
            println!("Wrong answer!");
        }
        */ 
        match guess.cmp(&answer) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
        if chance < 1 {
            println!("Failed!!!");
            break;
        }
    }
}

 

 

[실행 결과]

C:\project_rust\guessing_game>cargo run
   Compiling guessing_game v0.1.0 (C:\project_rust\guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 0.56s
     Running `target\debug\guessing_game.exe`
Guess the number!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
50
You guessed: 50
Too small!
Failed!!!

반응형

+ Recent posts