נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
45
חלקPart 7: משחקים עם PygameGames with Pygame כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Pixel PlatformerPixel Platformer

Tilemap, מצלמה, Coyote Time, Jump Buffer ומצבי אנימציה.

Tilemaps, a camera, coyote time, jump buffering and animation states.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

קריאת מפהReading a map

תזכורת: מה ביקשוReminder: the task

כתבו load(level, tile) שמחזירה מילון עם רשימות: "solid" (מלבנים (x, y, tile, tile) לכל #), "coins" (מרכזי משבצות c), ו-"start" (פינה של המשבצת P, או (0, 0) אם אין).

Write load(level, tile) returning a dict of lists: "solid" (rects (x, y, tile, tile) for each #), "coins" (centres of c cells), and "start" (the corner of the P cell, or (0, 0) if none).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def load(level, tile):
    out = {"solid": [], "coins": [], "start": (0, 0)}
    for r, row in enumerate(level):
        for c, ch in enumerate(row):
            x, y = c * tile, r * tile
            if ch == "#":
                out["solid"].append((x, y, tile, tile))
            elif ch == "c":
                out["coins"].append((x + tile // 2, y + tile // 2))
            elif ch == "P":
                out["start"] = (x, y)
    return out

print(load(["P.c", "###"], 16))
פלטOutput
{'solid': [(0, 16, 16, 16), (16, 16, 16, 16), (32, 16, 16, 16)], 'coins': [(40, 8)], 'start': (0, 0)}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

תנועה עם התנגשותMoving with collision

תזכורת: מה ביקשוReminder: the task

בלי pygame: כתבו move(p, dx, vy, solids) כש-p הוא רשימה [x, y, w, h] ו-solids רשימת טאפלים. מזיזים ב-x (נעצרים בקיר), ואז ב-y (נוחתים או נתקלים בתקרה). מחזירה (vy, on_ground).

Without pygame: write move(p, dx, vy, solids) where p is a list [x, y, w, h] and solids a list of tuples. Move on x (stopping at walls), then on y (landing or bumping the ceiling). Return (vy, on_ground).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def overlap(a, b):
    return a[0] < b[0] + b[2] and b[0] < a[0] + a[2] and a[1] < b[1] + b[3] and b[1] < a[1] + a[3]

def move(p, dx, vy, solids):
    p[0] += dx
    for s in solids:
        if dx and overlap(p, s):
            p[0] = s[0] - p[2] if dx > 0 else s[0] + s[2]
    p[1] += round(vy)
    on_ground = False
    for s in solids:
        if overlap(p, s):
            if vy > 0:
                p[1], vy, on_ground = s[1] - p[3], 0.0, True
            else:
                p[1], vy = s[1] + s[3], 0.0
    return vy, on_ground

floor = [(0, 100, 200, 16), (100, 84, 16, 16)]
p = [50, 80, 12, 14]
print(move(p, 0, 10, floor), p)
print(move(p, 60, 0, floor), p)
print(move([105, 104, 12, 14], 0, -6, [(100, 90, 16, 16)]))
פלטOutput
(0.0, True) [50, 86, 12, 14]
(0, False) [88, 86, 12, 14]
(0.0, False)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

מצלמהA camera

תזכורת: מה ביקשוReminder: the task

כתבו camera(target_x, cam, screen_w, world_w, ease=0.15) שמחזירה מיקום מצלמה חדש שמתקרב בהדרגה (כמו קפיץ עם ריסון) אל target_x - screen_w // 3, מוגבל לטווח [0, world_w - screen_w]. ואז steps_to_settle(...) שמחזירה כמה קריאות צריך עד שהמצלמה במרחק פחות מפיקסל אחד מהיעד (מעוגל).

Write camera(target_x, cam, screen_w, world_w, ease=0.15) returning a new camera position that moves gradually (like a damped spring) toward target_x - screen_w // 3, clamped to [0, world_w - screen_w]. Then steps_to_settle(...) returning how many calls until the camera is less than one pixel from the goal (clamped).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def camera(target_x, cam, screen_w, world_w, ease=0.15):
    goal = max(0, min(world_w - screen_w, target_x - screen_w // 3))
    return cam + (goal - cam) * ease

def steps_to_settle(target_x, cam, screen_w, world_w, ease=0.15):
    goal = max(0, min(world_w - screen_w, target_x - screen_w // 3))
    n = 0
    while abs(cam - goal) >= 1:
        cam = camera(target_x, cam, screen_w, world_w, ease)
        n += 1
    return n

print(round(camera(400, 0, 480, 736), 1), steps_to_settle(400, 0, 480, 736), steps_to_settle(400, 0, 480, 736, ease=0.5), steps_to_settle(50, 0, 480, 736))
פלטOutput
36.0 34 8 0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

סיירA patroller

תזכורת: מה ביקשוReminder: the task

כתבו patrol(x, d, speed, ground_cells, tile, steps) שמזיזה אויב (x בפיקסלים, רוחב 14) steps צעדים: לפני כל צעד בודקים שהמשבצת שמתחת לנקודה שלפניו (x + 14 + 1 ימינה, או x - 1 שמאלה) נמצאת ב-ground_cells (set של אינדקסי עמודות), אחרת הופכים כיוון. מחזירה (x, d, turns).

Write patrol(x, d, speed, ground_cells, tile, steps) moving an enemy (x in pixels, width 14) for steps steps: before each step check that the cell under the point ahead (x + 14 + 1 to the right, or x - 1 to the left) is in ground_cells (a set of column indexes), otherwise flip direction. Return (x, d, turns).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def patrol(x, d, speed, ground_cells, tile, steps):
    turns = 0
    for _ in range(steps):
        front = x + 15 if d > 0 else x - 1
        if front // tile not in ground_cells:
            d, turns = -d, turns + 1
        x += d * speed
    return x, d, turns

ground = set(range(4, 10))
print(patrol(100, 1, 1, ground, 16, 200))
xs = set()
x, d = 100, 1
for _ in range(300):
    x, d, _ = patrol(x, d, 2, ground, 16, 1)
    xs.add(x)
print(min(xs) >= 64, max(xs) + 14 <= 160)
פלטOutput
(138, 1, 2)
True True

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

Pixel Platformer: השלבPixel Platformer: the level

תזכורת: מה ביקשוReminder: the task

כתבו מחלקה Level(rows, tile=16) שטוענת מפה (# קרקע, c מטבע, P התחלה, F דגל), עם שחקן 12×14 בנקודת ההתחלה, coins, score, won. step(left, right, jump): תנועה אופקית 2 פיקסלים, קפיצה (-6.2) רק על הקרקע, כבידה 0.35 עד 8, התנגשות בהפרדת צירים, איסוף מטבעות (חפיפה עם ריבוע 8×8 במרכז המשבצת), וניצחון בנגיעה במשבצת הדגל.

Write a Level(rows, tile=16) class loading a map (# ground, c coin, P start, F flag), with a 12×14 player at the start, coins, score, won. step(left, right, jump): 2-pixel horizontal movement, a jump (-6.2) only when grounded, gravity 0.35 up to 8, axis-separated collision, coin pickup (overlap with an 8×8 square at the cell centre), and winning on touching the flag cell.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
platformer.py
def overlap(a, b):
    return a[0] < b[0] + b[2] and b[0] < a[0] + a[2] and a[1] < b[1] + b[3] and b[1] < a[1] + a[3]

class Level:
    def __init__(self, rows, tile=16):
        self.solid, self.coins, self.flag, start = [], [], None, (0, 0)
        for r, row in enumerate(rows):
            for c, ch in enumerate(row):
                x, y = c * tile, r * tile
                if ch == "#":
                    self.solid.append((x, y, tile, tile))
                elif ch == "c":
                    self.coins.append((x + tile // 2 - 4, y + tile // 2 - 4, 8, 8))
                elif ch == "P":
                    start = (x, y)
                elif ch == "F":
                    self.flag = (x, y, tile, tile)
        self.p = [start[0], start[1], 12, 14]
        self.vy, self.on_ground, self.score, self.won = 0.0, False, 0, False

    def step(self, left, right, jump):
        if self.won:
            return
        if jump and self.on_ground:
            self.vy = -6.2
        dx = 2 * (right - left)
        self.p[0] += dx
        for s in self.solid:
            if overlap(self.p, s):
                self.p[0] = s[0] - 12 if dx > 0 else s[0] + s[2]
        self.vy = min(8.0, self.vy + 0.35)
        self.p[1] += round(self.vy)
        self.on_ground = False
        for s in self.solid:
            if overlap(self.p, s):
                if self.vy > 0:
                    self.p[1], self.vy, self.on_ground = s[1] - 14, 0.0, True
                else:
                    self.p[1], self.vy = s[1] + s[3], 0.0
        below = [self.p[0], self.p[1] + 1, 12, 14]
        if self.vy >= 0 and any(overlap(below, s) for s in self.solid):
            self.on_ground, self.vy = True, 0.0
        got = [c for c in self.coins if overlap(self.p, c)]
        self.coins = [c for c in self.coins if c not in got]
        self.score += len(got)
        if self.flag and overlap(self.p, self.flag):
            self.won = True

level = Level(["............",
               "...c........",
               "P......#...F",
               "############"])
for frame in range(300):
    x = level.p[0]
    level.step(False, True, 34 <= x <= 38 or x >= 86)
    if level.won:
        break
print(level.won, level.score, frame)
פלטOutput
True 1 87

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

זמן קויוטה וזיכרון קפיצהCoyote time and jump buffering

תזכורת: מה ביקשוReminder: the task

שני טריקים שגורמים לפלטפורמר להרגיש טוב: זמן קויוטה (מותר לקפוץ עד 6 פריימים אחרי שיצאתם מהקרקע) וזיכרון קפיצה (לחיצה עד 6 פריימים לפני הנחיתה נשמרת ומבוצעת בנחיתה). כתבו JumpControl(coyote=6, buffer=6) עם update(on_ground, pressed) שמחזירה True בפריים שבו צריך לקפוץ (ואז מאפסת את שני המונים).

Two tricks that make a platformer feel good: coyote time (jumping allowed up to 6 frames after leaving the ground) and jump buffering (a press up to 6 frames before landing is kept and carried out on landing). Write JumpControl(coyote=6, buffer=6) with update(on_ground, pressed) returning True on the frame a jump should happen (then resetting both counters).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class JumpControl:
    def __init__(self, coyote=6, buffer=6):
        self.coyote, self.buffer = coyote, buffer
        self.since_ground = self.since_press = 999

    def update(self, on_ground, pressed):
        self.since_ground = 0 if on_ground else self.since_ground + 1
        self.since_press = 0 if pressed else self.since_press + 1
        if self.since_ground <= self.coyote and self.since_press <= self.buffer:
            self.since_ground = self.since_press = 999
            return True
        return False

jc = JumpControl()
walk_off = [jc.update(f < 3, f == 7) for f in range(10)]
jc = JumpControl()
early = [jc.update(f >= 6, f == 2) for f in range(10)]
jc = JumpControl()
late = [jc.update(f < 3, f == 12) for f in range(14)]
print(walk_off.index(True), early.index(True), True in late)
פלטOutput
7 6 False

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

עורך שלבים: בדיקת נגישותLevel editor: reachability

תזכורת: מה ביקשוReminder: the task

לפני שמפרסמים שלב, בודקים שאפשר לסיים אותו. כתבו reachable(rows, max_jump=3): מיקומים חוקיים הם משבצות ריקות שיש מתחתן #. מכל מיקום אפשר ללכת ימינה/שמאלה למיקום חוקי באותה שורה, לעלות עד max_jump שורות לעמודה סמוכה (או אותה עמודה), ולרדת כל מספר שורות לעמודה סמוכה. החזירו True אם מ-P אפשר להגיע ל-F (BFS).

Before publishing a level, check it can be finished. Write reachable(rows, max_jump=3): valid spots are empty cells with # below them. From a spot you may walk left/right to a valid spot in the same row, climb up to max_jump rows to an adjacent (or the same) column, and drop any number of rows to an adjacent column. Return True if F is reachable from P (BFS).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from collections import deque

def reachable(rows, max_jump=3):
    R, C = len(rows), len(rows[0])
    find = lambda ch: next((r, c) for r in range(R) for c in range(C) if rows[r][c] == ch)
    standable = lambda r, c: 0 <= r < R - 1 and 0 <= c < C and rows[r][c] != "#" and rows[r + 1][c] == "#"
    start, goal = find("P"), find("F")
    queue, seen = deque([start]), {start}
    while queue:
        r, c = queue.popleft()
        if (r, c) == goal:
            return True
        for nc in (c - 1, c, c + 1):
            for nr in range(max(0, r - max_jump), R - 1):
                if (nr, nc) not in seen and standable(nr, nc):
                    seen.add((nr, nc))
                    queue.append((nr, nc))
    return False

easy = ["......F", ".....##", "P.##...", "#######"]
wall = ["......F", "......#", "......#", "......#", "......#", "P.....#", "#######"]
print(reachable(easy), reachable(wall), reachable(wall, max_jump=5))
פלטOutput
True False True

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich