Building Rock Paper Scissors Game in Python!

Rock Paper Scissors Feature Img

Oh, hello again gaming coder! Today I will be guiding you on how to build a simple Rock Paper Scissors game all by yourself.

Are you ready? Let us begin!

Introduction to the Rock Paper Scissors Game

Before building any new game, one needs to understand all about the game including its rules, inputs, and outputs, and all the necessary things.

How to play the game?

Rock paper scissors is one of the classic hand games we have been playing since we were all small kids. It is typically played between two players (can be played with more than two players as well) each one forming one of three shapes (rock, paper, and scissors) at the same time, with an extended hand.

How to form hand gestures for the options?

Rock is represented by a closed fist; paper is represented by a flat hand and the scissors are represented by forming a V (the popular peace signal). An illustration of the gestures is shown in the image below.

Rock Paper Scissors Shape
Rock Paper Scissors Shape

Recommended read: Graphical Hi-lo game in Python

Rules of the Game

Although the coding part of the game can get a little complex the game rules are simple which are as follows:

  1. Rock wins against scissors.
  2. Scissors win against the paper.
  3. Paper wins against the rock.

Building Rock Paper Scissors in Python

We will divide the whole game building into parts to make it simple for you! All the steps we will be taking for building the game are mentioned below:

  1. Importing all the necessary modules
  2. Printing Greeting Messages and asking the player about how it wants to play the game.
  3. Creating separate functions for the following purposes:
    • Draw the Hand Diagrams
    • Play with the Computer!
    • Play with a Friend!

Step 1 – Importing the necessary modules.

We make use of a few modules while building the game. Let me introduce you to them one after another.

  1. Random module: It is a built-in module used to generate random objects be it integers, floating-point numbers, or other objects.
  2. Getpass module: Getpass module is typically used to get passwords from the users but in the game, the same is used to hide the input of player 1 from player 2 for a fair game.

To import the modules we use the following code:

import random
import getpass

Step 2 – Printing Greeting Messages and asking the player about how it wants to play the game.

It is advisable for a game builder to greet the player before the game begins. Better greeting messages makes your game better than the other developers of the same game. After greeting the player is asked if it wants to play with the computer or a friend or wants to simply exit the game.

In our case we will define a function storing all the greeting information. The code for the same is shown below:

def Info ():
    print ("\tHELLO THERE! WELCOME TO ROCK PAPER SCISSORS GAME!")
    print ("INSTRUCTIONS:\nBoth the players have three choices namely rock, paper and scissors.")
    print ("\nGAME RULES:")
    print ("\tSCISSORS beats PAPER")
    print ("\tPAPER beats ROCK")
    print ("\tROCK beats SCISSORS")
    print ("--------------------------------------------------------------------------")
    print ("Choose between the two options: ")
    print ("\t 1. Play with the computer")
    print ("\t 2. Play with a friend")
    print ("\t 3. Exit Game")

When the `Info` function is called it prints the information in the pattern shown below:

Info Rock Paper Scissors
Info Rock Paper Scissors

After the method of playing is chosen the player is asked about the no of rounds the player wants to play for with either the computer or a friend. Some things one must take into consideration is the number of rounds should be an integer and the player choice of method of gameplay should be valid as well.

The code for the same whole starting process of the game is shown below.

Info ()
choices = ["rock","paper","scissors"]
wrong = True
while wrong:
    try:
        n= int (input ("Enter your choice of Gameplay: "))
        if(n==1):
            wrong = False
            x = int (input ("Enter number of rounds you want to play: "))
            begin_game_computer(x)
        elif(n==2):
            wrong = False
            x = int (input ("Enter number of rounds you want to play: "))
            begin_game_friend(x)
        elif(n==3):
            wrong=False
            print ("\nThank you for playing! \nBye!")
        else:
            print ("Choose Again!")
    except (ValueError):
        print ("INVALID INPUT! Choose Again!")
        wrong=True

Let us understand what exactly is happening here. First, we called the Info function to greet the player and then we make use of the Python Exceptions to handle the necessary things.

If the player choses to play with the computer, then ‘begin_game_computer’ function is called and in the same way if the player choses to play with a friend, then ‘begin_game_friend’ function is called.

Step 3 – Creating the separate functions for various purposes.

Now a major step in building the game is defining the required functions for the proper working of the game. Let us build all the projects from the scratch.

1. Defining the function to draw the hand diagrams.

To make the game more interactive for the player, we will make use we define a function which prints the write hand diagram mapped to the right option chosen.

The code for the same is as follows:

def draw_diagrams(ch):
    if(ch=="rock"):
        print("""
                _______
            ---'   ____)
                  (_____)
                  (_____)
                  (____)
            ---.__(___)
            """)
    elif(ch=="paper"):
        print("""
                 _______
            ---'    ____)____
                       ______)
                      _______)
                     _______)
            ---.__________)
            """)
    elif(ch=="scissors"):
        print("""
                _______
            ---'   ____)____
                      ______)
                   __________)
                  (____)
            ---.__(___)
            """)
    else:
        print("WRONG INPUT! CHOOSE AGAIN PLEASE!\n")

2. Defining the function to play with the computer.

Before explaining anything, let me show the code first and explain it properly.

