0

so i have this hangman code... again, thanks in advance, and it reveals the words one by one and that works fine, but when there is multiple words like two l's in hello and two p's in apple it only reveals one not two. i don't know why this is and I've done some google greasing and what came up was enumerating but I've tried that to no avail. This is the code:

def hangman():
    global fullWordList
    fullWordList = []
    global wrongnums
    wrongnums =[]
    print("What is the word to be guessed?")
    print("Words means that there are no numbers")
    global guessnum
    guessnum=input('>')
    fullWord = guessnum
    for line in fullWord:
      for c in line:
        fullWordList.append(c)
        print (fullWordList)
    print("how many chances?")
    global chances
    chances=int(input('>'))
    print("game in beginning")
#    sleep(5)
#    print ("\n" * 100)
    global blanks
    blanks = '_ ' * len(guessnum)
    print()
    print(blanks)
    guessing()

def guessing():
    global fullWordList
    global chances
    print("guess a letter")
    global guess
    guess=input('>')
    guessloop()

def guessloop():
    global chances
    if guess in fullWordList:
        if guess in fullWordList:
            letterIndex = guessnum.index(guess)
            global blanks
            blanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
            fullWordList.remove(guess);
            global lenWord
            lenWord = len(fullWordList)
            print (fullWordList)
            print (lenWord)
            print ("Guess is correct!")
            if guess in fullWordList:
                guessloop()

            else:
                wrongnums.append(guess)
                print (wrongnums)
                if lenWord == 0:
                    print() 
                    print("Word: ",blanks)
                    win()

                else:
                    print() 
                    print("Word: ",blanks)
                    guessing()

        else:

            if lenWord == 0:
                win()

            else:
                print() 
                print("Word: ",blanks)
                guessing()

    elif guess in wrongnums:
        print("You've guessed that!")
        guessing()

    else:
        chances -=1
        wrongnums.append(guess)
        print (wrongnums)
        print ("Guess is wrong! ", chances, " more failed attempts allowed.")
        if chances == 0:
          gameOver()

        else:
          guessing()

def check():    
    print() 
    print("Word: ",newBlanks)
    guessing2()

def win():
  print("You guessed it well done")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()

def gameOver():
  print("You ran out of guesses, sorry, you lose")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()

Now i have also got a code:

def hangman():
    global fullWordList
    fullWordList = []
    global wrongnums
    wrongnums =[]
    print("What is the word to be guessed?")
    print("Words means that there are no numbers")
    global guessnum
    guessnum=input('>')
    fullWord = guessnum
    for line in fullWord:
      for c in line:
        fullWordList.append(c)
        print (fullWordList)
    print("how many chances?")
    global chances
    chances=int(input('>'))
    print("game in beginning")
#    sleep(5)
#    print ("\n" * 100)
    global blanks
    blanks = '_ ' * len(guessnum)
    print()
    print(blanks)
    guessing()

def guessing():
    global fullWordList
    global chances
    print("guess a letter")
    global guess
    guess=input('>')
    guessloop()

def guessloop():
    global chances
    if guess in fullWordList:
        if guess in fullWordList:
            letterIndex = guessnum.index(guess)
            global blanks
            guesses = (guessnum)
            guesses = blanks[letterIndex]
            blanks[letterIndex] = guess
            fullWordList.remove(guess);
            global lenWord
            lenWord = len(fullWordList)
            print (fullWordList)
            print (lenWord)
            print ("Guess is correct!")
            if guess in fullWordList:
                guessloop()

            else:
                wrongnums.append(guess)
                print (wrongnums)
                if lenWord == 0:
                    print() 
                    print("Word: ",blanks)
                    win()

                else:
                    print() 
                    print("Word: ",blanks)
                    guessing()

        else:

            if lenWord == 0:
                win()

            else:
                print() 
                print("Word: ",blanks)
                guessing()

    elif guess in wrongnums:
        print("You've guessed that!")
        guessing()

    else:
        chances -=1
        wrongnums.append(guess)
        print (wrongnums)
        print ("Guess is wrong! ", chances, " more failed attempts allowed.")
        if chances == 0:
          gameOver()

        else:
          guessing()

def check():    
    print() 
    print("Word: ",newBlanks)
    guessing2()

def win():
  print("You guessed it well done")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()

def gameOver():
  print("You ran out of guesses, sorry, you lose")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()


hangman()

This is what i edited it to and got this error:

blanks[letterIndex] = guess
TypeError: 'str' object does not support item assignment

I really am stumped, i hope this is enough data to help.

dom daly
  • 11
  • 6

1 Answers1

1

I've tried to change your code as little as possible, but I need to get code working fully to work out all the bugs, so I'm sharing what I've done with your code.

You've identified two problems - one is that as soon as there's a single match, the program moves on to the next guess, without checking for multiple positive hits.

