Let’s create a simple word guessing game in Python. Below are a couple of examples you can follow:
- Word Guessing Game using Random Module:
import random def initialize_game(): words = ['Donkey', 'Aeroplane', 'America', 'Program', 'Python', 'language', 'Cricket', 'Football', 'Hockey', 'Spaceship', 'bus', 'flight'] return random.choice(words) def make_a_guess(correct_word): guesses = '' turns = 10 while turns > 0: failed = 0 for char in correct_word: if char in guesses: print(char, end=' ') else: print('_', end=' ') failed += 1 if failed == 0: print("\nCongratulations! You've guessed the correct word:", correct_word) break guess = input("\nEnter your guess: ") guesses += guess turns -= 1 if turns == 0: print("\nSorry, you're out of turns. The correct word was:", correct_word) if __name__ == "__main__": player_name = input("What is your name? ") print(f"Best of luck, {player_name}!") random_word = initialize_game() print("\nPlease guess the characters:") make_a_guess(random_word)
- Word Guessing Game with a Predefined Word List:
def word_guessing_game(): words = ["lemon", "mango", "banana", "apple"] player_name = input("Enter your name: ") print(f"Hi {player_name}, let's start the game!\n") print("*** Word Guessing Game ***\n") random_word = random.choice(words) guessed_letters = set() attempts = 5 while attempts > 0: display_word = ''.join([char if char in guessed_letters else '_' for char in random_word]) print(f"Word: {display_word}") guess = input("Guess a letter: ").lower() if len(guess) != 1 or not guess.isalpha(): print("Please enter a single letter.") continue guessed_letters.add(guess) if guess in random_word: print("Correct guess!") else: print("Incorrect guess!") attempts -= 1 if set(random_word) == guessed_letters: print(f"Congratulations, {player_name}! You've guessed the word: {random_word}") break if attempts == 0: print(f"Sorry, {player_name}, you're out of attempts. The word was: {random_word}") if __name__ == "__main__": word_guessing_game()
Written by: Piyush Patil
Feel free to choose the one that suits your preference and have fun playing the word guessing game! 😊