جواب «The Robot Follows the Water» چالش 6 از جلسهی 14
سؤال
روی صفحهی بازی! ماز کشیده شده، dist و کوتاهترین راه path (از S تا G) آمادهاند. دو کار کن:
۱. در draw() روی هر خانهای که در dist است، شمارهاش را با screen.draw.text(str(dist[cell]), ...) بنویس.
۲. تابع walk() را کامل کن: هر بار که صدا زده میشود (هر ۰٫۳ ثانیه)، اگر step کمتر از len(path) - 1 است یکی زیادش کن و ربات را به خانهی path[step] ببر (مرکز خانه: c * SIZE + 30 و r * SIZE + 30).
راهنما
در draw(): for cell in dist: بعد r, c = cell و screen.draw.text(str(dist[cell]), (c * SIZE + 5, r * SIZE + 5), color="blue"). در walk(): if step < len(path) - 1: بعد step += 1، r, c = path[step] و robot.pos = (c * SIZE + 30, r * SIZE + 30).
یک جواب درست
import pgzrun
maze = [
"S..#....",
".#.#.##.",
".#...#..",
".####.#.",
"......#G",
]
SIZE = 60
WIDTH = 8 * SIZE
HEIGHT = 5 * SIZE
def neighbours(r, c):
result = []
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr = r + dr
nc = c + dc
if 0 <= nr < len(maze) and 0 <= nc < len(maze[0]) and maze[nr][nc] != "#":
result.append((nr, nc))
return result
dist = {(0, 0): 0}
queue = [(0, 0)]
while queue:
cell = queue.pop(0)
for nxt in neighbours(cell[0], cell[1]):
if nxt not in dist:
dist[nxt] = dist[cell] + 1
queue.append(nxt)
cell = (4, 7)
path = [cell]
while dist[cell] > 0:
for nxt in neighbours(cell[0], cell[1]):
if dist.get(nxt, -1) == dist[cell] - 1:
cell = nxt
break
path.append(cell)
path.reverse()
robot = Actor("robot", (30, 30))
step = 0
def walk():
global step
if step < len(path) - 1:
step += 1
r, c = path[step]
robot.pos = (c * SIZE + 30, r * SIZE + 30)
clock.schedule_interval(walk, 0.3)
def draw():
screen.fill("white")
for r in range(len(maze)):
for c in range(len(maze[0])):
if maze[r][c] == "#":
screen.draw.filled_rect(Rect(c * SIZE, r * SIZE, SIZE, SIZE), "gray")
for cell in dist:
r, c = cell
screen.draw.text(str(dist[cell]), (c * SIZE + 5, r * SIZE + 5), color="blue")
robot.draw()
pgzrun.go()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن