#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    1
    Rep Power
    0

    Python hangman code not working and I'm not sure why.


    I have made a simple hangman game using helpful resources from the internet and the game itself works fine, unfortunately when I tried to add in a feature to be able to playagain at the end of the game, it wouldn't work! I've been trying for almost an hour and even resources on the internet can't help me, this is my final stand I wonder if anyone can test my code and tell me what is wrong so I could fix it! I really would like to make this code work!
    I'd like for the code only to accept single letters and not accept the same letter more than once, if anyone knows how to do this please let me know, but right now I'm just focused on the playagain feature if anyone can help, thanks!

    I am a beginner at python, sorry!


    Code:
    import random 
    
    name = input("What is your name? ")
    print ("Hello, " +name, "It's time to play hangman!")
    
    
    countryName = ['england','spain','japan','korea','china','germany','france'] 
    word = random.choice(countryName) 
    guesses = '' 
    turns = 6
    def playAgain():
      print ("Would you like to play again? (yes or no)")
      return input().lower().startswith('y')
      print ('H A N G M A N')
      failed = ('')
      letter = ('')
      word = random.choice(countryName)
    
    
    while turns > 0: 
      failed = 0 
      for letter in word: 
        if letter in guesses: 
          print (letter)
        else: 
          print ("_ ")
          failed += 1 
      print 
           
    
      if failed == 0: 
        print ('You win! Good job!')
        gameIsDone = True
        break 
    
      guess = input('guess a letter: ') 
      guesses += guess
      
    
      if guess not in word: 
        turns -= 1
        
        print ('Sorry no') 
        print ("You have", + turns, "more guesses") 
        if turns < 6: print ('   O   ') 
        if turns < 5: print (' \_|_/ ') 
        if turns < 4: print ('  ;|;  ') 
        if turns < 3: print ('  / \  ') 
        if turns < 2: print (' -   - ') 
        if turns < 1: print (' E N D ')
        if turns == 0: print ('The answer was ' + word + ' sorry!')
        gameIsDone = True
        
    if gameIsDone:
      if playAgain():
         missedLetters = ''
         correctLetters = ''
         gameIsDone = False
         word = random.choice(countryName)
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    You have scatter shot of good ideas. Convert them into a cohesive whole.
    Code:
    # deal with python version issue
    import sys
    if sys.version[0] < '3':
      input = raw_input
    
    import random
    
    countryName = ['england','spain','japan','korea','china','germany','france'] # make the data globally available to other modules
    
    def playAgain():
      return input("Would you like to play again? (yes or no)\n").lower().startswith('y')
     
    def hangman(word, turns = 6):           # default number of turns allows the caller to control difficulty.
    
      # initialization
      print('The word has {} characters.'.format(len(word)))
      letters = set(word)
      guesses = set()                       # use a set to store the guesses
    
    
      while turns:                          # while incomplete
    
        # handle the input
        guess = input('guess a letter: ')[:1].lower()
        if guess in guesses:                # allow repeated guesses
          continue
        guesses.add(guess)
    
        # generate and show the displayed word
        fill_in = []
        for letter in word:
          if letter in guesses:
            fill_in.append(letter)
          else:
            fill_in.append('_')
        print(' '.join(fill_in))
    
        # check for victorious completion
        if letters.issubset(guesses):
          print ('You win! Good job!')
          turns = 0                         # break or return statements also work
    
        # deal with incorrect guess
        if guess not in word:
          turns -= 1
          print ('Sorry no')
          print ("You have", + turns, "more guesses")
          if turns < 6: print ('   O   ')
          if turns < 5: print (' \_|_/ ')
          if turns < 4: print ('  ;|;  ')
          if turns < 3: print ('  / \  ')
          if turns < 2: print (' -   - ')
          if turns < 1: print (' E N D ')
          if turns == 0: print ('The answer was ' + word + ' sorry!')
    
    def main(data, name=''):
      while True:
        hangman(random.choice(data))
        if not playAgain():
          break
    
    # play the game when the module is used a complete program.
    if __name__ == '__main__':              # an un-named module's name is '__main__'.  This is always the initial module.
      name = input("What is your name? ")
      print("Hello, " +name, "It's time to play hangman!")
      main(countryName, name)
    
    
    # program tested by playing.  Convenient doctest/unit test requires
    # more changes than seem appropriate for this post.
    # (input would be a stream that could be replaced with StringIO,
    #  and I'd include an option to avoid displaying the hanged man)


    A few other comments on your effort:
    Code:
    def playAgain():
      print ("Would you like to play again? (yes or no)")
      return input().lower().startswith('y')
    
      # statements following return are not evaluated.
      print ('H A N G M A N')
      failed = ('')				# these assignments are local to the function.  see the global statement in documentation
      letter = ('')
      word = random.choice(countryName)
    
    #...
    
    if gameIsDone:
      if playAgain():			### WHERE IS THE GAME????
         missedLetters = ''
         correctLetters = ''
         gameIsDone = False
         word = random.choice(countryName)
    Last edited by b49P23TIvg; November 8th, 2013 at 08:55 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo