nemrod.se Various guides and experiments

Hangman in Python


This is a refurbished version of a Python script I wrote on Dreamhack many years ago. It’s pretty simple, there is an array of words that it randomly selects one from and then you can guess. It displays the word with underscores as placeholders for unknown characters, with the real characters where they’re supposed to be if you’ve guessed them right.

It also displays wrong guesses and ASCII art of the classic hangman scenery according to how many times you’ve guessed on a wrong letter. You can change the ASCII file without affecting the game, just remember to keep every scene on ten lines. You can add more scenes (10 lines per scene) to the file and the game will adjust accordingly, not letting the game end until you get to the last scene.

It uses a wide range of methods and tricks in Python, such as list comprehension and shorthand if, so it might be fun to learn from. For example, this is how it prints the scenery:

    file = open('ascii', 'r')
    hangman = file.readlines()
    print ''.join([line for line in hangman[len(wrong) * 10:len(wrong) * 10 + 10]])

and this is how it prints the word (letter or underscore):

    for letter in word:
        print letter if letter in right else '_ ',

It’s also only about 45 lines of code (30-35 SLOC I guess), so it’s not very much code to look at. :)

It’s free as in free speech (and free beer) so you have no restrictions regarding usage or modifications to it, but it’s always nice to hear from anyone using what you make so feel free to post a comment or send me a mail. Any bug fixes, improvements or other additions would be neat to get so I can host the new version here. :)

hangman.py
ascii art of hangman, required to play


Posted in Projects | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *