DEV Community

Cover image for Python 26: Guess the Word Game
Gregor Schafroth
Gregor Schafroth

Posted on

Python 26: Guess the Word Game

New year, new code! Today I asked ChatGPT for a small game, as I thought this might be more fun. Here is the exercise I got. As usual you can find my solution below;

Game Title: Guess the Word

Description:
Create a text-based game where the computer selects a random word from a predefined list, and the player has to guess the word one letter at a time. The player has a limited number of attempts to guess the word correctly. Each time the player makes a guess, the computer should provide feedback on whether the guessed letter is in the word and in what position(s).

Requirements:

  1. You can define a list of words from which the computer randomly selects a word.
  2. The game should provide instructions to the player.
  3. The player should have a limited number of attempts (e.g., 5) to guess the word.
  4. After each guess, the game should display the progress made by revealing the correctly guessed letters in their correct positions (if any).
  5. The game should end when the player correctly guesses the word or runs out of attempts.
  6. Provide a congratulatory message if the player wins and reveal the word.
  7. Provide a message if the player loses and reveal the word.

My Solution

And here is my code. Here are some things I learned

  • random.choice() is a useful, simple way to select a random object in a list
  • a for loop can iterate through two strings at once, but will stop once the shorter of the two comes to an end. Not sure I really ever need this but interesting.

If I had more time I would make the responses to each attempt more user friendly and not print a separate line for each guessed letter. It would be better to just show ____ for wrong guesses and then insert the correctly guessed letters until all are there.

import logging
import random

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')

def get_word():
    """
    Selects the word to be guessed from a list
    """
    logging.debug('get_word()')
    word_list = ['Sheep', 'Dragon', 'Frog', 'Dachshund', 'Cat']
    random_word = random.choice(word_list)
    logging.debug(f'random_word: {random_word}')
    return random_word

def play(solution_word, attempts):
    """
    Let's the user guess the word with a certain number of attempts
    """
    logging.debug(f'get_word(solution_word={solution_word}, attempts={attempts})')
    try:
        while attempts > 0:
            logging.info(f'attempts left: {attempts}')
            user_guess = input('Guess: ')
            feedback = []
            index = 0  

            if user_guess.strip().lower() == solution_word.strip().lower():
                return True

            for index, (char1, char2) in enumerate(zip(user_guess, solution_word)):
                index += 1 
                if char1 == char2:
                    feedback.append(f"Letter {index}: {char1} is correct")
                else:
                    feedback.append(f"Letter {index}: {char1} is wrong")

            # Add feedback for extra letters in the user input
            if len(user_guess) > len(solution_word):
                for extra_letter in user_guess[len(solution_word):]:
                    index += 1 
                    feedback.append(f"Letter {index}: {extra_letter} is wrong")

            # Print all feedback
            for feedback_item in feedback:
                print(feedback_item)
            attempts -= 1
        print(f"Out of attempts! The word was: {solution_word}")
    except KeyboardInterrupt:
        logging.error('KeyboardInterrupt')
        pass
    return False

def main():
    solution_word = get_word()
    attempts = 5
    print(f'Guess the word letter by letter. You have {attempts} attempts to guess the word.')
    result = play(solution_word, attempts)
    print(result)

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Have a great 2024 everyone :)

Top comments (0)