iT邦幫忙

0

word guess game

  • 分享至 

  • xImage

word guessing game with three words storing the list called wlist
three words are boy, cat, dog respectively.
word randomm selecte from wlist as the secret word.
each character will masked with '-' and stroed in glist.
five changes for users to input single character for guessing
if correctly ,the character will be show in the corresponding location of the secret word

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
shiaobin
iT邦新手 4 級 ‧ 2023-06-08 14:44:06

幫你跟 ChatGPT 問了,以下是它的回答。

Sure! I can help you create a word guessing game based on your requirements. Here's the code:

import random

wlist = ["boy", "cat", "dog"]
secret_word = random.choice(wlist)
glist = list('-' * len(secret_word))
changes = 5

while changes > 0:
    print("Guess the word:", ''.join(glist))
    guess = input("Enter a single character: ")

    if len(guess) != 1:
        print("Please enter a single character.")
        continue

    if guess in secret_word:
        for i in range(len(secret_word)):
            if secret_word[i] == guess:
                glist[i] = guess

        if '-' not in glist:
            print("Congratulations! You guessed the word:", secret_word)
            break
    else:
        changes -= 1
        print("Incorrect guess. You have", changes, "chance(s) left.")

if changes == 0:
    print("Game over. The secret word was:", secret_word)

In this code, we start by importing the random module to select a random word from the wlist. The secret word is stored in secret_word, and we create a list of dashes (-) called glist to represent the masked word.

We then enter a loop where the player has five chances to guess a single character. Each time, we print the masked word (glist), ask for user input, and check if the guess is a single character. If the guess is correct, we replace the corresponding dashes in glist with the guessed character. If the player correctly guesses all the characters in the word, they win the game. Otherwise, if the guess is incorrect, we decrement the changes counter and inform the player about the remaining chances.

After the loop, we check if the player has used all their chances. If so, we reveal the secret word.

我要發表回答

立即登入回答