โโโ๏ธ Rock Paper Scissors Gameยถ
๐ Open Notebookยถ
๐บ Video Tutorialยถ
ROCK PAPER SCISSORS game in Python ๐ฟ (13:38)
What Youโll Learnยถ
In this chapter, youโll build the classic Rock Paper Scissors game, demonstrating how to use random computer opponents, implement game logic with nested conditionals, validate input with membership operators, and create replay functionality with game loops.
Learning Objectivesยถ
Implement classic game rules with conditional logic
Use random.choice() for computer opponent decision-making
Apply membership operators (in, not in) for input validation
Create game loops with replay functionality
Structure nested if-elif statements for complex logic
Design clear user interaction patterns
Concept Explanationยถ
What is Rock Paper Scissors?ยถ
Rock Paper Scissors is a simple hand game played between two players. Each player simultaneously forms one of three shapes:
Rock (fist) - beats scissors
Paper (flat hand) - beats rock
Scissors (two fingers) - beats paper
Game Rulesยถ
The win conditions follow a circular logic:
Rock crushes Scissors โ Rock wins
Scissors cuts Paper โ Scissors wins
Paper covers Rock โ Paper wins
Same choice โ Tie
This creates a balanced game where each choice has one win and one loss condition.
Program Structureยถ
1. Data Storageยถ
Use a tuple to store valid options:
options = ("rock", "paper", "scissors")
Tuples are perfect because:
Game options never change (immutable)
Memory efficient
Signals these are constants
2. Random Computer Choiceยถ
import random
computer = random.choice(options)
This gives the computer a fair, random selection each game.
3. Input Validation with Membershipยถ
The membership operator checks if a value exists in a sequence:
player = input("Choose: ").lower()
while player not in options:
player = input("Invalid! Choose rock, paper, or scissors: ").lower()
This prevents invalid input before processing game logic.
4. Nested Conditional Logicยถ
The game logic requires checking multiple conditions:
if player == computer:
print("Tie!")
elif player == "rock":
if computer == "scissors":
print("You win!")
else: # computer == "paper"
print("You lose!")
# ... more conditions
Game Flowยถ
Setup - Define valid options, initialize player choice
Computer Selection - Randomly choose from options
Game Loop - While user wants to play:
Input Loop - Get and validate player choice
Comparison - Check for tie first, then evaluate each player choice
Display Result - Show outcome with explanation
Replay - Ask if player wants another round
Exit - End game when player declines
Membership Operatorsยถ
Python provides two membership operators:
# 'in' operator
if "rock" in options:
print("Found!")
# 'not in' operator
if player not in options:
print("Invalid choice!")
These are cleaner than multiple comparisons:
# Without membership operator (verbose)
if player == "rock" or player == "paper" or player == "scissors":
# valid
# With membership operator (clean)
if player in options:
# valid
Decision Tree Structureยถ
The complete game logic as a decision tree:
Is player == computer?
โโ Yes โ Tie
โโ No โ Check player choice
โโ Rock?
โ โโ vs Paper โ Lose
โ โโ vs Scissors โ Win
โโ Paper?
โ โโ vs Scissors โ Lose
โ โโ vs Rock โ Win
โโ Scissors?
โโ vs Rock โ Lose
โโ vs Paper โ Win
Examplesยถ
Example 1: Basic Membership Operatorsยถ
# Using 'in' operator
fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
print("Found!") # Executes
if "orange" in fruits:
print("Found!") # Doesn't execute
# Using 'not in' operator
if "orange" not in fruits:
print("Not found!") # Executes
# With user input
choice = input("Enter a fruit: ").lower()
if choice in fruits:
print(f"{choice} is available")
else:
print(f"{choice} is not available")
Example 2: Simple Rock Paper Scissorsยถ
import random
options = ("rock", "paper", "scissors")
player = input("Choose rock, paper, or scissors: ").lower()
computer = random.choice(options)
print(f"You chose: {player}")
print(f"Computer chose: {computer}")
if player == computer:
print("Tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "rock" and computer == "paper":
print("You lose!")
Example 3: Input Validation Loopยถ
options = ("rock", "paper", "scissors")
player = None
# Keep asking until valid input
while player not in options:
player = input("rock, paper, or scissors: ").lower()
if player not in options:
print("Invalid! Try again.")
print(f"You chose: {player}")
Example 4: Complete Game Logicยถ
import random
options = ("rock", "paper", "scissors")
player = input("Choose: ").lower()
computer = random.choice(options)
print(f"\nYou: {player}")
print(f"Computer: {computer}\n")
if player == computer:
print("It's a tie!")
elif player == "rock":
if computer == "scissors":
print("Rock crushes scissors - You win! ๐")
else: # paper
print("Paper covers rock - You lose! ๐ข")
elif player == "paper":
if computer == "rock":
print("Paper covers rock - You win! ๐")
else: # scissors
print("Scissors cuts paper - You lose! ๐ข")
elif player == "scissors":
if computer == "paper":
print("Scissors cuts paper - You win! ๐")
else: # rock
print("Rock crushes scissors - You lose! ๐ข")
Example 5: With Replay Functionalityยถ
import random
options = ("rock", "paper", "scissors")
playing = True
while playing:
player = None
computer = random.choice(options)
# Input validation
while player not in options:
player = input("rock, paper, scissors: ").lower()
# Game logic
print(f"Computer chose: {computer}")
if player == computer:
print("Tie!")
elif (player == "rock" and computer == "scissors") or \
(player == "paper" and computer == "rock") or \
(player == "scissors" and computer == "paper"):
print("You win!")
else:
print("You lose!")
# Replay
again = input("\nPlay again? (yes/no): ").lower()
if again != "yes":
playing = False
print("Thanks for playing!")
Example 6: With Score Trackingยถ
import random
options = ("rock", "paper", "scissors")
player_score = 0
computer_score = 0
playing = True
print("=== ROCK PAPER SCISSORS ===")
print("First to 3 wins!\n")
while playing:
player = None
# Input validation
while player not in options:
player = input("Your choice: ").lower()
computer = random.choice(options)
print(f"Computer chose: {computer}")
# Determine winner
if player == computer:
print("Tie! No points.\n")
elif (player == "rock" and computer == "scissors") or \
(player == "paper" and computer == "rock") or \
(player == "scissors" and computer == "paper"):
print("You win this round! ๐\n")
player_score += 1
else:
print("Computer wins this round! ๐ข\n")
computer_score += 1
# Display score
print(f"Score - You: {player_score}, Computer: {computer_score}")
# Check for winner
if player_score == 3:
print("\n๐ YOU WIN THE GAME! ๐")
playing = False
elif computer_score == 3:
print("\n๐ป COMPUTER WINS THE GAME! ๐ป")
playing = False
print("-" * 30)
Example 7: Full Featured Versionยถ
import random
def get_player_choice(options):
"""Get and validate player input"""
player = None
while player not in options:
player = input("\n๐ฎ rock, paper, or scissors: ").lower()
if player not in options:
print("โ Invalid choice! Try again.")
return player
def determine_winner(player, computer):
"""Determine game outcome"""
if player == computer:
return "tie"
win_conditions = {
"rock": "scissors",
"paper": "rock",
"scissors": "paper"
}
if win_conditions[player] == computer:
return "player"
else:
return "computer"
def display_result(player, computer, winner):
"""Display game result with explanation"""
actions = {
("rock", "scissors"): "Rock crushes scissors",
("scissors", "paper"): "Scissors cuts paper",
("paper", "rock"): "Paper covers rock",
("scissors", "rock"): "Rock crushes scissors",
("paper", "scissors"): "Scissors cuts paper",
("rock", "paper"): "Paper covers rock"
}
print(f"\n{'='*40}")
print(f"You chose: {player.upper()}")
print(f"Computer chose: {computer.upper()}")
print(f"{'='*40}")
if winner == "tie":
print("๐ค It's a TIE!")
else:
action = actions.get((player, computer)) or actions.get((computer, player))
if winner == "player":
print(f"โ
{action}")
print("๐ YOU WIN!")
else:
print(f"โ {action}")
print("๐ข YOU LOSE!")
def main():
"""Main game function"""
options = ("rock", "paper", "scissors")
player_wins = 0
computer_wins = 0
ties = 0
print("\n" + "="*40)
print(" ROCK PAPER SCISSORS GAME")
print("="*40)
playing = True
while playing:
# Get choices
player = get_player_choice(options)
computer = random.choice(options)
# Determine winner
winner = determine_winner(player, computer)
# Update statistics
if winner == "player":
player_wins += 1
elif winner == "computer":
computer_wins += 1
else:
ties += 1
# Display result
display_result(player, computer, winner)
# Show statistics
print(f"\n๐ Statistics:")
print(f" Wins: {player_wins} | Losses: {computer_wins} | Ties: {ties}")
# Play again?
print("\n" + "-"*40)
again = input("Play again? (yes/no): ").lower()
if again != "yes":
playing = False
# Final summary
print("\n" + "="*40)
print(" GAME OVER")
print("="*40)
print(f"Final Score:")
print(f" You: {player_wins} wins")
print(f" Computer: {computer_wins} wins")
print(f" Ties: {ties}")
if player_wins > computer_wins:
print("\n๐ YOU ARE THE CHAMPION! ๐")
elif computer_wins > player_wins:
print("\n๐ป COMPUTER IS THE CHAMPION! ๐ป")
else:
print("\n๐ค IT'S A DRAW! ๐ค")
print("\nThanks for playing! ๐\n")
if __name__ == "__main__":
main()
Practice Exercisesยถ
Beginner Levelยถ
Fixed Choices: Create a game where both player and computer choices are hardcoded. Determine winner.
One Round: Build a single round game with player input and random computer choice.
Tie Checker: Write a program that only checks if choices are the same (tie).
Win Condition Only: Check only if player wins, ignore loss and tie.
Choice Display: Display both choices before showing the result.
Intermediate Levelยถ
Best of Three: Play 3 rounds and declare overall winner based on wins.
Win Percentage: Track total games and display win percentage.
Choice Statistics: Track how often each choice (rock/paper/scissors) is selected by both players.
Streak Tracker: Track and display longest winning streak.
Difficulty Levels: Add โeasyโ mode (computer chooses randomly) and โhardโ mode (computer tries to predict playerโs pattern).
Advanced Levelยถ
Extended Version: Add โlizardโ and โspockโ options (Rock Paper Scissors Lizard Spock variant with 5 choices).
AI Opponent: Create a computer that learns from playerโs previous choices and adapts strategy.
Tournament Mode: Multiple players compete in elimination rounds.
Multiplayer: Two human players instead of player vs computer.
Statistical Analysis: After 100 games, show detailed analytics (most common choices, win rates per choice, pattern detection).
Common Mistakes to Avoidยถ
Mistake 1: Not Handling Case Sensitivityยถ
Wrong:
options = ("rock", "paper", "scissors")
player = input("Choose: ") # User enters "Rock"
if player in options: # "Rock" != "rock"
print("Valid") # Won't execute
Correct:
options = ("rock", "paper", "scissors")
player = input("Choose: ").lower() # Convert to lowercase
if player in options:
print("Valid")
Why: User input case varies. Always normalize to lowercase for comparison.
Mistake 2: Incomplete Win Conditionsยถ
Wrong:
if player == "rock":
if computer == "paper":
print("You lose!")
# Missing scissors case!
Correct:
if player == "rock":
if computer == "paper":
print("You lose!")
elif computer == "scissors":
print("You win!")
# Now complete
Why: Must handle all possible computer choices for each player choice.
Mistake 3: Resetting Computer Choice in Wrong Placeยถ
Wrong:
computer = random.choice(options) # Only once!
while True:
player = input("Choose: ").lower()
# computer is same every game!
Correct:
while True:
computer = random.choice(options) # New choice each game
player = input("Choose: ").lower()
Why: Computer needs a fresh random choice for each round.
Mistake 4: Not Resetting Player Choiceยถ
Wrong:
player = None
while running:
while player not in options: # First time only!
player = input("Choose: ")
# player keeps old value in next iteration
Correct:
while running:
player = None # Reset each round
while player not in options:
player = input("Choose: ").lower()
Why: Player choice must be reset each round to prompt for new input.
Real-World Applicationsยถ
1. Game Theory Researchยถ
Rock Paper Scissors is studied in game theory, economics, and psychology to understand strategic decision-making, prediction, and randomness in competitive scenarios.
2. Conflict Resolutionยถ
Used as a simple, fair decision-making tool in casual situations when a random, unbiased choice is needed between two parties.
3. Robot Programmingยถ
Teaching robots to play RPS helps demonstrate basic AI concepts like decision trees, pattern recognition, and strategy adaptation.
4. Tournament Systemsยถ
The game is used in actual competitive tournaments worldwide, demonstrating how simple rules can create complex strategic depth.
Challenge Projectsยถ
1. Rock Paper Scissors Lizard Spockยถ
Expand to the 5-option variant from โThe Big Bang Theoryโ.
Requirements:
Implement all 5 options (rock, paper, scissors, lizard, spock)
10 different win conditions
Display rule explanations
Track statistics for all options
2. AI That Learnsยถ
Create a computer opponent that improves over time.
Requirements:
Track playerโs choice history
Detect patterns (if player chooses rock twice, likely paper next)
Adapt strategy based on history
Display AI โconfidence levelโ
Compare random vs learning AI performance
3. RPS Championship Tournamentยถ
Host a multi-player elimination tournament.
Requirements:
Support 8+ players
Bracket-style elimination
Best of 3 per match
Display tournament bracket
Crown champion
4. RPS Casinoยถ
Gambling version with betting system.
Requirements:
Starting balance of $100
Place bets before each round
Win doubles bet, lose forfeits bet
Track balance over time
Bankruptcy detection
High score leaderboard
5. RPS Battle RPGยถ
Turn-based battle game using RPS mechanics.
Requirements:
Health points for player and enemy
RPS determines damage dealt
Special moves and powerups
Multiple enemy types
Boss battles
Level progression
๐ Key Takeaways from Videoยถ
Variables store data values that can be reused
Import modules to use external code
Use loops to repeat actions
Use if-elif-else for conditional logic
๐ก These points cover the main concepts from the video tutorial to help reinforce your learning.