Night 28: Plan your project
你已使用 Python 或伪代码完成过这个夜间练习,两种语言均计入完成记录。你可以再次练习。
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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 |
English
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 |
English
Break it into small parts
- A big program is many small parts. Each part is one function.
| 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) | pet_mood(energy, food) |
hungry, tired or happy |
English
Build and test one part at a time
- Write one function. Test it with a few
printlines. Then the next one.
def play(energy):
energy = energy - 2
if energy < 0:
energy = 0
return energy
print(play(5))
print(play(1))
- Test the edges: what happens at 0, at 1, at 10?
English
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. Define status(energy, food). It 返回值 the text Energy 5, Food 3 for status(5, 3).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Part 2. Define play(energy). Playing uses 2 energy, so it returns energy - 2. But energy never goes below 0: play(1) 返回值 0.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Part 3. Define eat(food). Eating adds 3 food, but food is never more than 10: eat(9) 返回值 10.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Part 4. Define pet_mood(energy, food). It returns "hungry" when food is 0, else "tired" when energy is 0, else "happy".
点击“运行”查看此处输出。