簡體   English   中英

調試“猜詞”游戲

[英]Debugging a “guess the word ” game

我的代碼有一個小問題,在我把所有字母都正確后,我不得不輸入另一個字母,它會表明我做對了。 問題是什么?

import random
import string
import sys

def split(word):
    return list(word)

alphabet = 'abcdefghijklmnopqrstuvwxyz'
list(alphabet)

words = ['hat','pop' ,'cut' , 'soup' , 'you' , 'me' , 'gay' , 'lol' ]

guess_word = []
wrong_letters_storage = []
secret_word = random.choice(words)
word_length = print("the length of the word is " + str(len(secret_word)))
correct_letters = split(secret_word)


def words():
    for letter in secret_word:
        guess_word.append("-")
    return print("the words that you are guessing is " + str(guess_word))

def guessing():

    while True:
        c = 0
        b = 7
        while c <= 7:

            print("")
            hide = ""
            print("you have " + str(b) + " guess left")
            print("Wrong letters : " + str(wrong_letters_storage))
            command = input("guess: ").lower()

            if not '-' in guess_word:
                print("you win!")
                break
            elif command == 'quit':
                print("thank you for playing my game")
                break
            else:

                if not command in alphabet :
                   print("pick an alphabet")
                elif command in wrong_letters_storage:
                   print("you have picked this word")
                else :

                    if command in secret_word :
                        print("right")
                        c += 1
                        b -= 1

                        for x in range(0, len(secret_word)):
                            if correct_letters[x] == command:
                                guess_word[x] = command
                                print(guess_word)

                    elif not command in secret_word :
                        print("wrong")
                        wrong_letters_storage.append(command)
                        c += 1
                        b -= 1
                    else :
                        print("error")

            print("*"*20)
        return print("Thank you for playing my game")



words()
guessing()
print("the words that you are guessing is " + secret_word )

您的代碼有幾個“問題”:

  • 在您要求下一個字符input()之后,您檢查當前解決方案中是否沒有更多'-'
  • return print("whatever")返回None因為 print function 打印並返回None
  • 您使用帶有single_letter_names的變量,這使得很難知道它們的用途
  • 您使用list代替set()進行查找(這里很好,但不是最佳的)

您可以通過在 input() 命令之前移動測試語句來解決您的問題:

# your code up to here

while True:
    c = 0
    b = 7
    while c <= 7:
        if not '-' in guess_word:
            print("you win!")
            break

        print("")
        hide = ""
        print("you have " + str(b) + " guess left")
        print("Wrong letters : " + str(wrong_letters_storage))
        command = input("guess: ").lower()

        if command == 'quit':
            print("thank you for playing my game")
            break
        else:

        # etc.

做更多的重構可能會更好:

import random
import string
import sys

def join_list(l):
    return ''.join(l)

def guessing():
    # no need to put all this in global scope

    alphabet = frozenset(string.ascii_lowercase) # unchangeable set of allowed letters 

    words = ['hat', 'pop', 'cut', 'soup', 'you', 'me', 'beautiful', 'lol']

    secret = random.choice(words)       # your random word
    secret_word = list(secret.lower())  # your random word as lowercase list
    wrong = set()                       # set of wrongly guessed characters
    right = set()                       # set of already correctly guessed characters
    correct = frozenset(secret_word)    # set of letters in your word, not changeable

    guess_word = ['-' for k in correct] # your guessed letters in a list

    guesses = 7
    guessed = 0
    print("The length of the word is ", len(secret))

    # loop until breaked from (either by guessing correctly or having no more guesses)
    while True: 
            print("")
            print(f"you have {guesses-guessed} guess left")
            if wrong: # only print if wrong letters guessed
                print(f"Wrong letters : {wrong}")
            # print whats know currently:
            print(f"Guess so far: {join_list(guess_word)}")

            command = input("guess: ").strip().lower()
            try:
                if command != "quit":
                    command = command[0]
            except IndexError:
                print("Input one letter")
                continue

            if command == 'quit':
                print("thank you for playing my game")
                break
            else:
                if command not in alphabet:
                    print("pick an alphabet")
                    continue
                elif command in (wrong | right):
                    print("you already picked this letter")
                    continue
                else :
                    guessed += 1
                    # always lookup in set of lowercase letters
                    if command in correct:
                        right.add(command)
                        for i,letter in enumerate(secret_word):
                            if command == letter: 
                                # use the correct capitalisation from original word
                                guess_word[i] = secret[i] 
                    else:
                        print("wrong")
                        wrong.add(command)

            print("*"*20) 

            # break conditions for win or loose
            if join_list(secret_word) == join_list(guess_word):
                print("You won.")
                break
            elif guessed == guesses:
                print(f"You lost. Word was: {join_list(secret_word)}")
                break

guessing()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM