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

def hangman():
    choice=input("Enter a letter: ")
    if len(choice)>1:
        print ("Only one letter please")
    elif a!=-1:
        print ("Correct")
        print (c)
        if type==c:
            print ("WINNAR!")
        if d==0:
            print ("O",e)
        elif d==1:
            print (e,"O<")
        elif d==2:
            print (e,"0<-")
        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))

After running and testing the program several times I've discovered some problems.
- 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.

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()
    def generateWord( self, fileName ):
        f = open( fileName, "r" )
        words = f.readlines()

        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,
                print "_ ",

    def newGame( self ):
        win = False
        while not win and self.__tries > 0:
            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
                if guess in self.__used:
                    print "Letter already used.\n"
                    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!"
            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 :)

Edited 6 Years Ago by masterofpuppets: n/a

So helpful!

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.

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
         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:

## 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

Edited 6 Years Ago by woooee: n/a

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 == ""

Edited 6 Years Ago by JuvenileMango: n/a

This question has already been answered. Start a new discussion instead.