Black Friday Sale: Get 50% Off on First Month Fee For All Courses* - Claim your spot now!
Uncategorized

How to Make Rock Paper Scissors Game in Python

Reading Time: 10 mins

Creating a Rock Paper Scissors game in Python is an excellent project for those starting their programming journey. It not only teaches basic Python syntax but also highlights the logic-building skills required for larger projects. By breaking the process into manageable steps, you can build a functional game that’s both simple and engaging. This guide will walk you through the entire process with clear explanations and practical tips.

What You’ll Need?

To begin, make sure your computer is ready for coding. Python is a powerful and user-friendly programming language, and setting it up is straightforward. Here’s what you need:

  • Python Installed: If you haven’t already installed Python, download the latest version from python.org. The installation process is intuitive, and Python’s official site provides detailed instructions for all operating systems.
  • Code Editor: You can use any text editor or IDE (Integrated Development Environment) to write your code. Beginners often find IDLE, the built-in Python editor, useful. More advanced users might prefer VS Code or PyCharm for additional features like syntax highlighting and debugging tools.
  • Basic Python Knowledge: This project assumes you understand variables, conditional statements (if/else), and loops (while or for). If these concepts are new to you, reviewing a Python basics tutorial will be helpful.

Starting with the right tools and a clear understanding of the basics sets the foundation for a smooth coding experience.

How Does Rock Paper Scissors Work?

The rules of the game are simple, making it an ideal beginner project. Each round, the player selects one option from rock, paper, or scissors. The computer then randomly selects its choice. The winner is determined as follows:

  • Rock beats Scissors
  • Scissors beat Paper
  • Paper beats Rock
Image14

When both the player and the computer choose the same option, the round results in a tie. This simplicity allows you to focus on implementing the game logic without being overwhelmed by complexity.

Understanding these rules also helps when writing the code. Each rule translates into a conditional statement, which is the backbone of the game logic. By clearly defining these conditions in the code, you ensure the game behaves as expected.

Step-by-Step Guide to Code the Game

Step 1:Defining the Game Function

The core logic of the game is encapsulated within a function called play_rps().

This function contains all the necessary steps to set up and run the game, making the code modular and reusable.

def play_rps():

Step 2: Game Setup and Welcome Message

The first step is setting up the Python environment and preparing the necessary components for the game. Begin by importing the random module. This module enables the computer to make random choices, mimicking the unpredictability of a real opponent.

import random

The game starts with a welcome message and instructions for the player on how to play.

The player is prompted to enter ‘r’ for rock, ‘p’ for paper, ‘s’ for scissors, or ‘q’ to quit the game.

    print(“Welcome to Rock, Paper, Scissors!”)

    print(“Enter ‘r’ for rock, ‘p’ for paper, or ‘s’ for scissors.”)

    print(“Enter ‘q’ to quit the game.”)

Step 3: Score Tracking

  • Two variables (user_score and computer_score) are initialized to keep track of the number of rounds won by the player and the computer.
  • These scores are updated after each round based on the result (win, lose, or tie).
import random

def play_rps():
   print("Welcome to Rock, Paper, Scissors!")
   print("Enter 'r' for rock, 'p' for paper, or 's' for scissors.")
   print("Enter 'q' to quit the game.")

   computer_score=0
   user score = 0
Image1

Step 4: Game Loop

The main part of the program is a while-loop that continuously runs until the player chooses to quit by entering ‘q‘.

During each iteration of the loop:

  • The computer randomly selects one of the three options (rock, paper, or scissors) using Python’s random.choice() function.

This ensures the computer’s decision is truly random, creating a fair challenge for the player. Displaying the computer’s choice adds transparency and makes the game more engaging.

  • Interacting with the player is a crucial part of the game. The user is prompted to enter their choice.
  • If the user enters ‘q‘, the game exits the loop.
  • If a valid input is entered, the program compares the user’s choice to the computer’s choice to determine the winner of the round.
while True:
   computer = random.choice(['r', 'p', 's'])
   user = input("Enter your choice: ")

      if user == 'q':
         break

    print("Computer chose", computer)
    print("You chose", user)
Image9

Step 5: Determining the Winner

The heart of the game lies in comparing the player’s choice with the computer’s. Use conditional statements to evaluate the outcome:

The program compares the player’s choice and the computer’s choice to determine the outcome:

  • If both choices are the same, it’s a tie.
  • If the computer’s choice beats the player’s (e.g., rock beats scissors), the computer wins.
  • Otherwise, the player wins.

The scores are updated accordingly, and the result of each round is displayed.

if computer == user:
   print("It's a tie!")
elif computer == 'r' and user == 's':
    print("Computer wins!")
    computer_score += 1
elif computer == 'p' and user == 'r':
    print("Computer wins!")
    computer_score += 1
