Actually learn Python by typing out the code yourselves: class 2
In this class, we will build a rock paper scissors game[1] we can play with the computer. It’s better to type the code in an editor so you can save it.
Flow chart ↑
Toggle the following flow chart to help you understand the logic behind our code.
Flow Chart
flowchart TD
A["Start: n = 0, w = 0"]
A--> B{n < 5?}
B -- Yes --> C["wait_for_player_input()"]
C-->C1{Valid?}
C1--Yes--> D["random_shape()"]
C1--No -->C
D --> E{"who_won()"}
E -- Player --> F[w += 1]
E -- Computer --> G[ n += 1]
E -- Tied --> B
F-->G
G-->B
B -- No ----> H[Show Results]
H-->I[End]
Get player’s input ↑
def wait_for_player_input():
shape = input("Rock (r), Paper (p), Scissors (s) ? ")
if shape in ["r", "p", "s"]:
return shape
else:
return wait_for_player_input()
Attention
: a function that call itself is called recursive function.
Generate a random shape ↑
We will need to import a function from a python module, put this line at the beginning of your file.
import random
Let’s create a function to return a random shape as computer’s input
def random_shape():
random.choice(['r', 'p', 's'])
Who won? ↑
Return 0 for tie, 1 if player won, 2 if computer won.
def who_won(pshape, cshape):
if pshape == cshape:
return 0
r = pshape + cshape
if r == 'rs' or r == 'pr' or r == 'sp':
return 1
return 2
All code ↑
Let’s write the main game logic and put all code together.
import random
def wait_for_player_input():
shape = input("Rock (r), Paper (p), Scissors (s) ? ")
if shape in ["r", "p", "s"]:
return shape
else:
return wait_for_player_input()
def random_shape():
return random.choice(['r', 'p', 's'])
def who_won(pshape, cshape):
if pshape == cshape:
return 0
r = pshape + cshape
if r == 'rs' or r == 'pr' or r == 'sp':
return 1
return 2
def play(n_game):
n = 0
w = 0
while n < n_game:
print(f"Game # {n + 1}")
pshape = wait_for_player_input()
cshape = random_shape()
print(f"Computer: {cshape}")
match who_won(pshape, cshape):
case 0:
print("Tied! Replay")
continue
case 1:
print("You got this one!")
w += 1
case 2:
print("Computer got this one!")
print()
n += 1
print(f"You got {w} out of {n_game}")
if w > n_game / 2:
print("You WON!")
else:
print("You LOST!")
play(3)
Attention
: make sure your python version is 3.10 or above to use match statement.
Challenge ↑
- Create a new function play_till(n_won) so that whoever won n_won first, won the whole game.
Leave a comment if you have any questions (you don’t need to register an account).