โœŠโœ‹โœŒ๏ธ Rock Paper Scissors Gameยถ

๐Ÿš€ Open Notebookยถ

Open In Colab Open In Kaggle

๐Ÿ“บ Video Tutorialยถ

Watch on YouTube

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ยถ

  1. Setup - Define valid options, initialize player choice

  2. Computer Selection - Randomly choose from options

  3. 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

  4. 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)

Practice Exercisesยถ

Beginner Levelยถ

  1. Fixed Choices: Create a game where both player and computer choices are hardcoded. Determine winner.

  2. One Round: Build a single round game with player input and random computer choice.

  3. Tie Checker: Write a program that only checks if choices are the same (tie).

  4. Win Condition Only: Check only if player wins, ignore loss and tie.

  5. Choice Display: Display both choices before showing the result.

Intermediate Levelยถ

  1. Best of Three: Play 3 rounds and declare overall winner based on wins.

  2. Win Percentage: Track total games and display win percentage.

  3. Choice Statistics: Track how often each choice (rock/paper/scissors) is selected by both players.

  4. Streak Tracker: Track and display longest winning streak.

  5. Difficulty Levels: Add โ€œeasyโ€ mode (computer chooses randomly) and โ€œhardโ€ mode (computer tries to predict playerโ€™s pattern).

Advanced Levelยถ

  1. Extended Version: Add โ€œlizardโ€ and โ€œspockโ€ options (Rock Paper Scissors Lizard Spock variant with 5 choices).

  2. AI Opponent: Create a computer that learns from playerโ€™s previous choices and adapts strategy.

  3. Tournament Mode: Multiple players compete in elimination rounds.

  4. Multiplayer: Two human players instead of player vs computer.

  5. 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ยถ

  1. Variables store data values that can be reused

  2. Import modules to use external code

  3. Use loops to repeat actions

  4. Use if-elif-else for conditional logic

๐Ÿ’ก These points cover the main concepts from the video tutorial to help reinforce your learning.