Hello World! Putting it all together

0
2811

By Jeff Kazmierski, Copy Editor

Well, hello again! This week in Hello World! we’re applying everything we’ve covered over the past month, throwing in some new stuff, and using our knowledge to develop a slightly more complex game program.

First, though, we’ll need to go over some of the concepts we’ll be using.

Take a look at the program in the sidebar, rps.py. The variable “choices,” declared after the block of comments, is a Python array type called a “dictionary.” Recall from the lesson two weeks ago that in Python there are three types of arrays – lists, tuples and dictionaries. We worked with lists in last week’s lesson and we’ll do tuples next week.  

A dictionary is an unordered list of data pairs stored as a key and value combination. Take a closer look at the variable declaration:

choices = {‘r’:’rock’,     ‘p’:’paper’, ‘s’:’scissors’}

The value to the left of the colon in each entry is the key; the value to the right is the value. Unlike in lists, items stored in a dictionary are accessed by their keys. Dictionaries don’t use indexes. Go ahead and enter the variable “choices” in the IDLE command line, then try this:

>>> choices =     {‘r’:’rock’,     ‘p’:’paper’, ‘s’:’scissors’}

>>> choices[‘r’]    

‘rock’

The same sort of thing happens if you use the other two keys. You can also have Python show a list of either the keys or values in a dictionary:

>>> choices.keys()    

dict_keys([‘p’, ‘s’, ‘r’])    

>>> choices.values()

dict_values([‘paper’, ‘scissors’, ‘rock’])

The rest of the program uses this dictionary set for its major functions.

Enough about dictionaries. Notice how the program is organized into functions? We covered those last week; they’re indicated by the keyword def and contain blocks of code that can be run when needed. You do this by programming the function name like a command, as in:

main()    

which tells Python to execute the code inside the main() function. Take a look at the program.  We won’t go through it line by line, because (hopefully) by now you understand enough about Python to be able to interpret the code and work out what’s happening in each block.

getInput(question):

The first defined function, getInput(question), is a generic function that will be called whenever we need to get input from the user. It takes one argument (the ‘question’ between the parentheses) as a string (remember those?) and returns a single lower-case character.

makeChoice():

The second function, makeChoice(), offers the player a choice of values to enter (rock, scissors or paper), compares the first character ( human[0] ) to the list of keys in choices ( choices.keys() ) and returns it if it’s a valid choice. It takes no arguments (notice the empty parens) and returns one character.

playGame():

The playGame() function looks complicated, but really it’s just calling a bunch of other functions and doing something with the results. It takes no arguments (empty parens again) and returns no variable. It does, however, compare the player’s and computer’s choices (in the if/elif/else block) and tells us who won.

compChoice():

The function compChoice() picks a random number from one to three and returns one of the three keys from choices. That’s all it does.

compare():

The compare(h, c) function determines who won. It compares the human choice ( h ) against the computer’s random result ( c ) and returns an integer value based on the result. If the values are the same, it returns 0. If the human is the winner, it returns 1. If the computer wins, it returns -1. This value is put in the variable result in playGame() , which then prints one of three messages

intro():

The intro() function doesn’t do much. It’s used only once, when the program is executed, and all it does is print a bunch of text. You could just as easily stick the print() statements inside the main() function, but I like to keep them separate.

main():

Finally, the main() function calls intro(), asks the player if he wants to play, calls playGame(), and asks if the user wants to play again. Notice when getInput(question) is called, each instance sends a different string in the place of the variable question.  It’s called by the last line of the program, as we explained last week, because that’s how Python rolls.

That’s the rock-paper-scissors program, in a nutshell. Go ahead and try it out. But, because programming isn’t just about regurgitating code, play around with it. Try one or more of these ideas:

Use a list instead of a dictionary to store the game choices.  

Add variables to track the number of games won and lost. Add more variables to count who won and who lost. Keep a tally of tie games.

Just for fun, as a slightly more advanced project, modify it to play the “Lizard/Spock expansion” game from “Big Bang Theory.” In this variant, you add two values, ‘lizard’ and ‘Spock’. Each option now defeats two others and is defeated by two. The full rules can be seen on Wikipedia (en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock).

How much more complex does the game become if you add two more options?

Good luck, and good programming!

Rock, Paper, Scissors

# rps.py

# a simple rock/paper/scissors game

import random

# the dictionary array ‘choices’ is initialized here

# as a ‘global’ variable so it’s available anywhere

# in the program.

# a dictionary consists of an unordered list of

# key:value pairs bound by curly braces {} and

# separated by commas.

choices = {‘r’:’rock’, ‘p’:’paper’, ‘s’:’scissors’}

# a generic function to obtain any type of input

def getInput(question):

    sel = input(question)

    return sel[0].lower()

# function to obtain choice of rock, paper or scissors

def makeChoice():

    human = ‘ ‘

    # looks for the player’s input in the set

    # of key values in dictionary ‘choices’

    while human not in choices.keys():

        print(“Choose your weapon:”)

        print(”  (r)ock”)

        print(”  (s)cissors”)

        print(”  (p)aper”)

        human = getInput(“: “)

    # this line ensures we return the proper input values

    return human[0].lower()

# function that makes all the action happen

def playGame():

    human = makeChoice()

    # show the user what he chose

    print(“You chose “+choices[human]+”.”)

    comp = compChoice()

    # show the user the computer’s choice

    print(“I choose “+choices[comp]+”.”)

    result = compare(human, comp)

    if result == 1:

        print(“Inconceivable!  You have bested me!”)

    elif result == 0:

        print(“A tie!”)

    else:

        print(“Machine beats man!”)

# function to generate a random choice for

# the computer’s selection

def compChoice():

    comp = random.randint(1, 3)

    if comp == 1: return ‘r’

    elif comp == 2: return ‘p’

    elif comp == 3: return ‘s’

# function to compare the player and

# computer selections and see who wins

def compare(h, c):

    # tie game

    if h == c: return 0

    # player wins

    elif (( h == ‘r’ and c == ‘s’) or

          (h == ‘s’ and c == ‘p’) or

          (h == ‘p’ and c == ‘r’)):

        return 1

    # computer wins

    else: return -1

def intro():

    print(“Welcome, puny human, to the ultimate test”)

    print(“of intellect – Rock, Paper, Scissors!”)

    print(“nYou will pit your tiny human mind against”)

    print(“my superior silicon processor!”)

def main():

    a = ‘ ‘

    intro()

    a = getInput(“Do you want to play a game? “)

    while a == ‘y’:

        playGame()

        a = getInput(“Play again? “)

    print(“Farewell, meatsack.”)

main()

Comments

comments