The personal wiki of ...
Making it Look Like Hangman

It will be more fun if we make our game look like Hangman.

All we need to do is print parts of the poor hangman person when there is a wrong guess. Try adding something like this to the wrong guess part:

... print 'Nope.' print turns, 'more turns' if turns < 5: print ' O ' if turns < 4: print ' \_|_/ ' if turns < 3: print ' | ' if turns < 2: print ' / \ ' if turns < 1: print ' d b ' if turns == 0: print 'The answer is', secret

You can try drawing your own person with punctuation symbols like this. Picking a Random Secret

The only problem with the game is that it always plays the same secret word. We should use the random library to choose a random word.

Add "import random" to the top of your program and change the line that sets up the secret so that it looks like this:

#!/usr/bin/env python

import random

print 'time to play hangman' secret = random.choice(['tiger', 'panda', 'mouse']) guesses = 'aeiou' ...

The square brackets [ ] and commas make a list, and the random.choice picks one thing randomly from the list.

Of course, you can make the list as long as you like. Here is a longer list:

... print 'time to play hangman' secret = random.choice([ 'crocodile', 'elephant', 'penguin', 'pelican', 'leopard', 'hamster', ]) ...

You can write a long list on lots of lines like this, as long as you remember to end any parentheses () and brackets [] that you started. Don't forget to put a comma after each thing in the list. Loading a List from the Internet

I have an even longer list of animals on the internet, at http://davidbau.com/data/animals.

If your computer happens to be connected to the internet, you can load this data in python using a function called "urllib.urlopen". (URLs are what web addresses are called, so urllib stands for "URL library," and urlopen means "open a URL.")

The code looks like this:

import urllib

animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() secret = random.choice(animals)

What this means is:

import urllib Import the library called "urllib" to use. animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() Open up the address http://davidbau.com/data/animals animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() Read the whole webpage into a big string. animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() Split the string into a list of words. animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() Call the whole list "animals". secret = random.choice(animals) Choose a random one and call it "secret."

You can use urllib to load up more data than you could ever type in yourself.

Next
Contact Us | Section Map | Disclaimer | RSS feed RSS FeedBack to top ^

Valid XHTML and CSS | Built on Foswiki

Page Updated: 20 Jan 2012 by ian. © Victoria University of Wellington, New Zealand, unless otherwise stated