Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 149 ยท Projects

Project: Rock, Paper, Scissors

Build rock, paper, scissors in Python step by step. Practice input, random choices, a rules dictionary, input validation, score keeping and best-of-N matches.

Rock, paper, scissors is the perfect first project. Everyone knows the rules, a single round fits in ten lines of code, and yet a polished version needs real programming decisions: how to store the rules, what to do when the player types something odd, how to keep score, and when a match is over.

In this project you'll build the game in five stages. Each stage is a complete program you can run, and each one improves on the last. Along the way you'll use input, random choices, if statements, dictionaries, while loops and functions. If any of those feel shaky, keep the linked lessons open in another tab.

How the editor plays the game

A game needs a player. In these editors, input() reads its answers from the Input box under the code, one line per call, and every stage comes with moves already filled in. Press Run to play a whole game, then change the lines in the Input box to play differently. If the program asks for more lines than the box contains, you'll see an EOFError; just add more lines.

The computer's moves are random, which would make the preset input pointless: you couldn't predict who wins. So every stage calls random.seed(...) first. A seed makes the "random" sequence repeatable, so the computer makes the same choices on every run. Delete the seed line when you want a real, unpredictable opponent.

Stage 1: one round

Start with the smallest game that works: ask for a move, let the computer pick one with random.choice(), and compare.

Python Stage 1: a single round

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

random.choice() picks one element of a list, each with equal chance. Calling .strip().lower() on the input means " Rock " and "ROCK" both become "rock", which saves the player from frustrating mistakes.

The long condition works, but it has two problems. First, the rules are buried in logic: to add a new move, you'd rewrite the condition. Second, type banana in the Input box and run it again. The program says "You lose!", because anything that isn't a tie or a listed win falls through to else. Let's fix both.

Stage 2: a rules table and input validation

Every rule of the game has the same shape: this move beats that move. Shapes like that belong in a dictionary, not in an if chain. With BEATS, deciding a round becomes a single lookup:

Python Stage 2: rules in a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first part of the output is a quick self-check. It runs decide() for all nine combinations, so you can see at a glance that each move wins against exactly one other move and loses against exactly one. Running your logic against every case like this is a cheap habit that catches typos in rules tables.

A few details are worth a closer look:

  • SHORTCUTS is built with a dictionary comprehension: move[0] is the first letter, so the result is {"r": "rock", "p": "paper", "s": "scissors"}.
  • SHORTCUTS.get(text, text) translates a shortcut and leaves everything else unchanged. If the player typed paper, get() doesn't find it as a key and returns the default, which is text itself.
  • ask_move() uses the loop until valid, then return pattern, so the rest of the program never sees a bad move. banana gets a polite complaint instead of a lost round.
  • list(BEATS) turns the dictionary's keys into a list for random.choice(), so the list of moves can never get out of sync with the rules.

Stage 3: keep playing and keep score

One round is over too quickly. Let's play until the player types q, and count wins, losses and ties along the way. A dictionary is again the right tool: the result of decide() is exactly the key we need to increase.

Python Stage 3: a score and a quit command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ask_move() now returns either a move or None, and the type hint str | None says so. The loop header uses the walrus operator := (see Assignment Operators), which assigns and tests in one step: "ask for a move, store it in player, and keep looping while it isn't None". Without it, you'd write while True: with an if player is None: break inside, which also works fine.

Notice that score[result] += 1 replaces three separate if branches. Because the results are the dictionary keys, adding a new kind of result later would need no new branch at all.

Stage 4: best-of-N matches

Friends rarely play forever; they play "best of three" or "best of five". In a best-of-N match, the first player to win more than half of N rounds takes the match. For best of five that's three wins, which is 5 // 2 + 1. Ties don't count as rounds, so a match can take longer than N rounds.

This stage also moves one round into its own function, play_round(), so the match logic reads like a description of the rules:

