Python Rock Paper Scissors Game

Create a Rock-Paper-Scissors game in Python. Master random choices, user inputs validation, and relational rule mappings.

Try Python Rock Paper Scissors Game Code

How it Works

Rock-Paper-Scissors is a standard game logic challenge. It requires verifying inputs against specific game rules and determining a winner.

Instead of writing tedious multi-layered if/else ladders, we can implement rules using a mapping dictionary. This is highly scaleable, allowing easy rules expansion (e.g., adding Lizard and Spock).

The script chooses randomly from the standard choices, compares it to the player's choice, and prints results including score updates.

Source Code

A Rock Paper Scissors script illustrating dictionary rule matching and random modules.

import random

def get_winner(player, computer):
    if player == computer:
        return "tie"
        
    # Dictionary mapping choice -> what it beats
    winning_rules = {
        "rock": "scissors",
        "paper": "rock",
        "scissors": "paper"
    }
    
    if winning_rules[player] == computer:
        return "player"
    return "computer"

def play_game():
    choices = ["rock", "paper", "scissors"]
    # Mocking player selections
    player_moves = ["rock", "paper", "scissors"]
    
    print("Rock, Paper, Scissors Game!")
    
    # Seed generator for deterministic outputs
    random.seed(11)
    
    for player_move in player_moves:
        computer_move = random.choice(choices)
        winner = get_winner(player_move, computer_move)
        
        print(f"\nPlayer chose:   {player_move.capitalize()}")
        print(f"Computer chose: {computer_move.capitalize()}")
        
        if winner == "tie":
            print("Result: It is a Tie!")
        elif winner == "player":
            print("Result: Player Wins!")
        else:
            print("Result: Computer Wins!")

play_game()
Terminal Output
Rock, Paper, Scissors Game!

Player chose:   Rock
Computer chose: Scissors
Result: Player Wins!

Player chose:   Paper
Computer chose: Paper
Result: It is a Tie!

Player chose:   Scissors
Computer chose: Rock
Result: Computer Wins!

Real-world Applications

  • Decisive rule verification matrices
  • Random number selector engines
  • Educational control flow logic projects

Frequently Asked Questions

How can I extend this to Rock-Paper-Scissors-Lizard-Spock?

Simply expand the `winning_rules` dictionary mapping so that each key points to a list of elements it beats. For example, `'rock': ['scissors', 'lizard']`.

How do I make the game run infinitely until the user quits?

Wrap the interaction logic inside a `while True:` loop and break the execution if the player inputs 'quit'.

More Examples