初级刽子手游戏:不能让我

2024-04-26 01:24:45 发布

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

我前天刚开始(在Python3上)编写代码(这让我成为了一个严肃的新手),我想我会尝试制作自己的Hangman游戏,但我只是不知道我到目前为止所做的有什么不对!^_^就是这样:

L = ["cat", "dog", "rabbit"]
from random import randrange
random_index = randrange(0,len(L))
w = L[random_index]
W = list(w)
a = input()
tries = 1
print(W)
while len(W) != 0 and tries<10:
    if a in W:
        print("yes")
        W.remove(a)
        tries += 1
        a = input()
    elif a not in W:
        print("no") 
        tries += 1
        a = input()
else:
    if len(W) == 0: 
        print("Well done! Your word was")
        print(w) 
    elif tries == 10:
        print("You died!")

我想问题来自我的“while len(W)!=0“,因为输入部分一切正常,所以它不会在应该停止的时候停止!(意思是什么时候应该没有什么可以猜测的了!) 所以,我希望有人会很好,浪费他一天的两分钟来帮助我的基本不那么有趣的问题!提前谢谢!你知道吗


Tags: 代码ininputindexlenifrandompython3
3条回答
  • 您可以有多个字母的变量名

  • random.choice(L)L[random.randrange(len(L))]容易

所以呢

from random import choice

def show_word(target_word, remaining_letters, blank="-"):
    print("".join(blank if ch in remaining_letters else ch.upper() for ch in target_word))

words = ["cat", "dog", "rabbit"]
target_word = choice(words)
remaining_letters = set(target_word)

print("Let's play Hangman!")

for round in range(1, 11):
    show_word(target_word, remaining_letters)
    guess = input("Guess a letter: ").strip().lower()
    if guess in remaining_letters:
        print("You got one!")
        remaining_letters.remove(guess)
        if not remaining_letters:
            break
    else:
        print("Sorry, none of those...")

if remaining_letters:
    print("You died!")
else:
    print("You solved {}! Well done!".format(target_word.upper()))

如果我很了解你的问题,你可以这样解决你的问题,还记得你可以给用户提供信息,在输入法中添加提示:

L = ["cat", "dog", "rabbit"]
from random import randrange
random_index = randrange(0,len(L))
w = L[random_index]
W = list(w)
tries = 1
print(W)
while len(W) != 0 and tries<10:
  a = input("select word")
  if a in W:
    print("yes")
    W.remove(a)
    tries += 1
  else:
    print("no") 
    tries += 1

  if len(W) == 0: 
    print("Well done! Your word was")
    print(w)
  elif tries == 10:
    print("You died!")

当您猜到上一个循环末尾的最后一个字母时,当前循环将告诉您猜的是正确的,然后要求另一个字母。试试这个

L = ["cat", "dog", "rabbit"]
from random import randrange
random_index = randrange(0,len(L))
w = L[random_index]
W = list(w)
tries = 0
print(W)
while len(W) != 0 and tries<10:
    a = input()
    if a in W:
        print("yes")
        W.remove(a)
        tries += 1
    elif a not in W:
        print("no") 
        tries += 1
else:
    if len(W) == 0: 
        print("Well done! Your word was")
        print(w) 
    elif tries == 10:
        print("You died!")

相关问题 更多 >

    热门问题