Simple python code to implement the hangman game.The code assumes that you have a file named 'words.txt' which contains n number of words.The program randomly selects one word from the file. The user is given 8 chances to guess the word.Each word guessed by the user is added to the lettersGuessed list.Procedure isWordGuessed() is used to determine whether the guessed letter is in the secretWord.If not the number of guesses remaining is reduced by one.Procedure getGuessedWord is used to print present correctly guessed words and thier locations...
===================================================import
import random
import string
WORDLIST_FILENAME = "words.txt"
def loadWords():
print "Loading word list from file..."
inFile = open(WORDLIST_FILENAME, 'r', 0)
line = inFile.readline()
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def chooseWord(wordlist):
return random.choice(wordlist)
def isWordGuessed(secretWord, lettersGuessed):
for letter in secretWord:
if letter in lettersGuessed:
continue
else:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
result = ""
for letter in secretWord:
if letter in lettersGuessed:
result += letter
else:
result += '_ '
return result
def getAvailableLetters(lettersGuessed):
result = ""
for letter in string.ascii_lowercase:
if letter not in lettersGuessed:
result += letter
return result
def hangman(secretWord):
lettersGuessed = []
mistakesMade = 8
guess=""
print "Welcome to the game, Hangman!"
print "I am thinking of a word that is" ,len(secretWord)," letters long."
while mistakesMade:
print "--------------------------------------------------------"
print "You have",mistakesMade," guesses left."
print "Available letters:",getAvailableLetters(lettersGuessed)
print "Please guess a letter:"
guess=raw_input()
guess=guess.lower()
if guess in lettersGuessed:
print "You've already guessed that letter" ,getGuessedWord(secretWord,lettersGuessed)
continue
else:
lettersGuessed.append(guess)
if isWordGuessed(secretWord,[guess]):
print "Good guess:",getGuessedWord(secretWord,lettersGuessed)
else:
print "Oops! That letter is not in my word:",getGuessedWord(secretWord,lettersGuessed)
mistakesMade -= 1
if '_' not in getGuessedWord(secretWord,lettersGuessed):
print "Congratulations, you won!"
print "Sorry, you ran out of guesses. The word was ",secretWord,"."
def main():
wordlist = loadWords()
secretWord = chooseWord(wordlist)
hangman(secretWord)
if __name__ == '__main__':
main()
==================================================