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.
Not much to see here.
C++ solution, slightly less interactive and rather longer. Procedural, nothing more fancy than a string.
[…] today a task that was more practical engineering than theoretical science. Write a game of Hangman. The language is C++ although, for the sake of simplicity, I avoided classes and algorithms. […]
Python 3 version with ascii graphics.
Uses wordlist from 12dicts, which can be found at http://wordlist.sourceforge.net/
My attempt using python. It uses the description of the exercise as a source of words, but this can be easily changed.
I have hardcoded the
class HangMan(object):
“””
“””
def __init__(self):
“””
“””
self.hangman = [‘head’, ‘torso’, ‘leftarm’, ‘rightarm’, ‘leftleg’, ‘rightleg’]
self.wordsList = [‘head’, ‘torso’, ‘leftarm’, ‘rightarm’, ‘leftleg’, ‘rightleg’]
def GetNextHangManPart(self):
“””
“””
for word in self.hangman:
ostr = “Wrong guess! you got %s Try Again!” %(word)
yield ostr
def PlayGame(self):
“””
“””
for word in self.wordsList:
letterCount = 0
GuessCount = 0
hangmanGenerator = self.GetNextHangManPart()
print “New word with %d characters” %(len(word))
try:
while(letterCount < len(word)):
input = raw_input("Guess the %d letter: " %(letterCount+1))
if word[letterCount] == input:
print "Good Work"
letterCount +=1
else:
print hangmanGenerator.next()
except:
print "You lost! better luck next time"
print "Game Completed!"
if __name__ == '__main__':
hm = HangMan()
hm.PlayGame()