Night 14: Rock, paper, scissors
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: rock, paper, scissors
- Week 2 ends with a game you know: rock, paper, scissors!
- Nothing new to learn: you use functions,
IF, loops andINPUTtogether.
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(MoveA, MoveB)answers one question: doesMoveAwin againstMoveB?
FUNCTION Beats(MoveA : STRING, MoveB : STRING) RETURNS BOOLEAN
IF MoveA = "rock" AND MoveB = "scissors" THEN
RETURN TRUE
ENDIF
IF MoveA = "scissors" AND MoveB = "paper" THEN
RETURN TRUE
ENDIF
IF MoveA = "paper" AND MoveB = "rock" THEN
RETURN TRUE
ENDIF
RETURN FALSE
ENDFUNCTION
OUTPUT Beats("paper", "rock")
OUTPUT Beats("rock", "paper")
ANDmeans both must be TRUE.
Use the function
- Now one round is easy to read:
FUNCTION Beats(MoveA : STRING, MoveB : STRING) RETURNS BOOLEAN
RETURN (MoveA = "rock" AND MoveB = "scissors") OR (MoveA = "scissors" AND MoveB = "paper") OR (MoveA = "paper" AND MoveB = "rock")
ENDFUNCTION
DECLARE You, Pet : STRING
You ← "rock"
Pet ← "scissors"
IF You = Pet THEN
OUTPUT "Draw!"
ELSE
IF Beats(You, Pet) THEN
OUTPUT "You win!"
ELSE
OUTPUT "Pet wins!"
ENDIF
ENDIF
- Here
Beatsis written in a shorter way, withOR. Both ways are fine.
Week 2 is done!
- You can make games now: loops that wait, random numbers, procedures, and functions that answer.
- Play a few rounds with a friend. Then let the pet choose with
RAND!
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write Beats(MoveA : STRING, MoveB : STRING) RETURNS BOOLEAN. It returns TRUE when MoveA เบต MoveB: rock beats scissors, scissors beats paper, paper beats rock. Otherwise it returns FALSE.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read your move, then the pet's move, with INPUT. Output You win!, Pet wins! หรือ Draw!. Use your Beats function.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Play 3 rounds. Each round, read your move and the pet's move. Count the wins in YouWon และ PetWon. At the end, output the score like You 2 - 1 Pet.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Players make typos. Read a move. While it is not rock, paper หรือ scissors, output Try again and read another. Then output OK: and the move.
คลิก Run เพื่อดูผลลัพธ์ที่นี่