Rock Paper Scissors In Python


Let's create the game Rock Paper Scissors in Python. We will create 2 games, first, we will create a simple game that can be played in the terminal, and second, we will use the Pygame library to create the same game in a better way.

    Table Of Contents

  1. Game Introduction
  2. Simple Rock Paper Scissors Game In Python
    1. Game setup
    2. Taking Player's Choice And Generate Computer's Choice
    3. Determine the winner
    4. Complete Python Code Of Simple Rock Paper Scissors
  3. Rock Paper Scissors Using PyGame
    1. PyGame Intro
    2. Importing necessary modules
    3. Initialize the game
    4. Load images
    5. Game loop
    6. Initial intro screen
    7. Main game screen structure
    8. Handle Mouse Click
    9. Display choices
    10. Check winner
  4. Complete Pygame Code For Rock Paper Scissors
  5. Conclusion

rock paper scissors in python

Game Introduction (Rock, Paper, Scissors)

Before we start, let's understand the rules of the game and how it is played. Let's start with the game introduction.

Rock, Paper, Scissors is a very famous game in which two players play against each other.

Both the player chose one of the three options: Rock, Paper, or Scissors simultaneously.

Each choice has a different hand gesture, players simultaneously make a hand gesture on some count. Where ✊ is Rock, ✋ is Paper, and ✌️ is Scissors.

Rules of the game:

  1. Rock beats Scissors because it crushes Scissors.
  2. Scissors beat Paper because it cuts Paper.
  3. Paper beats Rock because it covers Rock.

1. Simple Rock Paper Scissors Game In Python

First, we are going to create a simple version of this game that can be played on the command line or terminal.

In the terminal player have to input a number 1, 2, or 3 to give a choice, where 1 is Rock, 2 is Paper, and 3 is Scissors.

Our second player will be the computer itself, it will also randomly a number between 1 and 3.

Based on the choice of the player and the computer, we will determine the winner.


I. Game Setup

We will start the game by creating a file named rock-paper-scissors.py.