The second problem is that the error you were getting is that 'blanks' was a string and you were trying to change a character at a specific index (line 43 of the second code sample: blanks[letterIndex] = guess). Strings are immutable, so the attempt to alter a character in place isn't possible. There's more than one way around this - one that I went with (below) is to set 'blanks' up as a list, allowing you to change any of the elements of the list (since lists are mutable). To display the list to the user, try ''.join(blanks) to make a presentable string out of the list.

I made a few changes to the code (again, trying to honour your structure and style) to come up with something that works:

  1. removed the variable guessnum (you only need fullWord)
  2. converted 'blanks' from being a string to a list - now you can make changes as guesses are correct. This directly relates to the question you ask.
  3. simplified the flow of your if ... else statement in the guessing function, going through the three possible outcomes: correct guess, repeated guess, and incorrect guess. Within those are some sub-checks (if correct, is it a win? if incorrect, is it a loss?) I included some comments so you can see what changes were made and where.
  4. when a guess is correct, 'blanks' is updated accordingly for EVERY match that occurs. (And blanks is displayed by using ''.join(blanks) to make a string of the elements.) When a guess is correct, fullWordList is also updated for EVERY match that occurs - the letter is replaced with '-'. So now a check for a win is whether the fullWordList contains only '-' elements.

There's still no catching of exceptions, but what is here works with a word like 'apple' - trying to win, lose, and repeat guesses.

Hope it helps - let me know if there's something that isn't clear. I didn't want to just re-write your code, but wanted to walk through one approach to the problem.

There are other improvements that can be made, but this at least clears your hurdles.

THE CODE

def hangman():
    global fullWordList
    fullWordList = []
    global wrongnums
    wrongnums =[]
    print("What is the word to be guessed?")
    print("Words means that there are no numbers")
    # no need to set two variables for same thing (fullWord and guessnum)
    global fullWord
    fullWord=input('>')
    for line in fullWord:
      for c in line:
        fullWordList.append(c)
        print (fullWordList)
    print("how many chances?")
    global chances
    chances=int(input('>'))
    print("game in beginning")
#    sleep(5)
#    print ("\n" * 100)
    global blanks
    # treat blanks as a list rather than string (list is mutable)
    blanks = ['- '] * len(fullWord)
    print()
    print(blanks)
    guessing()

def guessing():
    global fullWordList
    global chances
    print("guess a letter")
    global guess
    guess=input('>')
    guessloop()

def guessloop():
    global chances, guess, blanks, blankList, fullWordList

# three possibilities: correct guess, repeated guess, incorrect guess 
# 1. correct guess
    if guess in fullWordList:
    #generates list of indices of ALL matches  
    # stackoverflow.com/questions/9542738/python-find-in-list
        letterIndex = [i for i, x in enumerate(fullWordList) if x == guess]
        print letterIndex
        for idx in letterIndex:
            # change elements in blank list if there's a match
            blanks[idx] = (guess +' ')
            # update fullWordList to replace correct guesses with '-'
            fullWordList[idx] = ('-')
        # display the updated blank list as a string            
        print ''.join(blanks)
        # replace all occurrences of guess from fullWordList with '-'
        print ("Guess is correct!")
        # add guess to wrongnums to record it as 'already guessed'
        wrongnums.append(guess)
        # check if it's a winning guess
        if fullWordList == ['-']*len(fullWord):
            print() 
            # display updated list as string
            print("Word: ", ''.join(blanks))
            win()

# 2. repeated guess
    elif guess in wrongnums:
        # don't add to wrongnums if already guessed (letter is already in there)
        if guess in wrongnums:
            print("You've guessed that!")
            print ''.join(blanks)

# 3. incorrect guess
    else:
        chances -=1
        wrongnums.append(guess)
        print (wrongnums)
        print ("Guess is wrong! ", chances, " more failed attempts allowed.")
        print ''.join(blanks)
        if chances == 0:
            gameOver()

    guessing()

def check():    
    print() 
    print("Word: ",newBlanks)
    guessing2()

def win():
  print("You guessed it well done")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()

def gameOver():
  print("You ran out of guesses, sorry, you lose")
  print("Would you like to play again?")
  PG = input(">")
  if PG == "yes" or PG == "Y" or PG == "Yes" or PG == "yea" or PG == "Yea":
    print ("Game will restart in 5 seconds")
    sleep(5)
    hangman()

  else:
    print("Going to main menu in 5 seconds")
    sleep(5)
    start()

hangman()
Stidgeon
  • 2,673
  • 8
  • 20
  • 28
  • Wow, thank you soo much. i see how you have fixed everything you have explained it very well. i was going to do some optimization after the code was completed and now there isn't as much to be done. You explained it well for me. – dom daly Nov 25 '16 at 08:12