Night 24: Move around
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: move around
- Your pet has a map. Tonight it walks around on it!
- Nothing new to learn: you use
input(),whileandifon a map.
Words for tonight
| Word | Meaning |
|---|---|
| move | go from one place to another |
| position | where something is: x and y |
| command | a word that tells the program what to do |
Where is the pet?
- Two numbers say where the pet is:
x(left–right) andy(up–down). - On a screen,
y = 0is the top row. So "up" makesysmaller.
| Move | Change |
|---|---|
| up | y = y - 1 |
| down | y = y + 1 |
| left | x = x - 1 |
| right | x = x + 1 |

The game loop
- Read a command, change the world, repeat. Every game works like this.
x = 2
y = 2
moves = ["up", "left", "left"]
for move in moves:
if move == "up":
y = y - 1
elif move == "left":
x = x - 1
print("Now at", x, y)
- In the tasks, the moves come from
input()until the player typesstop.
Stay on the map
- Check the edge before you move.
x = 0
move = "left"
if move == "left" and x > 0:
x = x - 1
print(x)
xstays 0: the pet is already at the left wall.- Now take your pet for a walk!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Your pet is at x = 2, y = 2. Read one move: up, down, left หรือ right. Change x หรือ y, then print them. left gives 1 2. up makes y smaller.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now read moves again and again, until the move is stop. Change x และ y for each move. At the end, print x และ y.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The map is 5 × 5: x และ y go from 0 ไป 4. Do not let the pet walk off the map. A move into the wall does nothing.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
After the moves, draw the 5 × 5 map: P where the pet is, . everywhere else. Row y and column x hold the P.
คลิก Run เพื่อดูผลลัพธ์ที่นี่