简体   繁体   中英

A hangman game in Python

I'm working on a certain project and this has a bug in it. The play again works perfect for the 'no'. But it displays this each time I type 'yes':

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

Here's my whole code

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()

If the code looks here like it does in your editor, your problem is that you haven't indented all the code after print('TIME TO PLAY HANGMAN') , and so python thinks it is at the outer scope and only executes it once. It needs to look like:

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

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

The only thing your Hangman function does is print "TIME TO PLAY HANGMAN". Everything else is outside the function. Fix your indentation to put the gameplay loop inside the function and it should work.

You're stuck in the while loop:

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

Your loop is continuously looking to see if playagain == 'yes' . Since you enter yes, the condition for your while loop to run is still true, which is why it runs again and prints your statements.

I didn't run your code or check the rest of it, but based on the problem you gave, this should be your fix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM