PythonMastery

Rock paper scissors game in Python

Play rock paper scissors against the computer for five rounds. A dictionary holds the rules, input is checked, and the program keeps the score.

The player types a move, the computer picks one at random, and a dictionary of rules decides who wins. Each key is a move and its value is the move it beats.

The program

python
import random

random.seed(17)  # fixed seed so the output matches this page; remove it for real use

beats = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
moves = list(beats)

rounds = 5
round_number = 1
player_score = 0
computer_score = 0

while round_number <= rounds:
    player = input(f"Round {round_number}. rock, paper or scissors? ").strip().lower()
    if player not in beats:
        print("Please type rock, paper or scissors.")
        continue

    computer = random.choice(moves)
    print(f"The computer chose {computer}.")

    if player == computer:
        print("Draw.")
    elif beats[player] == computer:
        print("You win this round.")
        player_score += 1
    else:
        print("The computer wins this round.")
        computer_score += 1
    round_number += 1

print(f"Final score: you {player_score}, computer {computer_score}")
if player_score > computer_score:
    print("You win the game!")
elif player_score < computer_score:
    print("The computer wins the game.")
else:
    print("The game is a draw.")

Typed in this example: rock, Paper, lizard, scissors, paper, rock. Press Run to type your own.

output
Round 1. rock, paper or scissors? rock
The computer chose scissors.
You win this round.
Round 2. rock, paper or scissors? Paper
The computer chose paper.
Draw.
Round 3. rock, paper or scissors? lizard
Please type rock, paper or scissors.
Round 3. rock, paper or scissors? scissors
The computer chose paper.
You win this round.
Round 4. rock, paper or scissors? paper
The computer chose paper.
Draw.
Round 5. rock, paper or scissors? rock
The computer chose paper.
The computer wins this round.
Final score: you 2, computer 1
You win the game!

How it works

Try changing it: more moves

Because the rules are data, a bigger game needs only a bigger dictionary. In rock paper scissors lizard Spock, each move beats two others, so each value is a set:

python
beats = {
    "rock": {"scissors", "lizard"},
    "paper": {"rock", "spock"},
    "scissors": {"paper", "lizard"},
    "lizard": {"spock", "paper"},
    "spock": {"scissors", "rock"},
}


def winner(a, b):
    if a == b:
        return "draw"
    return a if b in beats[a] else b


print(winner("lizard", "spock"))
print(winner("rock", "paper"))
print(winner("spock", "spock"))
output
lizard
paper
draw

Learn the idea: Dictionaries, Loops: for, while, and the Pythonic Patterns, Control Flow: Conditionals