Import the random module to generate a random number (we are going to need it later for the computer's choice).

Create a variable PLAY and set it to True. This variable will be used to run the game until the player decides to quit the game.

Now create a python while loop that will run until PLAY is False.

# import random module
# for computer to choose random choice
import random

PLAY = True

while PLAY:
    # all the game code goes here

II. Taking Player's Choice And Generate Computer's Choice

Now all of our code will be inside the while loop.

Print the necessary instructions to the player and ask him to enter his choice and store it in a variable player_turn.

Also, generate a random number between 1 and 3 and store it in a variable computer_turn.

While RUN:
    # print the instructions to the player
    print("\nPlease enter your input:\n\t1: Rock\n\t2. Paper\n\t3: Scissors")
    player_turn = int(input("Choose: "))

    # generate a random number between 1 and 3
    computer_turn = random.randint(1, 3)

It would be nice if you display the choices of both player and computer in the terminal.

Create a dictionary to map the numbers chosen by text. And show rock for 1, paper for 2, and scissors for 3.

While RUN:
    ...

    # map the numbers choosen by text
    choice = {1: "Rock", 2: "Paper", 3: "Scissors"}
    print(f"Player: {choice[player_turn]}\tComputer: {choice[computer_turn]}")

III. Determine The Winner

Now we will determine the winner of the game.

Let's rename the variables player_turn to pt and computer_turn to ct, because we are going to use these variables multiple times. So it's better to use shorter names.

Use the if-else statement and compare the values of pt and ct to determine the winner.

If values are the same then it's a tie. One with rock will win with scissors and one with paper will win with rock. And so on. Check the rules of the game above.

while RUN:
    ...
    # determine the winner
    pt = player_turn
    ct = computer_turn
    if(pt == ct):
        print("It's Tie!")
    elif (pt == 1 and ct == 2):
        print("Paper covers Rock. Computer wins!")
    elif (pt == 1 and ct == 3):
        print("Rock smashes Scissors. Player wins!")
    elif (pt == 2 and ct == 1):
        print("Paper covers Rock. Player wins!")
    elif (pt == 2 and ct == 3):
        print("Scissors cuts Paper. Computer wins!")
    elif (pt == 3 and ct == 1):
        print("Rock smashes Scissors. Computer wins!")
    elif (pt == 3 and ct == 2):
        print("Scissors cuts Paper. Player wins!")

After determining the result of the game, ask the user if they want to continue playing. If yes then continue the loop, else break the loop.

while RUN:
    ...
    # ask the user if they want to continue play
    print("\nDo you want to play again? (y/n)")
    if(input() == "n"):
        PLAY = False
        print("Thank you for playing!")
    else:
        continue

IV. Complete Python Code Of Simple Rock Paper Scissors

Here is the complete code for the game.

# import random module
# for computer to choose random choice
import random

PLAY = True
while PLAY:
    # print the instructions to the player
    print("\nPlease enter your input:\n\t1: Rock\n\t2. Paper\n\t3: Scissors")
    player_turn = int(input("Choose: "))

    # generate a random number between 1 and 3
    computer_turn = random.randint(1, 3)

    # map the numbers choosen by text
    choice = {1: "Rock", 2: "Paper", 3: "Scissors"}
    print(f"Player: {choice[player_turn]}\tComputer: {choice[computer_turn]}")

    # determine the winner
    pt = player_turn
    ct = computer_turn
    if(pt == ct):
        print("It's Tie!")
    elif (pt == 1 and ct == 2):
        print("Paper covers Rock. Computer wins!")
    elif (pt == 1 and ct == 3):
        print("Rock smashes Scissors. Player wins!")
    elif (pt == 2 and ct == 1):
        print("Paper covers Rock. Player wins!")
    elif (pt == 2 and ct == 3):
        print("Scissors cuts Paper. Computer wins!")
    elif (pt == 3 and ct == 1):
        print("Rock smashes Scissors. Computer wins!")
    elif (pt == 3 and ct == 2):
        print("Scissors cuts Paper. Player wins!")

    # ask the user if they want to continue play
    print("\nDo you want to play again? (y/n)")
    if(input() == "n"):
        PLAY = False
        print("Thank you for playing!")
    else:
        continue

The output of the game:

rock paper scissors game output CLI

2. Rock Paper Scissors Using PyGame

Did you play the game above? If yes then you would have understood that playing games on the terminal aren't that fun. So, let's create the same game in PyGame.

First, let's take a brief introduction to PyGame.

PyGame Introduction

PyGame is a Python library used for creating simple games. It is a cross-platform library.

It includes graphics as well as an audio library to design very interactive games.

To install PyGame run the following command in your terminal:

pip install pygame
# or
pip3 install pygame

I. Importing Necessary Modules

We are going to need a few modules to create the game. Let's import them.

# import the necessary modules
import pygame     # for creating the game
from pygame.locals import *
import random     # for generating random numbers
import sys        # for getting the exit code

II. Initialize The Game

Start with creating the necessary variables that we are going to use in the game.

Define 3 colors: WHITE, BLACK, and RED. PyGame uses RGB values to define colors.

After you define the colors, create a display surface. This is the surface that will be used to display the game. Use the pygame.display.set_mode() function to create the display surface.

Set the caption of the game using pygame.display.set_caption() function.

# colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# game settings
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 400
FPS = 30
pg.init()
screen = pg.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pg.display.set_caption("Rock Paper Scissors")

III. Load Images

We are going to use some images within the game. Let's load them.

You can download the entire game with the images below.

To load the images to the game, use the pygame.image.load() function.

Pass the URL of the image to the function. Store the returned image in a variable.

Scale the image to the desired size using the pygame.transform.scale() function.

# load the images
rps_intro = pg.image.load("rps-intro.png")
rock_img = pg.image.load("rock.png")
paper_img = pg.image.load("paper.png")
scissors_img = pg.image.load("scissors.png")

# resize images
rps_intro = pg.transform.scale(rps_intro, (WINDOW_WIDTH, WINDOW_HEIGHT))
rock_img = pg.transform.scale(rock_img, (100, 100))
paper_img = pg.transform.scale(paper_img, (100, 100))
scissors_img = pg.transform.scale(scissors_img, (100, 100))

Here are the images used in the game:

used images in the game

IV. Game Loop

Now, we are going to create the main game loop.

Every Pygame game has the main loop. The main loop is the code that runs continuously until the game is closed.

Inside this main loop, get all the events happening on the game screen using pg.event.get(). Check if the event is of type QUIT then quit the game. If it is a mouse button click then execute the function handle_click() (which we will define later).

# main game loop
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        elif event.type == pg.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pg.mouse.get_pos()
            # handle players's mouse click
            handle_click(mouse_x, mouse_y)

    pg.time.Clock().tick(FPS)

V. Initial Intro Screen

The game will start with the intro screen. Let's create the intro screen.

The intro screen will be nothing but the intro image is loaded to the screen. And wait 1 second before the game starts.

# display the intro screen
def game_intro():
    screen.blit(rps_intro, (0, 0))
    pg.display.update()
    pg.time.wait(1000)

game_intro()

Use the blit() function on the screen to display the intro image.

It accepts two parameters, the image and the position of the image.

The position of the image is specified by the x and y coordinates.

Here is the output of the game when the intro screen is displayed:

rock paper scissor intro

VI. Main Game Screen Structure

The game screen will load after the intro screen. Let's create the game screen.

Make the screen white and add images of the rock, paper, and scissors to the screen in such a way that they are centered.

Create the header of the game with the black background and white text.

Also, display the instruction to the player.

To draw a rectangle using the pg.draw.rect() function that accepts the screen surface, color, and position of the rectangle as arguments.

def draw_structure():
    screen.fill(WHITE)
    screen.blit(rock_img, (50, 100))
    screen.blit(paper_img, (200, 100))
    screen.blit(scissors_img, (350, 100))

    # create game header
    pg.draw.rect(screen, BLACK, (0, 0, WINDOW_WIDTH, 50))
    header_text = pg.font.Font(None, 36).render("Rock Paper Scissors", True, WHITE)
    screen.blit(header_text, (WINDOW_WIDTH // 2 - header_text.get_width() // 2, 15))

    # game instruction
    instruction = pg.font.Font(None, 30).render("Click on the rock, paper or scissors to play!",True, BLACK)
    screen.blit(instruction, (WINDOW_WIDTH // 2 - instruction.get_width() // 2, 60))
    pg.display.update()

draw_structure()

VII. Handle Mouse Click

Our game screen is ready. Let's create the function that handles the mouse click.

The function will accept the x and y coordinates of the mouse click and check if the mouse click is within the rock, paper or scissors image.

If the mouse click is within the rock image, then the player will choose the rock. If the mouse click is within the paper image, then the player will choose the paper. If the mouse click is within the scissors image, then the player will choose the scissors.

If the mouse click is not within any of the images, then the function will do nothing.

def handle_click(x, y):
    if x > 50 and x < 150 and y > 100 and y < 200:
        display_choice("rock")
        return
    elif x > 200 and x < 300 and y > 100 and y < 200:
        display_choice("paper")
        return
    elif x > 350 and x < 450 and y > 100 and y < 200:
        display_choice("scissors")
        return
    else:
        return

Once we have a valid click, we call a function that displays the choice of the player.


VIII. Display Choices

This function will randomly choose the choice of the computer and store it in a variable called computer_choice.

The choices of both the player and computer will be displayed on the screen.

def display_choice(player_choice):
    playmode_font = pg.font.Font(None, 25)
    # display player choice
    player_choice_text = playmode_font.render("You chose: " + player_choice, True, BLACK)
    screen.blit(player_choice_text, (10, 220))

    # display computer choice
    computer_choice = random.choice(["rock", "paper", "scissors"])
    computer_choice_text = playmode_font.render("Computer chose: " + computer_choice, True, BLACK)
    screen.blit(computer_choice_text, (200, 220))

    check_winner(player_choice, computer_choice)

    pg.display.update()

Once choices are displayed, we call a function that checks the winner.


IX. Check The Winner

This function will check the winner of the game.

def check_winner(player_choice, computer_choice):
    if player_choice == computer_choice:
        game_status = "It's a tie!"
    elif player_choice == "rock":
        if computer_choice == "paper":
            game_status = "You lose! Paper covers rock."
        else:
            game_status = "You win! Rock breaks scissors."
    elif player_choice == "paper":
        if computer_choice == "scissors":
            game_status = "You lose! Scissors cut paper."
        else:
            game_status = "You win! Paper covers rock."
    elif player_choice == "scissors":
        if computer_choice == "rock":
            game_status = "You lose! Rock breaks scissors."
        else:
            game_status = "You win! Scissors cut paper."
    else:
        print("Invalid choice!")
    screen.blit(pg.font.Font(None, 40).render(game_status, True, RED), (10, 275))
    
    # show reset button
    reset_button = pg.Rect(150, 320, 200, 50)
    pg.draw.rect(screen, (173, 89, 29), reset_button)
    reset_text = pg.font.Font(None, 30).render("Replay", True, WHITE)
    screen.blit(reset_text, (WINDOW_WIDTH // 2 - reset_text.get_width() // 2, 335))

Once the winner is determined, we display the winner on screen. We also display a reset button that will reset the game.

To create the functionality of the reset button, we need to use the MOUSEBUTTONDOWN event.

Within the main loop create a conditional statement and check if the button is clicked, if yes, then redraw the game screen.

while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        elif event.type == pg.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pg.mouse.get_pos()
            handle_click(mouse_x, mouse_y)

            # reset game
            if mouse_x > 150 and mouse_x < 350 and mouse_y > 320 and mouse_y < 370:
                draw_structure()

Complete Pygame Code For Rock Paper Scissors

Here is the complete code for the game using Pygame.

import pygame as pg
from pygame.locals import *
import random
import sys

# color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# game settings
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 400
FPS = 30
pg.init()
screen = pg.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pg.display.set_caption("Rock Paper Scissors")

# load the images
rps_intro = pg.image.load("rps-intro.png")
rock_img = pg.image.load("rock.png")
paper_img = pg.image.load("paper.png")
scissors_img = pg.image.load("scissors.png")

# resize images
rps_intro = pg.transform.scale(rps_intro, (WINDOW_WIDTH, WINDOW_HEIGHT))
rock_img = pg.transform.scale(rock_img, (100, 100))
paper_img = pg.transform.scale(paper_img, (100, 100))
scissors_img = pg.transform.scale(scissors_img, (100, 100))

def game_intro():
    screen.blit(rps_intro, (0, 0))
    pg.display.update()
    pg.time.wait(1000)

game_intro()

def draw_structure():
    screen.fill(WHITE)
    screen.blit(rock_img, (50, 100))
    screen.blit(paper_img, (200, 100))
    screen.blit(scissors_img, (350, 100))

    # create game header
    pg.draw.rect(screen, BLACK, (0, 0, WINDOW_WIDTH, 50))
    header_text = pg.font.Font(None, 36).render("Rock Paper Scissors", True, WHITE)
    screen.blit(header_text, (WINDOW_WIDTH // 2 - header_text.get_width() // 2, 15))
    instruction = pg.font.Font(None, 30).render("Click on the rock, paper or scissors to play!",True, BLACK)
    screen.blit(instruction, (WINDOW_WIDTH // 2 - instruction.get_width() // 2, 60))
    pg.display.update()

draw_structure()

def handle_click(x, y):
    if x > 50 and x < 150 and y > 100 and y < 200:
        display_choice("rock")
        return
    elif x > 200 and x < 300 and y > 100 and y < 200:
        display_choice("paper")
        return
    elif x > 350 and x < 450 and y > 100 and y < 200:
        display_choice("scissors")
        return
    else:
        return

def display_choice(player_choice):
    playmode_font = pg.font.Font(None, 25)
    # display player choice
    player_choice_text = playmode_font.render("You chose: " + player_choice, True, BLACK)
    screen.blit(player_choice_text, (10, 220))

    # display computer choice
    computer_choice = random.choice(["rock", "paper", "scissors"])
    computer_choice_text = playmode_font.render("Computer chose: " + computer_choice, True, BLACK)
    screen.blit(computer_choice_text, (200, 220))

    check_winner(player_choice, computer_choice)

    pg.display.update()

def check_winner(player_choice, computer_choice):
    if player_choice == computer_choice:
        game_status = "It's a tie!"
    elif player_choice == "rock":
        if computer_choice == "paper":
            game_status = "You lose! Paper covers rock."
        else:
            game_status = "You win! Rock breaks scissors."
    elif player_choice == "paper":
        if computer_choice == "scissors":
            game_status = "You lose! Scissors cut paper."
        else:
            game_status = "You win! Paper covers rock."
    elif player_choice == "scissors":
        if computer_choice == "rock":
            game_status = "You lose! Rock breaks scissors."
        else:
            game_status = "You win! Scissors cut paper."
    else:
        print("Invalid choice!")
    screen.blit(pg.font.Font(None, 40).render(game_status, True, RED), (10, 275))
    
    # show reset button
    reset_button = pg.Rect(150, 320, 200, 50)
    pg.draw.rect(screen, (173, 89, 29), reset_button)
    reset_text = pg.font.Font(None, 30).render("Replay", True, WHITE)
    screen.blit(reset_text, (WINDOW_WIDTH // 2 - reset_text.get_width() // 2, 335))

# main game loop
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        elif event.type == pg.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pg.mouse.get_pos()
            handle_click(mouse_x, mouse_y)

            # reset game
            if mouse_x > 150 and mouse_x < 350 and mouse_y > 320 and mouse_y < 370:
                draw_structure()
    pg.time.Clock().tick(FPS)

Click here to download the rock paper scissors game code.

Here is the output of the game.

rock paper scissors in python pygame

Conclusion

In this small journey, you learned to create 2 different rock paper scissors games in python. The first one is a simple text-based game that is played on terminal other is built in the PyGame library.

Why stop now, let's create a tic tac toe game in Python.

Happy Coding! 😇