Tuesday 7 May 2013

Basic Python - Rock Paper Scissors

When thinking about ideas for a Python tutorial I remembered the old game, Rock Paper Scissors. This is a fun game to write in Python and includes loads of concepts, so makes it an ideal beginner program to write.

Lets think first of all how we would structure our program.

  • Firstly a human will need to make a choice of Rock, Paper or Scissors.
  • Secondly the computer will need to make its choice, this will need to be random.
  • These two choices need to be compared.
  • Finally the winner needs to be declared.

I have written this in Python 2.7.

To load Python 2.7 click on the IDLE icon on the desktop.

This should open the following window




Then click on File then New Window to get to the stage where you can start to enter your program.



So lets look into how we can write this.

The first thing is you need to make a choice. Lets write this as a function, which we can call later. Remember the idea behind a function is not complicated. Its just a series of instructions you can call any time.

Lets call the function makeYourChoice()

def makeYourChoice():



We want to be able to ask for the user input so they can choose between Rock, Paper and Scissors. Perhaps also we might want to add an option to quit, as I guess our game will keep running until we want to leave it.

Lets tell the person playing the game what we would like them to input for each choice. I have suggested R to be typed for Rock, P for Paper and S for Scissors. Q sounds about right for quit. Note the indent of a tab (4 spaces) before each of these lines, as we are inside our function.

    print "Press R for Rock"
    print "Press P for Paper"
    print "Press S for Scissors"
    print "Press Q to Quit!"



Now we have asked the user what they would like to choose we need to get them to input their choice. The raw_input command is what you need for this. So underneath your last line enter.

    userChoice = raw_input("What do you want to choose?").lower()


So this line creates a variable userChoice. Into this variable it adds the input the user enters. At the same time it shows some text explaining what it is the program is expecting the user to enter. Finally, I have converted whatever is entered into lower case text with .lower(). This way, I know if the user enters upper or lower case, I will only be dealing with lower case.

So we have given the user a list of options, and asked them to make a choice. We can see we will have an r,p,s or q stored in our variable userChoice.

To make it a little easier later on, lets turn the r,p & s into the words "Rock", "Paper" and "Scissors"

For Rock we want to say if the user has chosen 'r' let the function return "Rock" to be used in the rest of the program.

    if userChoice == "r":
        return "Rock"


Remember putting r and Rock inside " " or ' ' indicates it is a string of letters we are dealing with.

So thats the option for Rock so this needs repeating for Paper and Scissors. Why not try programming those yourself? Is this what you typed?




The last option is q for quit. Well if the user wants to quit, we don't want to return anything to the program, we just want to quit. So lets add a line to do that.

    if userChoice == "q":
        sys.exit(0)



This relies on you having the sys libraries available, so you need to put the following line at the very top of your program.

import sys




Right we have covered the option for Rock, Paper, Scissors and Quit. That's everything, right? Or is it? What if the user was to type something other than the four options? What would our program do then? I think its worth putting something in there in case they do press something else. It is safe to say people don't always follow instructions!

Let us add in something which says if they don't do any of the above, then give them the instructions again. We can use an else statement. These go very well after if commands. It means do all the things in the if statement first, else for all other cases do this.

    else:
        makeYourChoice()



So what we are going to do is say if you have not chosen any of the if statements, run the else statement. The else option tells the computer to run the function we are writing again. We know this is the function which asks people to make their choice, and records it. So if they have that wrong, just ask them again!

Right so that is the first stage finished. There were a few interesting things in there. Firstly the print commands to ask the user to do something. Next we had the raw_input asking the user to enter something, and storing the input into a variable. Finally we had some if statements, and the else statement. These allow choices to be made.

So here is our function in full.



Should we test this now?

We know we are returning either Rock, Paper or Scissors, so lets just run our function with a print statememt to see what it says.

Below our function type the following

print makeYourChoice()



This line will print the output from the makeYourChoice() function.

Now run this program by pressing F5. This will save the program first.

Call the program RockPaperScissors.py when asked.



When asked try typing R. What happens? Run it again and test for P and S.  What about a small p?

Now try something to test our else statement. Type in g. What happened. This was different from R,P or S. What if you type in Rock. Was this expected? Remember our if statements only pick up a R,P or S, so our program sees Rock the same as it sees a g.

Finally run it again and see what happens if you try q for quit?

We have finished with the print makeYourChoice() line so it is no longer required. You can either delete the line or you can place a # in front of the line to make Python ignore it. I am going to delete it.

