Python中的hang子手游戏

问题描述:

我正在开发一个特定的项目,它有一个bug。该剧再次适合'不'。但是,这将显示每次我输入“是”:Python中的hang子手游戏

TIME TO PLAY HANGMAN 
Do you want to play again (yes or no)? 

这里是我的全部代码

import random 

def Hangman(): 
print ('TIME TO PLAY HANGMAN') 

wordlist =['apples', 'oranges', 'grapes', 'pizza', 'cheese', 'burger'] 
secret = random.choice(wordlist) 
guesses = 'aeiou' 
turns = 5 

while turns > 0: 
    missed = 0 
    for letter in secret: 
     if letter in guesses: 
      print (letter,end=' ') 
     else: 
      print ('_',end=' ') 
      missed= missed + 1 

    print 

    if missed == 0: 
     print ('\nYou win!') 
     break 

    guess = input('\nguess a letter: ') 
    guesses += guess 

    if guess not in secret: 
     turns = turns -1 
     print ('\nNope.') 
     print ('\n',turns, 'more turns') 
     if turns < 5: print ('\n | ') 
     if turns < 4: print (' O ') 
     if turns < 3: print (' /|\ ') 
     if turns < 2: print (' | ') 
     if turns < 1: print ('/\ ') 
     if turns == 0: 
      print ('\n\nThe answer is', secret) 

playagain = 'yes' 
while playagain == 'yes': 
    Hangman() 
    print('Do you want to play again? (yes or no)') 
    playagain = input() 
+0

我甚至无法让你的代码运行。它在各地都被打破了。 – DejaVuSansMono

+0

你只需要缩进大部分的代码,这样它的hangman函数的一部分 – Navidad20

如果代码看起来这里像它在你的编辑器,你的问题是你有没有在print('TIME TO PLAY HANGMAN')之后缩进了所有代码,所以python认为它在外部范围内,只执行一次。它需要看起来像:

def Hangman(): 
    print ('TIME TO PLAY HANGMAN') 
    wordlist =['apples', 'oranges', 'grapes', 'pizza', 'cheese', 'burger'] 
    # etc. 

playagain = 'yes' 
while playagain == 'yes': 
    # etc. 

Hangman函数做的唯一的事情就是打印“时间玩刽子手”。其他一切都在功能之外。修正你的缩进以将游戏循环放入函数中,它应该起作用。

你停留在while循环:

playagain = 'yes' 
while playagain == 'yes': 
    Hangman() 
    print('Do you want to play again? (yes or no)') 
    playagain = input() 

你的循环在不断地寻找,看是否playagain == 'yes'。既然你输入了yes,while循环运行的条件仍然是真的,这就是为什么它再次运行并打印你的语句。

我没有运行你的代码或检查它的其余部分,但根据你给的问题,这应该是你的修复。