Created
January 2, 2013 22:08
-
-
Save steveklabnik/4438728 to your computer and use it in GitHub Desktop.
A guessing game in Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use io::{Reader,ReaderUtil}; | |
| use core::rand::{Rng}; | |
| use core::int::abs; | |
| fn generate_secret_number() -> int { | |
| abs(Rng().gen_int() % 100) + 1 | |
| } | |
| fn process_guess(secret:int, guess: int, guesses: &mut int) { | |
| io::println(fmt!("You guessed: %d", guess)); | |
| if guess > secret { | |
| io::println("Your guess was too high!"); | |
| } | |
| else if guess < secret { | |
| io::println("Your guess was too low!"); | |
| } | |
| else if guess == secret { | |
| io::println("You got it!"); | |
| *guesses = 4; // this will end up ending the game. | |
| } | |
| *guesses += 1; | |
| } | |
| fn main() { | |
| let secret = generate_secret_number(); | |
| let guesses = @mut 1; | |
| io::println("--- N U M B E R - G A M E ---"); | |
| io::println(""); | |
| io::println("Guess a number from 1-100 (you get five tries):"); | |
| loop { | |
| io::println(fmt!("Guess #%d", *guesses)); | |
| let in = io::stdin().read_line(); | |
| match int::from_str(in) { | |
| Some(number) => process_guess(secret, number, guesses), | |
| None => io::println("Hey, put in a number.") | |
| } | |
| if *guesses == 5 { break; } | |
| } | |
| io::println("Done!"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment