Night 28: Plan your project
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: plan your project
- In three nights you build your own pet game. Tonight you plan it.
- You will learn one thing: how to plan a program before you write it.
Words for tonight
| Word | Meaning |
|---|---|
| plan | what you will do, written before you start |
| step | one small part of the work |
| test | try the code to see if it is right |
What does the game do?
- Write the answers in plain words first:
| Question | Our pet game |
|---|---|
| What does it remember? | Energy (0 to 10) and Food (0 to 10) |
| What can the player type? | play, eat, sleep, quit |
| What does it show? | the energy and food after each command |
Break it into small parts
- A big program is many small parts. Each part is one function. This is called decomposition.
| Command | Function | What it does |
|---|---|---|
| (after each) | Status(Energy, Food) |
the text Energy 5, Food 3 |
play |
Play(Energy) |
2 energy less, never below 0 |
eat |
Eat(Food) |
3 food more, never above 10 |
| (warnings) | PetMood(Energy, Food) |
hungry, tired or happy |
Build and test one part at a time
- Write one function. Test it with a few
OUTPUTlines. Then the next one.
FUNCTION Play(Energy : INTEGER) RETURNS INTEGER
DECLARE Left : INTEGER
Left ← Energy - 2
IF Left < 0 THEN
Left ← 0
ENDIF
RETURN Left
ENDFUNCTION
OUTPUT Play(5)
OUTPUT Play(1)
- Test the edges: what happens at 0, at 1, at 10?
Tonight's tasks are the parts
- Each task is one part of the plan.
- Tomorrow you join them together with a game loop.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Part 1 of the plan. Write Status(Energy : INTEGER, Food : INTEGER) RETURNS STRING. It returns the text Energy 5, Food 3 for Status(5, 3).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Part 2. Write Play(Energy : INTEGER) RETURNS INTEGER. Playing uses 2 energy, so it returns Energy - 2. But energy never goes below 0: Play(1) ผลตอบแทน 0.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Part 3. Write Eat(Food : INTEGER) RETURNS INTEGER. Eating adds 3 food, but food is never more than 10: Eat(9) ผลตอบแทน 10.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Part 4. Write PetMood(Energy : INTEGER, Food : INTEGER) RETURNS STRING. It returns "hungry" when food is 0, else "tired" when energy is 0, else "happy".
คลิก Run เพื่อดูผลลัพธ์ที่นี่