-1

This hangman game isn't entirely finished as I'm still working on it, however i came across this error which occurs very often if i get all my guesses correct. When i run it and guess a number of guesses it will sometimes not print the correct amount of left gaps after the letter or the error:

 Traceback (most recent call last):
  File "C:\Users\Gaming\Desktop\Hangman.py", line 110, in <module>
    display(Hangman,randomWord,wrongLetters,correctLetters)
  File "C:\Users\Gaming\Desktop\Hangman.py", line 73, in display
    blanks = secretWord[i] + blanks[:i]  + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'
IndexError: string index out of range

will come up and sometimes both errors will happen follow one after another.

Can someone tell me how to fix this error and why it happens?

import random

Hangman = ['''

   +---+
   |   |
       |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
   |   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  /    |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  / \  |
       |
 =========''']

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def GetRandomWord(word):
    chosenWord = random.choice(word)
    return chosenWord


def display(hangmanPic,secretWord,numWrongLetters,correctLetters):
    blanks = '-'*len(secretWord)

    for i in range(len(secretWord)):#repleaces blank letters with correct letters
        if secretWord[i] in correctLetters:
            blanks = secretWord[i] + blanks[:i]  + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'

    print("Missing Letters:")        
    for letter in blanks:
        print(letter,end='')
    print(hangmanPic[numWrongLetters])



def getGuess(alreadyGuessed):
    while True:
        print("Guess Letter:")
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print("Please enter only 1 letter.")
        elif guess in alreadyGuessed:
            print("Letter is already guessed.")
        elif guess.isdigit():
            print("Please enter a letter not integer.")
        else:
            return guess

def playAgain():
    print("Do you want to play again?") 
    pass



print("H A N G M A N")
correctLetters = ''
guessedLetters = ''
wrongLetters = 0
randomWord = GetRandomWord(words)
gameDone = False

while True:
    display(Hangman,randomWord,wrongLetters,correctLetters)
    guess = getGuess(correctLetters + guessedLetters)

    if guess in randomWord:
        correctLetters += guess
        foundAllLetters = True
        for i in range(len(randomWord)):
            if randomWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if randomWord[i] in correctLetters:
            foundAllLetters = True
            print("Well Done You found what the missing word is!")
            gameDone = True

    else:
        wrongLetters +=1
        guessedLetters += guess
Arount
  • 9,853
  • 1
  • 30
  • 43
Ivan
  • 117
  • 1
  • 1
  • 9
  • 3
    You are getting a 'string index out of range' error because you are accessing a string with an index that is out of range. The error even tells you the exact line, all you have to do now is determine which of the two strings you are accessing by index on that line is shorter than you presume, which seems straightforward enough. What have you tried to solve this, and where are you stuck? – HugoRune Mar 04 '17 at 13:28
  • Im stuck on the part that if i remove blanks[i+1] it will solve the issue as far as i know however then the missing letters after the letters wont show as in the '-' – Ivan Mar 04 '17 at 15:01

1 Answers1

-1
for i in range(len(secretWord)):
    if secretWord[i] in correctLetters:
        blanks = secretWord[i] + blanks[:i]  + blanks[i+1]
    #                                                  | will be out of range for the last 'i'

What you should do, only change the letter at blanks[i]. Strings, however, are immutable in Python, but from what I can see you should be perfectly fine using a list instead. Change the declaration of blanks to

blanks = ['-']*len(secretWord)

Now you should be able to use

blanks[i] = secretWord[i]

Another tip would be to use enumerate instead of range for a little cleaner code:

blanks = ['-']*len(secretWord)
for i, letter in enumerate(secretWord):
    if letter in correctLetters:
        blanks[i] = letter
Community
  • 1
  • 1
pingul
  • 3,351
  • 3
  • 25
  • 43
  • idk why someone downvoted your comment and my post but, when i use 'blanks[i] = secretWord[i]' this error comes up TypeError: 'str' object does not support item assignment. – Ivan Mar 04 '17 at 15:07
  • actaully the same error comes up when i use enumerate as well – Ivan Mar 04 '17 at 15:09
  • @Ivan Ah, I didn't realise `blanks` was a string and not a list. I've made a small edit. – pingul Mar 04 '17 at 15:59
  • Thanks DUDE !! :D ive been trying to solve this stupid problem for over 1 hour and the key were two brackets to solving the issue :D – Ivan Mar 04 '17 at 16:11