Editor

Rock Paper Scissors in Python

Beginner · Games · about 30 minutes to build · 90 lines

You play rock, paper, scissors against the computer, round by round, until one of you has won three rounds.

The program

Press Run and answer its questions in the box that appears under the code.

rock_paper_scissors.py
"""Rock, paper, scissors against the computer: first to three wins the match."""
import random
CHOICES = ("rock", "paper", "scissors")
# Each choice beats the one it points to.
BEATS = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
SHORTCUTS = {"r": "rock", "p": "paper", "s": "scissors"}
WINS_NEEDED = 3
def get_player_choice():
"""Ask until the player types rock, paper or scissors (or r, p, s)."""
while True:
text = input("Rock, paper or scissors? (r/p/s): ").strip().lower()
choice = SHORTCUTS.get(text, text)
if choice in CHOICES:
return choice
print(" Please type r, p or s.")
def decide_winner(player, computer):
"""Return "player", "computer" or "draw" for one round."""
if player == computer:
return "draw"
if BEATS[player] == computer:
return "player"
return "computer"
def play_match():
"""Play rounds until someone reaches WINS_NEEDED and return the winner."""
scores = {"player": 0, "computer": 0}
round_number = 1
while max(scores.values()) < WINS_NEEDED:
print(f"\nRound {round_number}")
player = get_player_choice()
computer = random.choice(CHOICES)
print(f" You chose {player}, the computer chose {computer}.")
winner = decide_winner(player, computer)
if winner == "draw":
print(" It's a draw.")
elif winner == "player":
print(f" {player.capitalize()} beats {computer}. You win the round.")
else:
print(f" {computer.capitalize()} beats {player}. The computer wins the round.")
if winner != "draw":
scores[winner] += 1
print(f" Score: you {scores['player']}, computer {scores['computer']}")
round_number += 1
return "player" if scores["player"] == WINS_NEEDED else "computer"
def ask_yes_no(prompt):
"""Ask a yes/no question and return True for yes."""
while True:
answer = input(prompt).strip().lower()
if answer in ("y", "yes"):
return True
if answer in ("n", "no"):
return False
print(" Please type y or n.")
def main():
"""Play matches until the player wants to stop."""
print("=== Rock, Paper, Scissors ===")
print(f"First to {WINS_NEEDED} wins takes the match.")
matches_won = 0
matches_played = 0
while True:
winner = play_match()
matches_played += 1
if winner == "player":
matches_won += 1
print("\nYou win the match.")
else:
print("\nThe computer wins the match.")
print()
if not ask_yes_no("Play again? (y/n) "):
break
print(f"Matches won: {matches_won} of {matches_played}. Thanks for playing.")
if __name__ == "__main__":
main()

Open it in the full editor to save it, share it and keep building.

Sample run

What the program printed, and what was typed (in yellow).

=== Rock, Paper, Scissors ===
First to 3 wins takes the match.

Round 1
Rock, paper or scissors? (r/p/s): lizard
  Please type r, p or s.
Rock, paper or scissors? (r/p/s): s
  You chose scissors, the computer chose paper.
  Scissors beats paper. You win the round.
  Score: you 1, computer 0

Round 2
Rock, paper or scissors? (r/p/s): rock
  You chose rock, the computer chose rock.
  It's a draw.
  Score: you 1, computer 0

Round 3
Rock, paper or scissors? (r/p/s): r
  You chose rock, the computer chose paper.
  Paper beats rock. The computer wins the round.
  Score: you 1, computer 1

Round 4
Rock, paper or scissors? (r/p/s): rock
  You chose rock, the computer chose scissors.
  Rock beats scissors. You win the round.
  Score: you 2, computer 1

Round 5
Rock, paper or scissors? (r/p/s): p
  You chose paper, the computer chose rock.
  Paper beats rock. You win the round.
  Score: you 3, computer 1

You win the match.

Play again? (y/n) n
Matches won: 1 of 1. Thanks for playing.

How it is built

1. The rules as data

BEATS maps each choice to the one it defeats, so the rules live in one dictionary instead of a chain of if statements. SHORTCUTS lets the player type r, p or s.

CHOICES = ("rock", "paper", "scissors")
# Each choice beats the one it points to.
BEATS = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
SHORTCUTS = {"r": "rock", "p": "paper", "s": "scissors"}
WINS_NEEDED = 3

2. Reading the player's choice

SHORTCUTS.get(text, text) turns r into rock and leaves a full word as it is. Anything that is still not in CHOICES gets a message and another try.

def get_player_choice():
    """Ask until the player types rock, paper or scissors (or r, p, s)."""
    while True:
        text = input("Rock, paper or scissors? (r/p/s): ").strip().lower()
        choice = SHORTCUTS.get(text, text)
        if choice in CHOICES:
            return choice
        print("  Please type r, p or s.")

3. Who wins a round

A draw is checked first. Otherwise one lookup, BEATS[player] == computer, tells whether the player beat the computer.

def decide_winner(player, computer):
    """Return "player", "computer" or "draw" for one round."""
    if player == computer:
        return "draw"
    if BEATS[player] == computer:
        return "player"
    return "computer"

4. A match to three

The scores live in a dictionary with the keys "player" and "computer", the same words decide_winner returns, so the winner of a round can be scored with scores[winner] += 1. The loop stops when either score reaches WINS_NEEDED.

def play_match():
    """Play rounds until someone reaches WINS_NEEDED and return the winner."""
    scores = {"player": 0, "computer": 0}
    round_number = 1
    while max(scores.values()) < WINS_NEEDED:
        print(f"\nRound {round_number}")
        player = get_player_choice()
        computer = random.choice(CHOICES)
        print(f"  You chose {player}, the computer chose {computer}.")

        winner = decide_winner(player, computer)
        if winner == "draw":
            print("  It's a draw.")
        elif winner == "player":
            print(f"  {player.capitalize()} beats {computer}. You win the round.")
        else:
            print(f"  {computer.capitalize()} beats {player}. The computer wins the round.")
        if winner != "draw":
            scores[winner] += 1

        print(f"  Score: you {scores['player']}, computer {scores['computer']}")
        round_number += 1

    return "player" if scores["player"] == WINS_NEEDED else "computer"

5. Counting matches

main() counts the matches won and played and asks to play again after each one.

def main():
    """Play matches until the player wants to stop."""
    print("=== Rock, Paper, Scissors ===")
    print(f"First to {WINS_NEEDED} wins takes the match.")
    matches_won = 0
    matches_played = 0
    while True:
        winner = play_match()
        matches_played += 1
        if winner == "player":
            matches_won += 1
            print("\nYou win the match.")
        else:
            print("\nThe computer wins the match.")
        print()
        if not ask_yes_no("Play again? (y/n) "):
            break

    print(f"Matches won: {matches_won} of {matches_played}. Thanks for playing.")

Make it bigger

  • Add two more moves, such as fire and water, by making each value in BEATS a set of the choices it defeats.
  • Let the player choose how many round wins take the match.
  • Make the computer smarter: count which choice the player uses most and play the move that beats it.
  • Keep a list of every round and print a summary table when the player stops.

What it practises