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 :)
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74