So you want to play Hangman on the Command Line, but you're new to Python? This is one of many, many ways to do it. This particular program was written in Python 2.7.

First thing's first. We need to create a list of words that we'll randomly pull from for each game. 

import random
import string
word_list = ["Awkward", "Bagpipes", "Banjo", "Bungler", "Croquet", "Crypt", "Dwarves", "Fiery", "Fishhook", "Fjord",
            "Gazebo", "Gypsy", "Haiku", "Haphazard", "Hyphen", "Ivory", "Jazzy", "Jiffy", "Jinx", "Jukebox", "Kayak",
            "Oxygen", "Pajama", "Phlegm", "Polka", "Quad", "Quip", "Sarcastic", "Rhythmic", "Zealous", "Wildebeast"]

The import statements are for functions later on in the program. Random will be used to - you guessed it - pull a random word from the word_list arrayString is used for manipulation later on.

Next, we need to set up the max number of wrong guesses before the game is over, and the player loses. I put 6 as default, because of 6 body parts.

max_wrong_guesses = 6

 

Now for the fun part - the functions. First, we pull a random word from the word_list array:

def get_word():
    return(word_list[random.randint(0,len(word_list))].lower())

All we're doing there is returning the word in word_list that is at the index of a random integer between 0 and the length of word_list. Then, we make it all lower case for checking later.

Next, we get a guess from the user:

def get_letter(guesses):
    while True:
        guess = raw_input("What is your guess? ").strip().lower()
        if len(guess) == 1 and guess in string.letters:
            if guess in guesses:
                print("You've already guessed {}, try again! ".format(guess))
                continue
            else:
                break
        else:
            print("Try again, but this time with ONE letter.")
            continue
    return guess

We make a loop that goes until we have a valid guess. If the user guesses multiple letters, or a letter that was already guessed, they get told that they're wrong. 

So, now we have a list of possible words, a maximum number of wrong answers, a random word from the list, and a letter from the user. Great! So, now what? Now, we need to do a few more checks. 

The first check is if the user has ran out of guesses.

def has_guesses(num):
    if num <= max_wrong_guesses:
        return True
    else:
        return False

It's a super simple function. We pass it a number, and check it against the max number of wrong guesses. If it's less than or equal to, we know the user has at least one more guess. Otherwise, they're out of guesses and they've lost.

The next check is seeing if the word has been guessed already.

def guessed_word(word, guesses):
    return set(word) <= set(guesses)

This just lets us know if all of the letters in the word are in the list of guesses the user has input.

So, the user has lost or won the game. Do they want to play another one? Let's find out!

def play_again(prompt):
    while True:
        value = raw_input(prompt).strip().lower()
        if value == "yes" or value == "y" or value == "no" or value == "n":
            break
        else:
            print("This is a yes or no question. Try again!")
            continue
    if value == "yes" or value == "y":
        return True
    return False

Admittedly, that if statement is a little messy. However, this is a simple sanity check. If the user types anything except "Yes","Y","No", or "N" (case insensitive), they get told to try a solid answer. Then, if they want to play again, the game starts again (code is later on).

Finally, our last little tidbit before getting into the game function itself. We have all this information - guesses left, guesses made, the word to guess, etc. What do we do with it? This function just prints out the current guesses, as well as number of blank spaces, in the word. For instance, if the word was "Hello", and the user has guessed "H,I,J,O", then the result from this function would be "H _ _ _ O". 

def printWord(word, guesses):
    result = ''
    for char in word:
        if char in guesses:
            result += ' {} '.format(char)
        else:
            result += '_ '
    print(result)

Okay, so we have all the logic and miscellaneous functions complete. All that's left, at this point, is to create the game function itself.

"while True" is called the "Game Loop". Basically, this keeps the program running until we tell it to stop.

In the loop, we just call our has_guesses function from earlier, and check if the user has run out of guesses. If they haven't yet, we get another letter from them. I feel like this function is mostly self-explanatory. If there's any confusion, send me an email or comment below!

def start_game():
    numGuesses = 0
    guesses = []
    current_word = get_word()
    while True:
        printWord(current_word, guesses)
        if has_guesses(numGuesses):
            current_guess = get_letter(guesses)
            guesses.append(current_guess)
            if current_guess in current_word:
                print(current_guess)
            else:
                if numGuesses < max_wrong_guesses:
                    print("Wrong! You have {} guesses remaining.".format(max_wrong_guesses-numGuesses))
                numGuesses += 1
            print("You have guessed {} so far. \n". format(guesses) )
            if guessed_word(current_word, guesses):
                again = play_again("Congratulations, you guessed '{}' correctly! Would you like to play again? ".format(current_word.capitalize()))
                if again:
                    numGuesses = 0
                    guesses = []
                    current_word = get_word()
                else:
                    break
        else: # Out of guesses
            again = play_again("Out of guesses! The word was {}. Would you like to play again? ".format(current_word.capitalize()))
            if again:
                numGuesses = 0
                guesses = []
                current_word = get_word()
            else:
                break

 

Finally, we call the start_game() method when the file is ran so we can actually play!

start_game()

 

The full source code can be found on GitHub.

Tags
Category