Hangman

December 20, 2011

In today’s exercise we implement the classic Unix V7 game hangman for guessing words. The player is given a series of blanks, one per letter of a word to be guessed. At each turn the player guesses a letter; if it is in the word, all occurrences of the letter are filled in the appropriate blank, but if the guess is wrong, another body part — traditionally, the head, torso, two arms and two legs, for a total of six — is added to the gibbet. The player wins by guessing all the letters of the word before the hangman adds all the pieces of his body.

Your task is to implement the interactive game of hangman. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

My attempt using python. It uses the description of the exercise as a source of words, but this can be easily changed.

from random import randint
import re
cad = """
The player is given a series of blanks, one per letter of a word to be guessed.
At each turn the player guesses a letter; if it is in the word,
all occurrences of the letter are filled in the appropriate blank,
but if the guess is wrong, another body part - traditionally, the head, torso,
two arms and two legs, for a total of six - is added to the gibbet.
The player wins by guessing all the letters of the word before the hangman adds all the pieces of his body.
"""
def printLine(word,letters):
cad = ""
for i in range(len(word)):
cad += (word[i] + "." ) if word[i] in letters else "_."
print cad
def printGibbet(n):
gibbet = ["head","torso","left Arm","right Arm","left leg","right leg"]
print ",".join(gibbet[:n])
def addLetters(word,letters,c):
for i in range(len(word)):
if (word[i] == c):
letters.insert(i,c)
return letters
def game():
# We take a list of words from the first line of text to have something to play with,
# we could change this to load from a file or hardcode a list of words
pattern = "^(\w{0,20})([;|,|.]*)$"
word_list = [re.search(pattern,c).group(1) for c in cad.split() if ((len(c) >= 5) & (re.search(pattern,c) != None ))]
word = word_list[randint(0,len(word_list) - 1 ) ]
n = 0
letters = []
while True:
printLine(word,letters)
c = raw_input("Guess a letter: ")
if (re.match("^[a-zA-Z]$",c)== None):
continue
if ((c in word) and ( not c in letters)):
letters = addLetters(word,letters,c)
else:
n +=1
printGibbet(n)
if (n == 6) :
print "You loose the word was %s" % word
return False
print "".join(letters)
if ("".join(letters)== word ):
print "You win! the word was %s " % word
return True