Advertisement
3th1ca14aX0r

Python Hangman

Jun 17th, 2024 (edited)
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | Source Code | 0 0
  1. import random
  2. import string
  3.  
  4. def get_valid_word(words):
  5.     """
  6.    Returns a valid word from the provided list of words.
  7.    Ensures the word has no spaces or hyphens and converts it to uppercase.
  8.    """
  9.     word = random.choice(words)
  10.     while '-' in word or ' ' in word:
  11.         word = random.choice(words)
  12.     return word.upper()
  13.  
  14. def hangman():
  15.     """
  16.    The main function for the Hangman game.
  17.    """
  18.     words = ["python", "javascript", "computer", "programming", "algorithm",
  19.              "hangman", "challenge", "development", "random", "function"]
  20.     word = get_valid_word(words)
  21.     word_letters = set(word)  # Letters in the word to be guessed
  22.     alphabet = set(string.ascii_uppercase)  # Set of uppercase English letters
  23.     used_letters = set()  # Set of letters guessed by the user
  24.  
  25.     lives = 6
  26.  
  27.     # Main game loop
  28.     while len(word_letters) > 0 and lives > 0:
  29.         print(f"\nYou have {lives} lives left and you have used these letters: ", ' '.join(sorted(used_letters)))
  30.  
  31.         # Display the current state of the word
  32.         word_list = [letter if letter in used_letters else '-' for letter in word]
  33.         print("Current word: ", ' '.join(word_list))
  34.  
  35.         # Get user input
  36.         user_letter = input("Guess a letter: ").upper()
  37.         if len(user_letter) != 1 or user_letter not in alphabet:
  38.             print("Invalid input. Please enter a single alphabet character.")
  39.             continue
  40.  
  41.         if user_letter in used_letters:
  42.             print("You have already used that character. Please try again.")
  43.             continue
  44.  
  45.         # Process valid guess
  46.         used_letters.add(user_letter)
  47.         if user_letter in word_letters:
  48.             word_letters.remove(user_letter)
  49.             print("Good guess!")
  50.         else:
  51.             lives -= 1
  52.             print("Letter is not in the word.")
  53.  
  54.     # End of the game
  55.     if lives == 0:
  56.         print(f"\nYou died. The word was {word}.")
  57.     else:
  58.         print(f"\nCongratulations! You guessed the word {word}!")
  59.  
  60. if __name__ == "__main__":
  61.     hangman()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement