Simple Hangman game in Python
Below is a simple implementation of the Hangman game in Python. This code assumes a console-based interaction.
import random WORDS = ["python", "java", "hangman", "programming", "computer"] MAX_TRIES = 6 def main(): secret_word = get_random_word() guessed_letters = ['\0'] * len(secret_word) tries = 0 while True: display_hangman(tries) display_guessed_word(guessed_letters) print("Enter a letter: ") guess = input().lower() if is_letter_already_guessed(guess, guessed_letters): print("You've already guessed that letter. Try again.") continue if guess in secret_word: update_guessed_letters(secret_word, guessed_letters, guess) else: tries += 1 if is_word_guessed(guessed_letters): print(f"Congratulations! You guessed the word: {secret_word}") break if tries == MAX_TRIES: display_hangman(MAX_TRIES) print(f"Sorry, you ran out of tries. The correct word was: {secret_word}") break def get_random_word(): return random.choice(WORDS) def display_hangman(tries): # Add hangman drawing logic based on the number of tries # You can customize the ASCII art for the hangman as needed. def display_guessed_word(guessed_letters): print("Current word:", end=" ") for letter in guessed_letters: if letter == '\0': print("_", end=" ") else: print(letter, end=" ") print() def is_letter_already_guessed(guess, guessed_letters): return guess in guessed_letters def update_guessed_letters(secret_word, guessed_letters, guess): for i, letter in enumerate(secret_word): if letter == guess: guessed_letters[i] = guess def is_word_guessed(guessed_letters): return '\0' not in guessed_letters if __name__ == "__main__": main()