thecodex.expert · The Codex Family of Knowledge
Tier 1 · Beginner · Python Project

Rock Paper Scissors

Play rock-paper-scissors against the computer, with score tracking. Learn comparing choices and encoding game rules.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want to play rock-paper-scissors against the computer: you pick, the computer picks randomly, and the program decides who won — keeping score across rounds. It teaches how to encode the rules of a game as code and compare two choices.

Where this shows up: any game logic, any “who wins” or “is this allowed” decision, matching systems, rule engines. Turning real-world rules into clear code is a core programming skill.

2 How to Think About It

Think about how to decide a winner, before any code:

The plan — in plain English
1. Player picks rock, paper, or scissors. → 2. Computer picks randomly. → 3. Compare: same = tie; otherwise check the three winning combos (rock beats scissors, scissors beats paper, paper beats rock). → 4. Update the score and play again.

Yes

No

Yes

No

Player picks

Computer picks randomly

Same choice?

Tie

Player wins combo?

Player wins

Computer wins

3 The Build — explained part by part

Here is the complete game. Each part is explained below.

Pythonrps.py
import random

choices = ["rock", "paper", "scissors"]
# What each choice beats.
beats = {"rock": "scissors", "scissors": "paper", "paper": "rock"}

player_score = 0
computer_score = 0

while True:
    player = input("rock, paper, scissors (or quit): ").lower()
    if player == "quit":
        break
    if player not in choices:
        print("Please choose rock, paper, or scissors.")
        continue

    computer = random.choice(choices)
    print(f"Computer chose {computer}.")

    if player == computer:
        print("Tie!")
    elif beats[player] == computer:
        print("You win!")
        player_score += 1
    else:
        print("Computer wins!")
        computer_score += 1

    print(f"Score - You: {player_score}, Computer: {computer_score}")
What each part does — in plain words
beats = {"rock": "scissors", ...} — this dictionary is the rules of the game: each choice maps to what it defeats. Encoding rules as data like this is cleaner than a tangle of if-statements.

player = input(...).lower() — read the player’s choice and lowercase it so “Rock” and “rock” both work.

if player not in choices: continue — if they typed something invalid, skip the rest and ask again.

computer = random.choice(choices) — the computer picks one of the three at random.

elif beats[player] == computer: — the heart of it: look up what the player’s choice beats; if that equals the computer’s choice, the player wins. Otherwise (not a tie, not a win) the computer wins.
Common mistakes — and how to avoid them
✗ Writing a long if/elif chain for every combination — hard to read and easy to get wrong.
✓ Encode the rules in a dictionary (beats) and compare — far cleaner.
✗ Forgetting .lower() — then “Rock” is treated as invalid.
✓ Lowercase the input so capitalisation does not matter.
✗ Not handling invalid input — a typo crashes the dictionary lookup.
✓ Check if player not in choices and ask again.

4 Test & Prove Each Part

We test the winner logic for every combination — the rules must be exactly right.

Rock beats scissors
The same choice is a tie
Paper loses to scissors
Pythontest_rps.py
BEATS = {"rock": "scissors", "scissors": "paper", "paper": "rock"}


def winner(player, computer):
    """Return 'player', 'computer', or 'tie'."""
    if player == computer:
        return "tie"
    if BEATS[player] == computer:
        return "player"
    return "computer"


def test_rock_beats_scissors():
    """Rock beats scissors."""
    assert winner("rock", "scissors") == "player"


def test_tie():
    """Same choice is a tie."""
    assert winner("paper", "paper") == "tie"


def test_paper_loses_to_scissors():
    """Paper loses to scissors."""
    assert winner("paper", "scissors") == "computer"

Run with pytest -v. Because the rules live in the BEATS dictionary and one winner function, we can test every outcome cleanly and trust the game is fair.

5 The Interface

INPUTyour choicerock, paper, scissors, or quit
What it expects
rock, paper, scissors (or quit): rock
OUTPUTresult + scorewho won and the running score
What it returns
Computer chose scissors.
You win!
Score - You: 1, Computer: 0

6 Run It & Automate It

Run it locally
python3 rps.py
Type your choice each round; type quit to stop.

Jenkins runs the tests automatically — each line explained below.

What you should see when it works
Terminala real run
rock, paper, scissors (or quit): rock
Computer chose scissors.
You win!
Score - You: 1, Computer: 0
If it breaks — how to fix it
🚨 KeyError when you type your choice.
You typed something not in the list (or with different case). Add the validation check and .lower().
🚨 The winner is always wrong.
Check your beats dictionary maps each choice to what it DEFEATS, not what beats it.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage('Get the code') { steps { checkout scm } }       // download the code
        stage('Install') { steps { sh 'python3 -m venv venv && . venv/bin/activate && pip install pytest' } }  // test tool
        stage('Test') { steps { sh '. venv/bin/activate && pytest -v' } }   // run every test
    }
    post {
        success { echo 'All tests passed.' }
        failure { echo 'A test failed — look above.' }
    }
}
🎯 Try this next — make it yours
  1. Best of five. End the game when someone reaches 3 wins. (Teaches: a win condition.)
  2. Add lizard and Spock. Extend the rules dictionary. (Teaches: scaling data-driven rules.)
  3. Track stats. Show win percentage at the end. (Teaches: maths on results.)
What you learned
You learned to encode rules as data (a dictionary of what beats what), validate input with continue, and track score across rounds. Encoding rules cleanly is what keeps game and business logic maintainable. Related: random, Control Flow.