Skip to content

Instantly share code, notes, and snippets.

@kosayoda
Created September 14, 2019 05:28
Show Gist options
  • Save kosayoda/4bbf7288e3513dd94cfd162109816d5c to your computer and use it in GitHub Desktop.
Save kosayoda/4bbf7288e3513dd94cfd162109816d5c to your computer and use it in GitHub Desktop.
Yell at this please
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