Create a rock paper scissors game in python tutorial

Rock paper scissors is a hand game that’s typically played between two people. The game works in that each player simultaneously forms one of three hand gestures with an outstretched hand. The shapes are rock (closed fist), paper (flat hand), or scissors (a closed fist with an index finger and middle finger extended).

The rules are as follows:

  • Rock vs Scissors: Rock wins because rock smashes scissors.
  • Rock vs Paper: Paper wins because paper covers rock.
  • Scissors vs Paper: Scissors win because scissors cut paper.
  • Everything else is a tie.

Let’s think of the elements we need in order to model a rock-paper-scissors text based game in python:

  1. Need to display the rules of the game to the player.
  2. Need to provide the options that a player can choose from.
  3. Need to keep track of the score.
  4. Need a way to get input from the player.
  5. Need a way to determine the winner based on options entered.
  6. Need a way to repeat the game until the player wants to terminate.

Let’s translate the above steps into python code, and then once we have it we can assemble the full program together. Since this is just a simple text based game we just need to import the random module.

1) This can be accomplished by using a simple print statement as follow:

game_rules = ('\n'
              'Rock paper scissors game rules:\n\n'
              'R = Rock, S = Scissors, P = Paper\n'
              'R vs R = tie\nP vs P = tie\nS vs S = tie\n'
              'R vs P = P wins\n'
              'S vs P = S wins\n'
              'R vs S = R wins\n'
              '________________\n')

2) We can add the options in a list as shown below:

options = ['R', 'P', 'S']

We can then select the appropriate items in the list by using the following:

computer = random.choice(options)

Therefore, putting it in a simple python script would look something like the following:

>>> import random
>>> options = ['R', 'P', 'S']
>>> computer = random.choice(options)
>>> computer
'S'

The choice() method is a method in the random class that allows you to randomly select an element from a sequence.

3) One way we can do this is by storing the data in a dictionary to map keys to values. For example, if we want to keep track of the scores of you, the computer, and the number of draws, we can create a simple dictionary as follows:

x, y, z = 0, 0, 0
score = {'you': x, 'computer': y, 'draw': z}

If we need to update the score after each win we can use the += operator as shown below:

score['computer'] += 1
score['you'] += 1
score['draw'] += 1

4) We can receive input from the user by using the input() function. An example of it in action is as follows:

start = input().upper()

The reason why we’re chaining the input() function with the upper() function so that we can make sure that the input entered is capitalized. For example, if we want to do something like the following:

if start == 'Y':
    body statements

If start is equal to ‘y’ then the following won’t do anything. So, for simplicity sake we can make y map to Y, and n (No) map to N.

5) This can be done by using builtin conditional constructs such as if, elif, and else statements. For example, let’s go back to the rules of rock paper scissors. What would you do if you wanted to decide the winner of rock vs scissors? We could do something like the following:

>>> import random
>>> x, y, z = 0, 0, 0
>>> score = {'you': x, 'computer': y, 'draw': z}
>>> options = ['R', 'P', 'S']
>>> computer = random.choice(options)
>>> you = input().upper()
r
>>> if you == 'R' and computer == 'S':
...     print('Computer chooses {}'.format(computer))
...     print('You win! Rock smashes Scissors!')
... elif you == 'R' and computer == 'P':
...     score['computer'] += 1
...     print('Computer win! Paper covers rock!')
... else:
...     score['draw'] += 1
...     print('Looks like a tie!')
... 
Looks like a tie!
>>> you
'R'
>>> computer
'R'
>>> 
>>> score
{'you': 0, 'computer': 0, 'draw': 1}

The computer element is stored in the computer variable. The player can enter their input after the following statement:

>>> you = input().upper()

Make sure that when you enter the input, don’t add single or double quotes because that will modify your input so that it never matches any of the options.

6) This can be done with a while loop:

while True:
    body statements

Then, we can add in our conditionals to determine the winner of each round contingent on the user input. However, to give the script some maintainability we can wrap all of that up into a function like run() as indicated below:

def run():
    while True:
        body statements

However, we need a way to terminate the game just in case the user doesn’t want to play anymore. There’s a couple of ways to do this, but one solution is to add in a condition that exits if the user enters a certain letter like ‘x’. Another solution is to exit if invalid input is entered as indicated below:

