不能让我的Python刽子手游戏计算猜测

2024-04-24 23:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

import random

# DEFINITIONS
name = str(input("Welcome to python hangman! What's your name?"))
print("Hello,", name + "!")
print("You have 6 chances to guess the letter in the word, best of luck!")


def get_guess():
    l = input("Guess a letter!")
    if len(l) != 1 or l not in             'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
    print("That is not a letter, try again.")
    get_guess()
elif l in guessed:
    print("You have already guessed that letter, try again.")
    get_guess()
else:
    guessed.append(l)
    return l

def check_guess(l):
for i in range(len(word_as_list)):
    if l == word_as_list[i]:
        word_as_blank[i] = l
if l in word:
    print("This is correct")
else:
    print("sorry this letter is not in the word")
    curr_guess = 0
    while curr_guess != 6:
        if curr_guess < 6:
            curr_guess = curr_guess +1
            print("you have had", curr_guess, "guesses")
        else:
            print("you have run out of guesses")

# VARIABLES AND LISTS


secret_lists = ["chicken", "python", "monkey", "giraffe", "panda", "tiger",  "fire", "christmas", "newspaper", "rudolph", name,"aoife"]  # secret words
word = random.choice(secret_lists)
word_as_list = list(word)
word_as_blank = ["_"]*len(word_as_list)
guessed = []

# MAIN PROGRAM

print(word_as_blank)
while word_as_list != word_as_blank:
   guess = get_guess()
   check_guess(guess)
   print(word_as_blank)
print("GAME OVER – you got the word.")

当前的猜测只是打印,他们有1,2,3猜测都在同一时间,我不知道如何做到这一点,一次一个,所以当他们得到的字母错误,它说什么猜测他们是在。你知道吗


Tags: thenameingetifhaveaslist
2条回答

我试过了,效果不错

#You have to make cure_guess global 
global cur_guess = 6
#Print out message
print("Sorry this letter is not in the word")
if curr_guess > 0:
    curr_guess -= 1
    print("You still have", curr_guess , guesses) 
else:
    print("You have runned of guesses")

撇开最佳实践不谈,您需要将curr_guess变量设置为全局变量(如word_as_listword_as_blankguessed等)。然后修改check_guess如下:

...
print("sorry this letter is not in the word")
if curr_guess < 6:
    curr_guess = curr_guess +1
    print("you have had", curr_guess, "guesses")
else:
    print("you have run out of guesses")

相关问题 更多 >