Micro Project: Hangman Game

Well , this micro game is the first game in the series games that I intend to make (just for fun).
Hangman game (from Wiki):
Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word, phrase or sentence and the other tries to guess it by suggesting letters or numbers, within a certain number of guesses.

This game is so so simple: given a random word, your job is to find that word in several steps. If you missed too many times, you lose. If you successfully find out what that word is, you win.
I rank this as a micro project because it’s so small, no graphics, just console.

I made use of OOP (Object-Oriented Programming), so the entire game is inside a class called HangmanGame, the code is very simple, easy to follow and well commented.

import random
HANGMAN_PICS = [
'''
   +---+
   |   |
       |
       |
       |
       |
=========
''',
'''
   +---+
   |   |
   O   |
       |
       |
       |
=========
''',
'''
   +---+
   |   |
   O   |
   |   |
       |
       |
=========
''',
'''
   +---+
   |   |
   O   |
  /|   |
       |
       |
=========
''',
'''
   +---+
   |   |
   O   |
  /|\  |
       |
       |
=========
''',
'''
   +---+
   |   |
   O   |
  /|\  |
  /    |
       |
=========
''',
'''
   +---+
   |   |
   O   |
  /|\  |
  / \  |
       |
=========
''',
'''
   +---+
   |   |
  [O   |
  /|\  |
  / \  |
       |
=========
''',
'''
   +---+
   |   |
  [O]  |
  /|\  |
  / \  |
       |
=========
'''
]

class HangmanGame():
    def __init__(self, word_list):
        self.word_list = list(word_list) # list contains our words
        self.missed = 0   # how many times player've missed
        self.secret_word = "" # what is the secret word
        self.correct_letters = {}  # dictionary, correct letters and their indexes
        self.missed_letters = []  # letters that are not in secret_word
        self.MAXIMUM_GUESSES = len(HANGMAN_PICS)-1
        self.ENDED = False   # is the game ended?
        self.game_state = 'CONTINUE' # player wins or loses

    def get_random_word(self):
        # return a random string from a list of words
        return self.word_list[random.randint(0, len(self.word_list)-1)]

    def display_board(self):
        print HANGMAN_PICS[self.missed]
        # print incorrect guesses
        print "Missed letters: " + ''.join(self.missed_letters)
        # print secret word
        for _ in range(len(self.secret_word)):
            if _ in self.correct_letters:
                print self.correct_letters[_],
            else:
                print '_',
        print

    def get_guess(self):
        guess = ''
        # get guess of player
        while not guess.isalpha():
            print 'Guess a letter:',
            guess = raw_input().strip()
            # if the letter already have been guessed
            if guess in self.correct_letters.values() or guess in self.missed_letters:
                print "you've already guessed that letter. Choose again"
                guess = ''
        # the letter is in the secret word
        if guess in self.secret_word:
            for (index, c) in enumerate(self.secret_word):
                if c == guess:
                    self.correct_letters[index] = c
            if len(self.correct_letters) == len(self.secret_word):
                # player wins
                self.game_state = 'WIN'
        else: # the letter is not in the secret word
            self.missed_letters.append(guess)
            self.missed += 1
            if self.missed >= self.MAXIMUM_GUESSES:
                # player loses
                self.game_state = 'LOSE'

    def play_again(self):
        # ask if player want to play more
        choice = ''
        print 'Do you want to play again? (y,n)'
        choice = raw_input().strip()
        if choice == 'y' or choice == 'yes':
            self.ENDED = False
            # reset the game
            self.reset()
        else:
            self.ENDED = True

    def reset(self):
        self.missed_letters = []
        self.correct_letters = {}
        self.missed = 0
        self.secret_word = ""
        self.game_state = 'CONTINUE'

    def start_game(self):
        while not self.ENDED:
            # get secret word
            self.secret_word = self.get_random_word()
            while self.game_state == 'CONTINUE':
                # display board
                self.display_board()
                # ask player to take a guess
                self.get_guess()
                # check if player wins or loses
                if self.game_state == 'WIN':
                    print 'Congrats! You win.'
                    print 'And the secret word is: ' + self.secret_word
                if self.game_state == 'LOSE':
                    # print the 'full' hangman
                    print HANGMAN_PICS[self.missed]
                    print "Too bad, you lose!\n"
                    print 'The secret word is ' + self.secret_word
            # game ended, ask if player want to play again
            self.play_again()
        print "See ya later."

if __name__ == '__main__':
    words = 'ant baboon badger bat bear beaver camel cat clam cobra ' \
            'cougar coyote crow deer dog donkey duck eagle ferret fox ' \
            'frog goat goose hawk lion lizard llama mole monkey moose ' \
            'mouse mule newt otter owl panda parrot pigeon python rabbit ' \
            'ram rat raven rhino salmon seal shark sheep skunk sloth snake ' \
            'spider stork swan tiger toad trout turkey turtle weasel whale ' \
            'wolf wombat zebra'.split()
    game = HangmanGame(words)
    game.start_game()

 

Advertisements