Hi, I'm trying to write a hangman game program, but some things aren't working properly.

def hangman():
    choice=input("Enter a letter: ")
    a=type.find(str(choice))
    if len(choice)>1:
        print ("Only one letter please")
        hangman()
    elif a!=-1:
        b[a]=str(choice)
        print ("Correct")
        c=''.join(b)
        print (c)
        if type==c:
            print ("WINNAR!")
        else:
            hangman()
    else:
        d+=1
        e[d]=choice
        if d==0:
            print ("O",e)
            hangman()
        elif d==1:
            print (e,"O<")
            hangman()
        elif d==2:
            print (e,"0<-")
            hangman()
        elif d==3:
            print (e,"O<-<\n You lose!")
 
if __name__=='__main__':
    type=input("Enter a word: ")
    type=''.join(type.lower().split(' '))
    b=['_ ']*len(type)
    print (''.join(b))
    d=-1
    e=['']*5
    hangman()

After running and testing the program several times I've discovered some problems.
Bugs:
- When more than one of the same letter is in a word, only the first letter is added. For example, if I used the word 'moose', then only the first 'o' would show, and I can't enter another 'o'.
- Capital letters cannot be entered, only when first entering the word.
- I also want a way to randomly generate words instead of the person entering it because it's not hangman if you know the word already.
- When you don't enter a word and just hit enter, the program still runs.
- When you enter a letter that isn't part of the word it gives you an error.
- If I enter a letter, then a space for when it asks me for a letter, then it screws up the program a little (not sure how to describe).

I want to incorporate error handling, and a class, but I'm not completely sure on how to do them.

Thanks for reading.

Member Avatar for masterofpuppets

hi,
here's a way of doing this using a class:

from random import *

class Hangman:
    def __init__( self, textFile ):
        self.__word = self.generateWord( textFile )
        self.__used = []
        self.__guessed = []
        self.__tries = 10
        self.__checkWord = self.removeDuplicateLetters()
        self.newGame()
        
    def generateWord( self, fileName ):
        f = open( fileName, "r" )
        words = f.readlines()
        f.close()

        return words[ randint( 0, len( words ) - 1 ) ].strip()

    def removeDuplicateLetters( self ):
        l = []
        for w in self.__word:
            if w not in l:
                l.append( w )
        return l

    def displayWord( self ):
        for l in self.__word:
            if l in self.__guessed:
                print l,
            else:
                print "_ ",
        print

    def newGame( self ):
        win = False
        while not win and self.__tries > 0:
            self.displayWord()
            guess = raw_input( "Enter your guess >> " ).lower()
            while guess not in "abcdefghijklmnopqrstuvwxyz":
                print "Enter a letter please!\n"
                guess = raw_input( "Enter your guess >> " ).lower()
            if guess in self.__word and guess not in self.__used:
                print "You guessed a letter!\n"
                self.__guessed.append( guess )
                if len( self.__guessed ) == len( self.__checkWord ):
                    win = True
            else:
                if guess in self.__used:
                    print "Letter already used.\n"
                else:
                    self.__tries -= 1
                    print "The letter is not in the word. Tries left >", self.__tries, "\n"

            self.__used.append( guess )

        if not win:
            print "You lost the game!"
        else:
            print "You guessed the word!"

if __name__ == "__main__":
    Hangman( "words.txt" )

it may not be the best way to implement but I think you'll get the idea :)
As for the word list, Why don't you use a test file containing all possible words for the game and read it in the program instead off asking the user to input the word. That's what I'm using anyway. There may be a bug I missed somewhere :)

hope this helps :)

commented: So helpful! +0

Wow thanks you so much for a better way of doing this. I tried the program and there were some bugs and I'm also using Python 3.1, but I did a little editing and got it to work. If I have any more questions, I'll let you know. Thanks again.

Member Avatar for masterofpuppets

yeah sorry about that I guess I should've mentioned that I'm using Python 2.5.2 :)

I had a simple solution using a list of lists to associate the letter with the original position.

def find_letter(letter, list_in, stars_list):
   for ch_list in list_in:
      ##print("     comparing %s and %s" % (letter, ch_list[0]))
      if letter == ch_list[0]:
         print("     found %s" % (ch))

         ## replace '*' with letter
         el = ch_list[1]     ## original position of this letter
         stars_list[el] = letter

         ## remove letter's list from the list of lists
         list_in.remove(ch_list)
         return list_in, stars_list

   ## letter not found so return original lists
   return list_in, stars_list


original_word = "Dictionary"
original_word = original_word.lower()

## convert word into list
word_list = [(ch, x) for x, ch in enumerate(original_word)]
print word_list

## list of '*' to be printed
stars_list = []
for ch in word_list:
   stars_list.append("*")

## simulate some guesses entered
guesses = ["A ", " b  ", "c", "I", "t", "i"]
for ch in guesses:
   ch = ch.strip().lower()
   word_list, stars_list = find_letter(ch, word_list, stars_list)
   print " ".join(stars_list)
   print word_list

Small problem, when I just hit entter in the input, it will count that as a correctly guessed letter. Then that means I need one less to win the game.

*edit* Nevermind, I figured out that I just needed to to guess == ""

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.