def begin_game_computer(n):
    score1=0
    score2=0
    for i in range(n):
        print("---------------------------------------------------------------------------")
        print("ROUND NUMBER: ",i+1)
        check = True
        while check:
            p_ch = input("Choose your option: ")
            if(p_ch.lower() in choices):
                check=False
            else:
                print("Wrong Input! Enter Again!")
        c_ch = choices[random.randint(0,2)]
        
        print("\nYOUR CHOICE: ")
        draw_diagrams(p_ch.lower())
        print("\nCOMPUTER's CHOICE: ")
        draw_diagrams(c_ch.lower())
        
        winner = check_win(p_ch,c_ch)
        if(winner==1):
            print("YOU WIN THE ROUND HURRAY!\n")
            score1+=1
        elif(winner==2):
            print("Oh no! Computer wins the round!\n")
            score2+=1
        else:
            print("DRAW ROUND!\n")
    print("---------------------------------------------------------------------------")
    print("FINAL SCORES ARE AS FOLLOWS: ")
    print("YOUR SCORE: ",score1)
    print("COMPUTER's SCORE: ",score2)
    if(score1>score2):
        print("---------------------------------------------------------------------------")
        print("HURRAY YOU WIN! Congratulations!")
        print("---------------------------------------------------------------------------")
    elif(score1<score2):
        print("---------------------------------------------------------------------------")
        print("Computer wins this time! Better Luck next time!")
        print("---------------------------------------------------------------------------")
    else:
        print("---------------------------------------------------------------------------")
        print("It's a draw game!")
        print("---------------------------------------------------------------------------")

Now let’s understand the whole information closely. This function plays an important role in the game so try to understand this function properly.

We make two variables score1 and score2 to store the scores of the two players ( in this case player 2 is computer). Now a loop is run for the total no of rounds and for each round we make sure to include a three things:

  1. The input of both the players: For the computer we define a list having all three options and using the random library the computer chooses a random option out of the three.
  2. Checking who wins the round: To check who won the round we make use of a separate function which takes both the inputs as arguments and return which player won ( 1 or 2). The code for the winner check function is shown below:
def check_win(c1,c2):
    if(c1=='rock' and c2=='paper'):
        return 2
    elif(c1=='paper' and c2=='rock'):
        return 1
    elif(c1=='paper' and c2=='scissors'):
        return 2
    elif(c1=='scissors' and c2=='paper'):
        return 1
    elif(c1=='rock' and c2=='scissors'):
        return 1
    elif(c1=='scissors' and c2=='rock'):
        return 2
    elif(c1==c2):
        return 0  
  1. Updating the score values: The next step is to increase the score of the first and second player if either of them wins and nothing happens if there is a draw.

This same procedure is repeated for the no of rounds mentioned by the player. And then we show the final scores of both the computer and the player and compare the scores to let the player know who won the game!

3. Defining the function to play along with a friend.

Playing the game with a friend is exactly same as that with a computer. The only difference is that in this case instead of taking the second input randomly we will take two inputs.

Another small change we make here is that before the second player enters its choice we hide the first player’s response. For the same we make use of the getpass method.

Let me show you how the code for playing along with friend looks like:

def begin_game_friend(n):
    score1=0
    score2=0
    for i in range(n):
        print("---------------------------------------------------------------------------")
        print("ROUND NUMBER: ",i+1)
        
        check = True
        while check:
            p1_ch = getpass.getpass(prompt="Choose your option player 1: ",stream=None)
            if(p1_ch.lower() in choices):
                check=False
            else:
                print("Wrong Input! Enter Again!")
        
        check = True
        while check:
            p2_ch = input("Choose your option player 2: ")
            if(p2_ch.lower() in choices):
                check=False
            else:
                print("Wrong Input! Enter Again!")
        
        print("\nPLAYER 1 CHOICE: ")
        draw_diagrams(p1_ch.lower())
        print("PLAYER 2 CHOICE: ")
        draw_diagrams(p2_ch.lower())
        
        winner = check_win(p1_ch,p2_ch)
        if(winner==1):
            print("Player 1 wins the round!\n")
            score1+=1
        elif(winner==2):
            print("Player 2 wins the round!\n")
            score2+=1
        else:
            print("DRAW ROUND!\n")
    
    print("---------------------------------------------------------------------------")
    print("FINAL SCORES ARE AS FOLLOWS: ")
    print("PLAYER 1 SCORE: ",score1)
    print("PLAYER 2 SCORE: ",score2)
    if(score1>score2):
        print("---------------------------------------------------------------------------")
        print("PLAYER 1 WINS! Congratulations!")
        print("---------------------------------------------------------------------------")
    elif(score1<score2):
        print("---------------------------------------------------------------------------")
        print("PLAYER 2 WINS! Congratulations")
        print("---------------------------------------------------------------------------")
    else:
        print("---------------------------------------------------------------------------")
        print("It's a draw game!")
        print("---------------------------------------------------------------------------")

Final Ouputs

Congratulations! We are all set to run the game now! Let me show you a sample result of 2 rounds both with computer and along with a friend.

Test RPS Round With Computer
Test RPS Round With Computer
Test RPS Round With Friend
Test RPS Round With Friend

Conclusion

I hope you were able to successfully build and understand the whole game building! Congratulations!
Now you know about how to create logic for rock paper scissors game, you can build some other games yourself!

Thank you for reading! Happy coding!