Python Stage 4: a best-of-five match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The preset input starts with two bad answers on purpose. 4 is rejected because a best-of-four match could end 2-2, and five fails str.isdigit(), so int() never sees it and can't raise a ValueError. (isdigit() is a quick check for whole numbers without a sign; for anything fancier, use the try/except ValueError pattern from the number guessing project.)

max(wins.values()) < needed keeps the loop going while neither side has enough wins. As soon as one does, the loop ends and the function reports who it was. Separating play_round() from play_match() means you can test or reuse each part on its own, which you'll do in the next stage.

Stage 5: more moves with the same code

The best test of a design is a new requirement. A popular variant of the game adds two moves, lizard and Spock, and every move now beats two others. With an if chain from stage 1 you'd need twenty comparisons. With a rules table you only change the data.

This time each move maps to a dictionary of the moves it beats, along with a verb that makes the result read nicely:

Python Stage 5: rock, paper, scissors, lizard, Spock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three ideas make this version robust:

  • The data checks itself. check_rules() uses assert to confirm that every move beats exactly two others and that no two moves beat each other. If you mistype a rule, the program stops immediately with a clear message instead of quietly playing an unfair game.
  • Prefix matching replaces fixed shortcuts. First letters no longer work, because scissors and spock both start with s. So ask_move() accepts any prefix that matches exactly one move: sc means scissors and sp means Spock, while a lone s is rejected as ambiguous. The preset input starts with exactly that mistake.
  • describe() works for any rules table. It doesn't mention a single move by name. Add more moves to RULES and nothing else changes.

Running it on your computer: copy a stage into a file such as rps.py, delete the random.seed(...) line, and run python rps.py in a terminal. You'll type your moves directly instead of using the Input box. For bigger programs, wrap the top-level code in a main() function behind if __name__ == "__main__": (see Modules and Imports).

Ideas to extend the game

Try these on your own, starting from stage 4 or 5:

  1. A computer that learns. Count the player's moves with collections.Counter and make the computer play whatever beats the player's favorite move. Does it win more often against you?
  2. Round history. Store every round as a tuple (player, computer, result) in a list and print a table at the end of the match.
  3. Two human players. Ask both players for a move. (In a terminal, getpass.getpass() reads input without showing it, so the second player can't peek.)
  4. Tests for the rules. Write unit tests for decide() or describe(), which are pure functions and easy to test.
  5. Enums for moves. Replace the move strings with an Enum, so a typo like "sissors" becomes an error instead of a silent bug.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With BEATS = {"rock": "scissors", "paper": "rock", "scissors": "paper"}, what does decide("scissors", "rock") return?

    BEATS["scissors"] is "paper", not "rock", and the moves differ, so the player loses.
  2. 2. Why does every stage call random.seed(3) before the game starts?

    A seed makes the random sequence repeatable. Delete it to get a different game every time.
  3. 3. How many wins does a player need to take a best-of-seven match?

    The match is decided by a majority of seven rounds: 7 // 2 + 1 is 4. Ties don't count as rounds.
  4. 4. What does SHORTCUTS.get(text, text) return when text is "paper" and SHORTCUTS only has the keys "r", "p" and "s"?

    get() returns its second argument when the key is missing, so full move names pass through unchanged.
  5. 5. In stage 5, why is a single letter s rejected as a move?

    Prefix matching only accepts a prefix that matches exactly one move. Type sc or sp instead.

Summary

  • random.choice() picks a random element; random.seed() makes the sequence repeatable while you test.
  • Storing rules in a dictionary turns a long if chain into a lookup and makes new moves a data change, not a code change.
  • The loop until valid, then return pattern keeps bad input away from the rest of the program; .strip().lower() forgives harmless differences.
  • A score dictionary keyed by result (score[result] += 1) replaces separate counters and branches.
  • A best-of-N match needs N // 2 + 1 wins, and ties don't count.
  • Small functions (decide(), ask_move(), play_round()) and self-checks such as check_rules() make the program easy to change and to trust.

Next: Project: Number Guessing Game, where you'll build a guessing game with hints, difficulty levels and replay statistics.