Project: Rock, paper, scissors
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Project: Rock, paper, scissors
- You play rock, paper, scissors against the computer.
- The rules live in functions that return an answer, so each part is easy to test.
- You use functions,
return,ifwithand/or, and string methods.
What you will build
rock, paper or scissors? Rock
The computer chose scissors.
You win!
Step 1: who wins?
- Same move: a draw.
- Rock beats scissors, scissors beats paper, paper beats rock.
- A function can
returnas soon as it knows the answer. The lines after thatreturndo not run.
Step 2: functions can use functions
messagedoes not repeat the rules. It callswinnerand turns the result into words.- One rule in one place: if the rules change, you change only
winner.
Step 3: check what the player typed
.strip()removes spaces at both ends;.lower()makes small letters.- A comparison like
move == "rock"is alreadyTrueorFalse, so you canreturnit directly.
Play for real
random.choice(list)picks one item at random: the computer's move. Run this and play in the input box.
import random
def winner(player, computer):
if player == computer:
return "draw"
if (player == "rock" and computer == "scissors") or (player == "scissors" and computer == "paper") or (player == "paper" and computer == "rock"):
return "player"
return "computer"
move = input("rock, paper or scissors? ").strip().lower()
computer = random.choice(["rock", "paper", "scissors"])
print("The computer chose " + computer + ".")
print(winner(move, computer))
Now build it
- Three steps. Press Check answer after each one: the checks call your functions with many moves.
Step 1: write winner(player, computer) that returns "player", "computer" or "draw". Rock beats scissors, scissors beats paper, and paper beats rock.
Click Run to see the output here.
Step 2: write message(player, computer) that returns "You win!", "Computer wins!" or "Draw!". Call your winner function inside it instead of repeating the rules.
Click Run to see the output here.
Step 3: players make typing mistakes. Write is_valid(move) that returns True for rock, paper or scissors, in any capitals and with spaces around it, and False for anything else.
Click Run to see the output here.