Want to improve your Python skills while building a fun project? This tutorial will guide you through creating a Rock Paper Scissors game using Python!
By the end, you’ll have a working game where the user plays against the computer in an interactive, score-tracking version of Rock Paper Scissors.
This beginner-friendly project covers essential programming concepts, including:
- Using the random module to simulate a computer opponent
- Handling user input validation using regular expressions
- Working with loops and conditional statements
- Keeping track of the score and allowing replay
Let’s dive in!
Step 1: Setting Up the Project
Before we start coding, let’s set up our Python project:
1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, rock_paper_scissors.py
.
Great, now, let's dive head first into our Python editor to get this build started.
Step 2: Understanding How the Game Works
The Rock Paper Scissors game follows these rules:
- The user chooses Rock (R), Paper (P), or Scissors (S).
- The computer randomly selects one of the three options.
- The game determines the winner based on these conditions:
- Rock beats Scissors 🪨✂️
- Scissors beats Paper ✂️📄
- Paper beats Rock 📄🪨
- The game tracks the score and asks if the user wants to play again.
Now, let’s start coding in Python!
Step 3: Importing Required Modules
We need three Python modules for this project:
import random # For generating random choices
import os # To clear the screen between rounds
import re # For validating user input
Why Do We Use These Modules?
random
: Python random allows the computer to randomly select Rock, Paper, or Scissors.os
: Clears the terminal screen after each round for better readability.re
: Helps us validate user input using regular expressions (regex).
Step 4: Asking the User If They Want to Play Again
At the end of each round, we’ll ask the user if they want to continue playing.
def check_play_status():
valid_responses = ['yes', 'no', 'y']
while True:
try:
response = input('Do you wish to play again? (Yes or No): ')
if response.lower() not in valid_responses:
raise ValueError('Yes or No only')
if response.lower() in ['yes', 'y']:
return True
else:
os.system('cls' if os.name == 'nt' else 'clear')
print('Thanks for playing!')
exit()
except ValueError as err:
print(err)
How It Works
- A list of valid responses (
yes
,no
,y
) ensures proper input validation. - If the user enters "yes" or "y", the game continues.
- If they type "no", we clear the screen, display a thank-you message, and exit using
exit()
. - If they enter anything else, the function keeps asking until they provide a valid response.
Step 5: Writing the Core Game Logic
Now, let’s write the function that runs the Rock Paper Scissors game.
def play_rps():
user_score = 0
computer_score = 0
play = True
while play:
os.system('cls' if os.name == 'nt' else 'clear')
print('')
print('Rock, Paper, Scissors - Shoot!')
user_choice = input('Choose your weapon [R]ock, [P]aper, or [S]cissors: ')
# Validate input using regex
if not re.match("^[RrPpSs]$", user_choice):
print('Invalid choice! Please choose: [R]ock, [P]aper, or [S]cissors.')
continue
print(f'You chose: {user_choice.upper()}')
choices = ['R', 'P', 'S']
opp_choice = random.choice(choices)
print(f'I chose: {opp_choice}')
# Determine the winner
if opp_choice == user_choice.upper():
print('It\'s a Tie!')
elif (opp_choice == 'R' and user_choice.upper() == 'S') or \
(opp_choice == 'S' and user_choice.upper() == 'P') or \
(opp_choice == 'P' and user_choice.upper() == 'R'):
print(f'{opp_choice} beats {user_choice.upper()}, I win!')
computer_score += 1
else:
print(f'{user_choice.upper()} beats {opp_choice}, You win!')
user_score += 1
print(f'Score - You: {user_score}, Computer: {computer_score}')
play = check_play_status()
How It Works
- The game runs in a loop (
while play:
) until the player decides to stop. - The screen clears at the beginning of each round for a clean look.
- Regular expressions (
re.match()
) ensure valid input (only R, P, or S). - The computer randomly picks Rock, Paper, or Scissors.
- The game uses if-elif-else conditions to determine the winner and update scores.
- The user can play again or exit after each round.
The core functionality of our Rock Paper Scissors game is handled in the play_rps()
function.
It does three main things:
- Takes user input and validates it.
- Uses the random module to let the computer make a choice.
- Compares choices using if-elif-else statements to determine the winner.