
147 views
Python Program for Word Guessing Game
Creating a word guessing game in Python can be a fun project. In this game, the player tries to guess a randomly selected word letter by letter. You can use a list of words and the random
module to select a word for the player to guess. Here’s a simple example of a word guessing game:
import random
# List of words for the game
word_list = ["apple", "banana", "cherry", "grape", "orange", "strawberry"]
# Choose a random word from the list
word_to_guess = random.choice(word_list)
# Initialize variables
guessed_letters = []
attempts = 6 # Number of allowed attempts
# Display initial message
print("Welcome to the Word Guessing Game!")
print(f"The word contains {len(word_to_guess)} letters.")
# Main game loop
while attempts > 0:
# Display the word with guessed letters and underscores
display_word = ""
for letter in word_to_guess:
if letter in guessed_letters:
display_word += letter
else:
display_word += "_"
print(f"Word: {display_word}")
print(f"Attempts left: {attempts}")
# Ask the player for a letter guess
guess = input("Guess a letter: ").lower()
# Check if the guess is a single letter
if len(guess) != 1 or not guess.isalpha():
print("Please enter a single letter.")
continue
# Check if the letter has already been guessed
if guess in guessed_letters:
print("You've already guessed that letter.")
continue
# Add the letter to the list of guessed letters
guessed_letters.append(guess)
# Check if the guess is correct
if guess in word_to_guess:
print("Correct guess!")
else:
print("Incorrect guess.")
attempts -= 1
# Check if the player has guessed all letters
if set(word_to_guess).issubset(set(guessed_letters)):
print("Congratulations! You've guessed the word:", word_to_guess)
break
# End of the game
if attempts == 0:
print("Out of attempts. The word was:", word_to_guess)
In this code:
- We start by defining a list of words from which the game selects a random word.
- The game initializes variables such as
guessed_letters
(to keep track of guessed letters) andattempts
(the number of allowed attempts). - The main game loop continues until the player either guesses the word or runs out of attempts.
- The player is prompted to guess a letter, and the program checks if the guess is valid.
- If the guess is correct, the program updates the displayed word with the guessed letters.
- If the guess is incorrect, the player loses an attempt.
- The game ends when the player either guesses the word correctly or runs out of attempts.
You can customize the word_list
with your own words or modify the game further to suit your preferences.