Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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.

importloggingimportrandomlogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s: %(message)s')defget_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}')returnrandom_worddefplay(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:whileattempts>0:logging.info(f'attempts left:{attempts}')user_guess=input('Guess:')feedback=[]index=0ifuser_guess.strip().lower()==solution_word.strip().lower():returnTrueforindex,(char1,char2)inenumerate(zip(user_guess,solution_word)):index+=1ifchar1==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 inputiflen(user_guess)>len(solution_word):forextra_letterinuser_guess[len(solution_word):]:index+=1feedback.append(f"Letter{index}:{extra_letter} is wrong")# Print all feedbackforfeedback_iteminfeedback:print(feedback_item)attempts-=1print(f"Out of attempts! The word was:{solution_word}")exceptKeyboardInterrupt:logging.error('KeyboardInterrupt')passreturnFalsedefmain():solution_word=get_word()attempts=5print(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 modeExit fullscreen mode

Have a great 2024 everyone :)

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

AI Entrepreneur, building AI Chatbot Assistants for companies and websites.
  • Location
    Zürich, Switzerland
  • Education
    University of St.Gallen, Switzerland
  • Work
    Entrepreneur
  • Joined

More fromGregor Schafroth

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp