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.
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:
Starting with the right tools and a clear understanding of the basics sets the foundation for a smooth coding experience.
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:
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.
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():
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.”)
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
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:
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.
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)
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:
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
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.
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")
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.
# 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!")
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()
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
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.
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)
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.
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
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
Using Unicode escape sequences in Python:
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
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
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.
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.
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.
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!