hangman done

This commit is contained in:
ridethepig 2023-02-19 13:07:18 +00:00
parent 3e7544fd6b
commit 6291739e3f

View File

@ -35,6 +35,66 @@ fn main() {
let secret_word_chars: Vec<char> = secret_word.chars().collect(); let secret_word_chars: Vec<char> = secret_word.chars().collect();
// Uncomment for debugging: // Uncomment for debugging:
// println!("random word: {}", secret_word); // println!("random word: {}", secret_word);
let mut guess_count = NUM_INCORRECT_GUESSES;
let mut right_count = 0;
let mut display_str: Vec<char> = Vec::new();
let mut guessed_chars = Vec::new();
let mut found;
for _ in 0..secret_word.len() {
display_str.push('-');
}
println!("Welcome to CS110L Hangman!");
loop {
println!(
"The word so fat is {}",
display_str.iter().collect::<String>()
);
println!(
"You have guessed the following letters: {}",
guessed_chars.iter().collect::<String>()
);
println!("You have {} guesses left", guess_count);
print!("Please guess a letter: ");
io::stdout().flush().expect("Error flushing stdout");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Error readline");
let guess = guess.trim();
if guess.len() != 1 {
println!(
"Invalid input \"{}\", only one letter is acceptable!",
guess
);
continue;
}
found = false;
let guess = guess.chars().nth(0).unwrap();
guessed_chars.push(guess);
for i in 0..secret_word_chars.len() {
if secret_word_chars[i] == guess && display_str[i] == '-' {
display_str[i] = guess;
found = true;
right_count += 1;
break;
}
}
if !found {
guess_count -= 1;
println!("Sorry, that letter is not in the word");
}
print!("\n");
if guess_count == 0 {
println!("Sorry, you ran out of guesses!");
break;
}
if right_count == secret_word_chars.len() {
println!(
"Congratulations you guessed the secret word: {}!",
secret_word
);
break;
}
}
// Your code here! :) // Your code here! :)
} }