Created
December 2, 2022 22:17
-
-
Save paul-hansen/f472e5d69339ebb9e0652c713928e7ff to your computer and use it in GitHub Desktop.
Hangman rust game written by ChatGPT
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
/// Everthing below this comment block was generated by ChatGPT from the prompt: | |
/// "write a hangman game in the rust language without comments" | |
/// (with comments it was too long and cut off the end) | |
use std::collections::HashSet; | |
use std::io; | |
const MAX_GUESSES: i32 = 6; | |
fn main() { | |
println!("Enter a word for the other player to guess: "); | |
let mut word = String::new(); | |
io::stdin() | |
.read_line(&mut word) | |
.expect("Failed to read word"); | |
word = word.trim().to_string(); | |
let unique_letters: HashSet<char> = word.chars().collect(); | |
let mut hidden_word = String::new(); | |
for _ in 0..word.len() { | |
hidden_word.push('_'); | |
} | |
let mut guessed_letters = String::new(); | |
let mut remaining_guesses = MAX_GUESSES; | |
let mut game_over = false; | |
while !game_over { | |
println!("Current word: {}", hidden_word); | |
println!("Remaining guesses: {}", remaining_guesses); | |
println!("Enter a letter: "); | |
let mut letter = String::new(); | |
io::stdin() | |
.read_line(&mut letter) | |
.expect("Failed to read letter"); | |
letter = letter.trim().to_string(); | |
if guessed_letters.contains(&letter) { | |
println!("You have already guessed that letter. Please try again."); | |
continue; | |
} | |
guessed_letters.push_str(&letter); | |
if word.contains(&letter) { | |
for (i, c) in word.char_indices() { | |
if c == letter.chars().next().unwrap() { | |
hidden_word.remove(i); | |
hidden_word.insert(i, c); | |
} | |
} | |
} else { | |
remaining_guesses -= 1; | |
} | |
if remaining_guesses == 0 { | |
game_over = true; | |
println!("You have run out of guesses. The word was: {}", word); | |
} else if hidden_word == word { | |
game_over = true; | |
println!( | |
"Congratulations! You have successfully guessed the word: {}", | |
word | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment