Night 14: Rock, paper, scissors
Vous avez déjà terminé cette soirée, en Python ou en pseudocode. Elle compte pour les deux. Entraînez-vous à nouveau si vous le souhaitez.
Tonight: rock, paper, scissors
- Week 2 ends with a game you know: rock, paper, scissors!
- Nothing new to learn: you use functions,
if, loops andinput()together.
Words for tonight
| Word | Meaning |
|---|---|
| rule | what is allowed and who wins |
| round | one turn of a game |
| draw | nobody wins; it is the same |
The rules
| Move | Beats |
|---|---|
| rock | scissors |
| scissors | paper |
| paper | rock |
- The same move on both sides is a draw.
Put the rules in one function
beats(a, b)answers one question: doesawin againstb?
def beats(a, b):
if a == "rock" and b == "scissors":
return True
if a == "scissors" and b == "paper":
return True
if a == "paper" and b == "rock":
return True
return False
print(beats("paper", "rock"))
print(beats("rock", "paper"))
andmeans both must be true.
Use the function
- Now one round is easy to read:
def beats(a, b):
return (a, b) in [("rock", "scissors"), ("scissors", "paper"), ("paper", "rock")]
you = "rock"
pet = "scissors"
if you == pet:
print("Draw!")
elif beats(you, pet):
print("You win!")
else:
print("Pet wins!")
- Here
beatsis written in a shorter way. Both ways are fine.
Week 2 is done!
- You can make games now: loops that wait, random numbers, functions with parameters and answers.
- Play a few rounds with a friend. Then make the pet choose with
random.choice!
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Define beats(a, b). It returns True when move a beats move b: rock beats scissors, scissors beats paper, paper beats rock. Otherwise it returns False.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Read your move, then the pet's move, with input(). Print You win!, Pet wins! ou Draw!. Use your beats function.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Play 3 rounds. Each round, read your move and the pet's move. Count the wins in you_won et pet_won. At the end, print the score like You 2 - 1 Pet.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Players make typos. Read a move. While it is not rock, paper ou scissors, print Try again and read another. Then print OK: and the move.
Cliquez sur Exécuter pour voir le résultat ici.