Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import string
- def get_valid_word(words):
- """
- Returns a valid word from the provided list of words.
- Ensures the word has no spaces or hyphens and converts it to uppercase.
- """
- word = random.choice(words)
- while '-' in word or ' ' in word:
- word = random.choice(words)
- return word.upper()
- def hangman():
- """
- The main function for the Hangman game.
- """
- words = ["python", "javascript", "computer", "programming", "algorithm",
- "hangman", "challenge", "development", "random", "function"]
- word = get_valid_word(words)
- word_letters = set(word) # Letters in the word to be guessed
- alphabet = set(string.ascii_uppercase) # Set of uppercase English letters
- used_letters = set() # Set of letters guessed by the user
- lives = 6
- # Main game loop
- while len(word_letters) > 0 and lives > 0:
- print(f"\nYou have {lives} lives left and you have used these letters: ", ' '.join(sorted(used_letters)))
- # Display the current state of the word
- word_list = [letter if letter in used_letters else '-' for letter in word]
- print("Current word: ", ' '.join(word_list))
- # Get user input
- user_letter = input("Guess a letter: ").upper()
- if len(user_letter) != 1 or user_letter not in alphabet:
- print("Invalid input. Please enter a single alphabet character.")
- continue
- if user_letter in used_letters:
- print("You have already used that character. Please try again.")
- continue
- # Process valid guess
- used_letters.add(user_letter)
- if user_letter in word_letters:
- word_letters.remove(user_letter)
- print("Good guess!")
- else:
- lives -= 1
- print("Letter is not in the word.")
- # End of the game
- if lives == 0:
- print(f"\nYou died. The word was {word}.")
- else:
- print(f"\nCongratulations! You guessed the word {word}!")
- if __name__ == "__main__":
- hangman()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement