본문 바로가기
프로그래밍/Rust

Rust로 up down 게임 작성해 보기

by 체리 2022. 5. 8.
반응형

rust를 배우고자 처음 작성해본 코드

생각보다 어렵지만 생각보다 쉬움?

 

code block에 rust가 없네 ㅠㅠㅠㅠㅠㅠㅠ

use std::io::{self, Write, BufRead};
use rand::Rng;

fn selected_number() -> u32 {
    let mut num_string = String::new();
    std::io::stdin()
        .lock()
        .read_line(&mut num_string)
        .expect("error");
    let num: u32 = num_string.trim().parse().unwrap();
    num
}

fn main() {
    let max_try_count: u32 = 10;

    println!("Up & down: up to 2 digits");
    println!("You can try {} times to guess the number", max_try_count);

    let picked_number: u32 = rand::thread_rng().gen_range(1, 99);
    println!("I picked a number.\n");

    for count in 1..max_try_count {
        print!("{:2}: Input your number: ", count);
        let _ = io::stdout().flush();
        let selected_number: u32 = selected_number();

        if selected_number == picked_number {
            println!("=> Right!");
            break;
        }
        else if selected_number > picked_number {
            println!("=> Down!");
        }
        else {
            println!("=> Up!");
        }

        if count == max_try_count {
            println!("=> You've tried {} times. The number I picked is {}", max_try_count, selected_number);
            break;
        }
    }
}

 

 

 

반응형

'프로그래밍 > Rust' 카테고리의 다른 글

Rust로 up down 게임 작성해 보기  (0) 2022.05.08

댓글0