بتل کد Battle Codeدارد باز می‌شود…

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).

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

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")
    robot.draw()

pgzrun.go()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 14: راه را پیدا کن

بیشتر بخوان: بازی‌سازی با پایتون و Pygame Zero