elif computer == 's' and user == 'p':
     print("Computer wins!")
     computer_score += 1
else:
     print("You win!")
     user_score += 1

 

Image4

Each condition corresponds to one of the rules discussed earlier. Breaking these conditions into simple comparisons ensures that the logic is both readable and easy to debug.

Step 6: Displaying Current Scores

After each round, the program prints the updated scores for both the player and the computer, allowing the user to track their progress throughout the game.

if computer== user:
    print("It's a tie!")
elif computer == 'r' and user == 's':
    print("Computer wins!")
    computer_score += 1
elif computer == 'p' and user == 'r':
    print("Computer wins!")
    computer_score += 1
elif computer == 's' and user == 'p':
    print("Computer wins!")
    computer_score += 1
else:
    print("You win!")
    user score += 1

print("You", user_score, "-", computer_score, "Computer")
Image13

Step 7:Ending the Game and Final Winner Declaration

Once the player chooses to quit by entering ‘q‘, the game breaks out of the loop and displays the final scores.

The program compares the total scores of the player and the computer and announces the overall winner based on the final scores.

  • If the user’s score is higher, they win.
  • If the computer’s score is higher, the computer wins.
  • If both scores are equal, the game ends in a tie.
# Compare scores and decide the final winner
print(f"\nFinal score: You {user_score} - {computer_score} Computer")

 if user_score > computer_score:
    print("Congratulations, you are the overall winner!")
elif user_score < computer_score:
     print("Computer is the overall winner. Better luck next time!")
else:
     print("It's a tie overall!")

 

Image3

Step 8: Calling the Game Function

After defining the play_rps() function, it is called at the end of the program to start the game.

This makes the program modular and allows for easy re-execution by calling the function again if needed.

# Start the game
play_rps()
Image8

Step 9 : Adding Enhancements and improving user experiences

  1. User Input Handling: For a better user experience, allowing the user to enter the full words “rock,” “paper,” or “scissors” (in either lowercase or uppercase), we can modify the input handling in the game to accept both formats. This involves converting the user input to lowercase and adjusting the comparisons accordingly.
import random

def play_rps():
    print("Welcome to Rock, Paper, Scissors!")
    print("Type 'rock', 'paper', or 'scissors' to play.")
    print("Type 'q' to quit the game.")

    computer_score = 0
    user_score = 0

    while True:
        # Randomly choose for computer
        computer = random.choice(['rock', 'paper', 'scissors'])
        user = input("Enter your choice (rock, paper, or scissors): ").lower()

        # Exit if user enters 'q'
        if user == 'q':
            break
Image10

The game now expects the user to enter the full words: “rock”, “paper”, or “scissors”. The input is converted to lowercase using .lower() to ensure case insensitivity, so the user can type in any combination of upper or lower case letters.

  • For example, “Rock”, “rock”, or “ROCK” will all be treated as “rock”.

2. Validation: The program checks if the user’s input is valid (either “rock”, “paper”, or “scissors”), and if not, it prompts the user to try again.

# Ensure valid input
if user not in ['rock', 'paper', 'scissors']:
    print("Invalid choice. Please try again.")
    continue
    print("Computer chose", computer)
    print("You chose", user)
Image6

3. Unicode Characters: To further improve the user experience, we can allow the player to choose from a set of symbols (✊ for rock, ✋ for paper, ✂ for scissors) in addition to typing the full words. Users can either copy and paste the symbols into the program directly, or we can use Unicode characters for these symbols.

Step 10: Direct Symbol Input (Copy-Paste Method):

  • The player can directly copy and paste the symbols ✊, ✋, or ✂ when prompted.
  • We will modify the input options to allow for these symbols alongside the words.

Unicode Characters:

  • The symbols can also be represented by their corresponding Unicode characters in Python. The player can input either the word (“rock”, “paper”, “scissors”) or the symbol (✊, ✋, ✂), and the program will handle both formats.
import random

def play_rps():
    print("Welcome to Rock, Paper, Scissors!")
    print("You can type 'rock', 'paper', 'scissors' or use the symbols ✊ (rock), ✋ (paper), or ✂ (scissors).")
    print("Enter 'q' to quit the game.")

    # Define symbols for rock, paper, scissors
    symbols = {'rock': '✊', 'paper': '✋', 'scissors': '✂'}
    choices = ['rock', 'paper', 'scissors']  # Valid choices for computer

    computer_score = 0
    user_score = 0
