Created
September 14, 2019 05:28
-
-
Save kosayoda/4bbf7288e3513dd94cfd162109816d5c to your computer and use it in GitHub Desktop.
Yell at this please
This file contains 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 std::io; | |
use std::iter; | |
use std::collections::BTreeSet; | |
use rand::seq::SliceRandom; | |
use rand::thread_rng; | |
static WORDS: &'static str = include_str!("wordlist.txt"); | |
fn format_display_string(secret: &str, guess_chars: &BTreeSet<char>) -> String { | |
let mut display_string: String = String::new(); | |
for letter in secret.chars() { | |
let c: char = if guess_chars.contains(&letter) { | |
letter | |
} else { | |
'_' | |
}; | |
display_string.push(c); | |
} | |
display_string.extend(iter::repeat('_').take(secret.len() - display_string.len())); | |
display_string | |
} | |
fn get_char() -> char { | |
let mut input: String = String::new(); | |
let guess: char; | |
loop { | |
println!("Enter a single character:"); | |
io::stdin() | |
.read_line(&mut input) | |
.expect("Failed to get input"); | |
if input.trim().chars().count() != 1 { | |
input.clear(); | |
continue; | |
}; | |
guess = input.chars().next().unwrap(); | |
break; | |
} | |
guess | |
} | |
fn main() { | |
let mut lives: i32 = 10; | |
let mut win: bool = false; | |
let words = WORDS.split_whitespace().collect::<Vec<&str>>(); | |
let secret: &str = words.choose(&mut thread_rng()).unwrap(); | |
let secret_chars: BTreeSet<char> = secret.chars().collect(); | |
let mut guess: char; | |
let mut guess_chars: BTreeSet<char> = BTreeSet::new(); | |
println!("Welcome to Hangman!"); | |
while lives > 0 { | |
let display_string: String = format_display_string(&secret, &guess_chars); | |
if display_string == secret { | |
win = true; | |
break; | |
}; | |
println!("\nYou have {} lives left.", lives); | |
println!("Word: {}", display_string); | |
println!( | |
"Guessed characters: {}", | |
guess_chars.iter().collect::<String>() | |
); | |
guess = get_char(); | |
if guess_chars.contains(&guess) { | |
continue; | |
} else { | |
guess_chars.insert(guess); | |
}; | |
if !secret_chars.contains(&guess) { | |
lives -= 1; | |
}; | |
} | |
if win { | |
println!( | |
"\nYou win! The word was {}. You had {} lives remaining.", | |
secret, lives | |
); | |
} else { | |
println!("You lose! The word was {}", secret) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment