Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created January 2, 2013 22:08
Show Gist options
  • Select an option

  • Save steveklabnik/4438728 to your computer and use it in GitHub Desktop.

Select an option

Save steveklabnik/4438728 to your computer and use it in GitHub Desktop.
A guessing game in Rust.
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