Image2
while True:
        # Randomly choose for computer and get its corresponding symbol
        computer_choice = random.choice(choices)
        computer_symbol = symbols[computer_choice]

        # Prompt user to enter either the word or the symbol
        user = input("Enter your choice (rock, paper, scissors, or paste a symbol ✊ ✋ ✂): ").lower()

        # Allow user to copy-paste symbols or type full words
        if user == 'q':
            break
        elif user in ['rock', 'paper', 'scissors']:
            user_choice = user
            user_symbol = symbols[user_choice]
        elif user in ['✊', '✋', '✂']:
            # Map symbols to corresponding words
            if user == '✊':
                user_choice = 'rock'
            elif user == '✋':
                user_choice = 'paper'
            elif user == '✂':
                user_choice = 'scissors'
            user_symbol = user
        else:
            print("Invalid choice. Please enter rock, paper, scissors, or use the symbols ✊ ✋ ✂.")
            continue
Image7

Using Unicode escape sequences in Python:

Image5
import random
def play_rps():
    print("Welcome to Rock, Paper, Scissors!")
    print("You can type 'rock', 'paper', 'scissors' or use the symbols ✊ (rock), ✋ (paper), ✂ (scissors).")
    print("Enter 'q' to quit the game.")
    # Mapping words and Unicode escape sequences to choices
    symbols = {'rock': 'u270A', 'paper': 'u270B', 'scissors': 'u270C'}
    choices = ['rock', 'paper', 'scissors']  # Valid choices for computer
    computer_score = 0
    user_score = 0
Image12
while True:
        # Randomly choose for computer and get its corresponding symbol
        computer_choice = random.choice(choices)
        computer_symbol = symbols[computer_choice]
        # Prompt user to enter either the word or the Unicode symbol
        user = input("Enter your choice (rock, paper, scissors, or use symbols ✊ ✋ ✂): ").lower()
        # Handle quitting the game
        if user == 'q':
            break
        # Allow user to input either the words or Unicode symbols
        if user in ['rock', 'paper', 'scissors']:
            user_choice = user
            user_symbol = symbols[user_choice]
        elif user in ['u270A', 'u270B', 'u270C']:
            # Map Unicode symbols to corresponding words
            if user == 'u270A':
                user_choice = 'rock'
            elif user == 'u270B':
                user_choice = 'paper'
            elif user == 'u270C':
                user_choice = 'scissors'
            user_symbol = user
        else:
            print("Invalid choice. Please enter rock, paper, scissors, or use the symbols ✊ ✋ ✂.")
            continue
Image11

Common Questions and Issues

1. Why doesn’t my game recognize invalid inputs?

If your game accepts invalid choices like “roc” or “papers,” ensure that you’re validating the input against the predefined choices list. Always provide clear feedback to guide the player.

2. How can I add a scoring system?

Introducing a scoring system is a great way to make the game more competitive. Initialize variables for the player and computer scores at the start of the program:

user_score = 0
computer_score = 0

Update these scores within the game loop based on the outcome of each round. Display the scores at the end to show the final tally.

3. Why don’t the symbols work?

In modern editors and environments that support Unicode (such as most Python IDEs, Jupyter notebooks, etc.), copying and pasting symbols like ✊, ✋, and ✂ should work fine. If:

-> You are working in a UTF-8-compatible editor.
-> Your terminal or environment properly supports Unicode.
-> You don’t expect portability issues (e.g., running the code on older systems or
non-Unicode-compatible terminals).

In such cases, directly copying and using the symbols (✊, ✋, ✂) should work without any issues.

Using Unicode values (e.g., u270A for ✊) instead of directly copying the symbols (e.g., ✊, ✋, ✂) is useful in the following scenarios:

Symbol Handling: Unicode symbols like ✊, ✋, ✂ might not display correctly in all environments or platforms (such as older text editors, terminals, or consoles that do not fully support Unicode). Using Unicode escape sequences ensures that these characters are rendered consistently across all platforms.

Encoding Issues: Directly copying symbols can sometimes lead to encoding issues, especially if the file is not saved with proper encoding (like UTF-8). Unicode values avoid such encoding problems.

Conclusion

Developing a Rock Paper Scissors game in Python is a rewarding project that teaches fundamental programming concepts. By breaking the task into manageable steps, even beginners can build a functional game while learning key coding principles. With Python’s simplicity and flexibility, you can start with a basic version and gradually enhance it by adding features like scoring, a graphical interface, or even network play.

Start coding today and see how fun it can be to bring classic games to life through programming!

Become a Future Tech Innovator
At ItsMyBot, we inspire children to explore coding, AI, and robotics through engaging, hands-on learning experiences. Our courses build essential tech skills, confidence, and creativity—preparing kids for a tech-driven future.

Tags

Share

Poornima Sasidharan

An accomplished Academic Director, seasoned Content Specialist, and passionate STEM enthusiast, I specialize in creating engaging and impactful educational content. With a focus on fostering dynamic learning environments, I cater to both students and educators. My teaching philosophy is grounded in a deep understanding of child psychology, allowing me to craft instructional strategies that align with the latest pedagogical trends.

Related posts