you = input().upper()
        if you == 'X':
            print("Time to exit...")
            print('your score = {} computer score = {} draws = {}'.
                      format(score['you'],score['computer'],score['draw']))

Also, if we wrap up our core logic in the run() function, then we need a way to start the game. One solution is as follows:

start = input().upper()
if start == 'Y':
    run()
elif start == 'N':
    print('You''\'ve entered {} so exiting...'.format(start))
else:
    print('You''\'ve entered {} which is invalid so exiting..'
          '.'.format(start))

In other words, once the program is running, if the user selects ‘Y’ then the run() function is called and the logic is executed. Otherwise, if N or some other letter is entered then the program never starts. The user will have to run the program again in order to start the game. The full program for rock paper scissors in python is listed below:

# Rock paper scissors text game implementation
# Written in python 3.6
# Written by Doug Purcell
# The player can play an unlimited number of times,and
# then the score will be tracked at the end.
#
################################################

import random
you = ''
options = ['R', 'P', 'S']
def run(games = 1):
    """ game loop """
    print('Welcome to Rock Paper Scissors in Python:')
    print('PLAY by typing one of the following below: \n R -> Rock\n P -> '
          'Paper\n ' 'S -> Scissors')
    x, y, z = 0, 0, 0
    score = {'you': x, 'computer': y, 'draw': z}
    while True:
        print('Round # {}. Do you choose \'R\', \'P\', or \'S\'?'.
            format(games))
        games += 1
        computer = random.choice(options)
        you = input().upper()
        if you == 'X':
            print("Time to exit...")
            print('your score = {} computer score = {} draws = {}'.
                      format(score['you'],score['computer'],score['draw']))
            exit(0)
        elif not(you == 'R' or you == 'S' or you == 'P'):
            print("\n{} is invalid input!".format(you))
            print('your score = {} computer score = {} draws = {}'.
                  format(score['you'],score['computer'],score['draw']))
            print("EXITING...")
            exit(0)
        else:
            if you == 'R' and computer == 'R':
                score['draw'] += 1
                print('Computer chooses {}'.format(computer))
                print('DRAW')
            elif you == 'P' and computer == 'P':
                score['draw'] += 1
                print('Computer chooses {}'.format(computer))
                print('DRAW')
            elif you == 'S' and computer == 'S':
                score['draw'] += 1
                print('Computer chooses {}'.format(computer))
                print('DRAW')
            elif you == 'R' and computer == 'P':
                score['computer'] += 1
                print('Computer chooses {}'.format(computer))
                print('Computer wins! Paper covers Rock!')
            elif you == 'R' and computer == 'S':
                score['you'] += 1
                print('Computer chooses {}'.format(computer))
                print('You win! Rock smashes Scissors!')
            elif you == 'P' and computer == 'R':
                score['you'] += 1
                print('Computer chooses {}'.format(computer))
                print('You Win! BOOM. Paper covers Rock!')
            elif you == 'S' and computer == 'R':
                 score['computer'] += 1
                 print('Computer chooses {}'.format(computer))
                 print('Computer wins! Rock smashes Scissors!')
            elif you == 'P'and computer == 'S':
                score['computer'] += 1
                print('Computer chooses {}'.format(computer))
                print('Computer wins! Ouch. Scissors cut Paper!')
            elif you == 'S' and computer == 'P':
                score['you'] += 1
                print('Computer chooses {}'.format(computer))
                print('You win! Scissor slices Paper!')
game_rules = ('\n'
              'Rock paper scissors game rules:\n\n'
              'R = Rock, S = Scissors, P = Paper\n'
              'R vs R = tie\nP vs P = tie\nS vs S = tie\n'
              'R vs P = P wins\n'
              'S vs P = S wins\n'
              'R vs S = R wins\n'
              '________________\n')
print(game_rules)
print('Want to play? Hit \'Y\' to play or \'N\' to exit\n')
start = input().upper()
if start == 'Y':
    run()
elif start == 'N':
    print('You''\'ve entered {} so exiting...'.format(start))
else:
    print('You''\'ve entered {} which is invalid so exiting..'
          '.'.format(start))
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.