Thats stage one finished, so we can now move onto stage 2.

Stage 2 is the fact the computer needs to make a choice. What we need to do is get the computer to randomly choose either Rock, Paper or Scissors. Lets write this as a function.

The first thing we need to do is import the random libraries into Python. This allows us to use some pre-programmed commands based on making random decisions. To import random into Python at the very top of the program type

import random



Below the end of the makeYourChoice() function, lets start a new function called computerRandom() which we will use for the computer to make its choice.

def computerRandom():

The first thing we need to do is to give the computer the three options to pick from. Lets store these in a list called options.

    options = ["Rock","Paper","Scissors"]

The options are in a list. The first thing in a list is in position 0, the second in 1 and the third in 2. From this we know that Rock is in position 0, Paper in position 1, and Scissors in position 2. Therefore we need to randomly choose either a 0,1 or a 2.

Lets store the random choice in a variable called randomChoice.

    randomChoice = random.randint(0,2)

random.randint(0,2) calls upon the random libraries you have imported into your program. This command randomly chooses an integer between 0 and 2. An integer can only be a whole number so the overall option is either a 0, 1 or a 2. Which is what we required.

Finally lets return our option. We want to return Rock, Paper or Scissors and not a 0,1 or a 2.

    return options[randomChoice]

Your function should look like this:



Lets look at that last line in a little more detail.

return options[Randomchoice] takes the random choice, which is a 0,1 or a 2 and maps this into the options list which is either a Rock, Paper or Scissors.

options [0] would return Rock, options[1] would return Paper and options[2] would return Scissors.

The third stage is to carry out a comparison. Again lets write this as a function.

The function is to compare the choice from the player with the computer choice. So lets name the function and create it with two inputs.

def comparison (humanChoice, computerChoice)

If both players have picked the same option then it is a draw. Lets write this as an if statement.

    if humanChoice == computerChoice:
return "Draw"

This states that if both are the same (== denotes this) then the word "Draw" is returned.

The next result is if the player picks Rock and the computer picks paper. Paper beats rock, therefore the computer wins.

Again lets cover that in an if statement

    if humanChoice == "Rock" and computerChoice == "Paper":
        return "Computer Wins"

Lets do something similar for the other options where the computer would win.

  • Player picks Paper and computer picks Scissors
  • Player picks Scissors and computer picks Rock


    if humanChoice == "Paper" and computerChoice == "Scissors":
        return "Computer Wins"
    if humanChoice == "Scissors" and computerChoice == "Rock":
        return "Computer Wins"

Now what if the player were to win? Well we have covered a draw and the computer winning, so everything else has to be the player winning. Lets cover that with an else statement.

    else:
        return "Human Wins"

Your finished comparison function should now look like:



We have now written all our functions for each part of the program, so lets put all this together.

As we know we have an option to quit the game, lets make the game keep going until we decide to quit.

We can do this by putting the main body of the game in a while loop. By saying while True we will remain in the while loop until we decide to quit.

while True:



Lets get the players choice, and the computers choice by calling each of the respective functions.

    humanChoice = makeYourChoice()
    computerChoice =  computerRandom()



So the player and the computer know there is no cheating going on, and also as it makes the game look nicer, lets print out what both have chosen.

    print "You chose", humanChoice
    print "The computer chose", computerChoice



We also have written a function to compare the two choices, which will determine a winner. Lets call this function and store the result in a variable called result.

    result = comparison (humanChoice, computerChoice)



Now we can declare a winner! Lets us the if statements again to do this.

    if result == "Draw":
        print "Its a draw"
    elif result == "Computer Wins":
        print "Unlucky you lost!"
    else: print "Well done you won!"



You can see we have used an if and an else statement as previously. However we also have a elif statement. elif stands for 'else if'. There is a subtle difference between using an if statement and an elif statement. Using elif means you should only get one answer printed in this case. Although an if statement would have worked in this case I wanted to introduce the element of elif.

Finally lets add an extra line to print a space after each game.

print " "



Your whole program should now look like this





Following requests I have decided to make the source code available for this program. Although you have the source code I would suggest you type the program into your computer. This will get you used to dealing with debugging your code.



6 comments:

  1. Replies
    1. Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download Now

      >>>>> Download Full

      Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download LINK

      >>>>> Download Now

      Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download Full

      >>>>> Download LINK Ab

      Delete
  2. Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download Now

    >>>>> Download Full

    Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download LINK

    >>>>> Download Now

    Trevor Appleton: Basic Python - Rock Paper Scissors >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete