Hello, I'm fairly new to programming, and am working on a project for a programming class. I've run into a problem, and need some help...
I'm writing a hangman game and I'm having trouble getting the guessed letter to replace the correct hidden letter. Say the word is DICTIONARY, if the guess is "A", I can't get ********** to become *******A**... I tried test=word , I get a string index out of range error....any help would be greatly appreciated, thanks =)

oh...for graphical representation, i'm using a graphics library that was written by the writers of the textbook that my class is using, but I left out the code for that to reduce clutter...


from random import *

def wordsSetup():

    wordBank = "DICTIONARY","YAHWEH","HANG","MUSIC","ORCHESTRA","GREEN","HYPERBOLE","DESTRUCTION","PYTHON","FRUSTRATION","EXTRA"
    x=randint(0,9)
    print x
    for i in range(10):
        if i == x:
            word=wordBank[i]
    return word
        
        
def main():
    word=wordsSetup()
    for i in range(len(word)):
        test="*"*(i+1)
    print word #test purposes
    guess1=raw_input("Enter Guess in Caps ")
    print guess1    
    for i in range(len(word)):
        print word[i]   
        if guess1==word[i]:
            test[i]=word[i] 
            print test
    return 0
main ()

make

#
for i in range(len(word)):
#
test="*"*(i+1)

into this test = "*"*(len(word)) In your example you are doing the assignment over and over. The for i in range(len(word)): is a loop, so you loop through the assignment over and over for no reason.

hi,
here are some small modifications to your program:

from random import *
 
def wordsSetup():
 
    wordBank = "DICTIONARY", "YAHWEH", "HANG", "MUSIC", "ORCHESTRA", "GREEN", "HYPERBOLE", "DESTRUCTION", "PYTHON", "FRUSTRATION", "EXTRA"
    x = randint( 0, 10 )

    return wordBank[ x ]
 
def main(): 
    word = wordsSetup()
    test = ""
    guessed = ""
    for i in word:
        test += "*"
    print word #test purposes
    guess1 = raw_input( "Enter Guess in Caps " )

    for i in range( len( word ) ):   
        if guess1 == word[ i ]:
            guessed += word[ i ]
        else:
            guessed += "*"
    print guessed
    
main()

You'll need to construct a new string with the guessed letters, because strings cannot be changed, that's why I'm using 'guessed' as a container for the guessed word.
Note that you'll have to figure out how to exclude letters that are already guessed and ask the user to enter letters until the word is guessed or the user is 'hanged' :)

hope this helps :)

I have been playing with your code for the hangman game and made a complete working program. It has gone a long way from what you started out with, but maybe you want to have a look at it. It may give you ideas for what you need to change in your own code.

I did the graphics just with ascii in the terminal window running it.

This article has been dead for over six months. Start a new discussion instead.