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

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

Flappy: ציפור מעופפתFlappy

Sprite sheet, אנימציית פריימים, Parallax ו-dt.

Sprite sheets, frame animation, parallax and dt.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

קשת קפיצהA jump arc

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

כתבו simulate(frames, flaps, gravity=0.35, flap=-6.0, start=160.0, max_fall=10.0) שמחזירה רשימת מיקומי y (מעוגלים ל-1) לכל פריים. בפריים שנמצא ב-flaps (set) המהירות נקבעת ל-flap; בכל פריים מוסיפים כבידה (עד max_fall) ואז מזיזים.

Write simulate(frames, flaps, gravity=0.35, flap=-6.0, start=160.0, max_fall=10.0) returning y positions (rounded to 1) for every frame. On a frame in flaps (a set) the velocity is set to flap; every frame add gravity (up to max_fall) and then move.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 simulate(frames, flaps, gravity=0.35, flap=-6.0, start=160.0, max_fall=10.0):
    y, vel, out = start, 0.0, []
    for f in range(frames):
        if f in flaps:
            vel = flap
        vel = min(max_fall, vel + gravity)
        y += vel
        out.append(round(y, 1))
    return out

path = simulate(30, {0})
print(path[:4], min(path), path[-1])
פלטOutput
[154.3, 149.0, 144.1, 139.5] 111.5 142.8

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

תרגילExercise 2

מלבני צינורPipe rectangles

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

בלי pygame: כתבו pipe_rects(x, gap_y, gap, height, width=40) שמחזירה שני טאפלים (x, y, w, h): העליון מ-0 עד תחילת הרווח, והתחתון מסוף הרווח עד height. ו-random_gap(rng, gap, height, margin=20) שמחזירה מרכז רווח כך שכל הרווח בתוך המסך עם שוליים.

Without pygame: write pipe_rects(x, gap_y, gap, height, width=40) returning two tuples (x, y, w, h): the top one from 0 to the gap's start, and the bottom one from the gap's end to height. And random_gap(rng, gap, height, margin=20) returning a gap centre so the whole gap is on screen with margins.

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

def pipe_rects(x, gap_y, gap, height, width=40):
    top_h = gap_y - gap // 2
    bottom_y = gap_y + gap // 2
    return (x, 0, width, top_h), (x, bottom_y, width, height - bottom_y)

def random_gap(rng, gap, height, margin=20):
    return rng.randint(gap // 2 + margin, height - gap // 2 - margin)

print(pipe_rects(300, 160, 110, 320))
rng = random.Random(4)
gaps = [random_gap(rng, 110, 320) for _ in range(1000)]
print(min(gaps), max(gaps))
פלטOutput
((300, 0, 40, 105), (300, 215, 40, 105))
75 245

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

תרגילExercise 3

ניקוד בלי כפילויותScoring without duplicates

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

כתבו advance(pipes, speed, bird_x, pipe_w=40) שמזיזה כל צינור (מילון עם x ו-scored) שמאלה ב-speed, מסמנת ומחזירה כמה צינורות חדשים עברו את הציפור (קצה ימני < bird_x), ומוחקת צינורות שיצאו מהמסך (x + pipe_w < 0). הרשימה מתעדכנת במקום.

Write advance(pipes, speed, bird_x, pipe_w=40) moving every pipe (a dict with x and scored) left by speed, marking and returning how many new pipes passed the bird (right edge < bird_x), and removing pipes off screen (x + pipe_w < 0). The list is updated in place.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 advance(pipes, speed, bird_x, pipe_w=40):
    points = 0
    for p in pipes:
        p["x"] -= speed
        if not p["scored"] and p["x"] + pipe_w < bird_x:
            p["scored"] = True
            points += 1
    pipes[:] = [p for p in pipes if p["x"] + pipe_w >= 0]
    return points

pipes = [{"x": 60.0, "scored": False}, {"x": 200.0, "scored": False}]
print(advance(pipes, 15, 90), advance(pipes, 15, 90), len(pipes))
for _ in range(10):
    advance(pipes, 15, 90)
print(pipes)
פלטOutput
1 0 2
[{'x': 20.0, 'scored': True}]

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

תרגילExercise 4

תיבת פגיעהA hitbox

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

כתבו hitbox(cx, cy, w, h, shrink=0.2) שמחזירה מלבן (x, y, w, h) שלמים, ממורכז באותה נקודה וקטן בכל כיוון ב-shrink מהגודל (למשל 0.2 = רוחב × 0.8), ו-hits_pipe(box, pipe_rects) שמחזירה True אם יש חפיפה עם אחד המלבנים.

Write hitbox(cx, cy, w, h, shrink=0.2) returning an integer rect (x, y, w, h), centred on the same point and smaller by shrink of the size (e.g. 0.2 = width × 0.8), and hits_pipe(box, pipe_rects) returning True if it overlaps any of the rects.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 hitbox(cx, cy, w, h, shrink=0.2):
    nw, nh = round(w * (1 - shrink)), round(h * (1 - shrink))
    return round(cx - nw / 2), round(cy - nh / 2), nw, nh

def hits_pipe(box, pipe_rects):
    x, y, w, h = box
    return any(x < px + pw and px < x + w and y < py + ph and py < y + h for px, py, pw, ph in pipe_rects)

box = hitbox(90, 150, 30, 22)
print(box, hits_pipe(box, [(103, 0, 40, 140)]), hits_pipe(box, [(101, 0, 40, 143)]))
פלטOutput
(78, 141, 24, 18) False True

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

תרגילExercise 5

Flappy: לוגיקת המשחקFlappy: game logic

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

כתבו מחלקה Flappy(seed=0, w=480, h=320) עם ציפור ב-x=90 (y במרכז, מהירות 0), pipes, score, alive, ו-frame. flap() קובעת מהירות -6. tick(): כל 90 פריימים (מפריים 0) מוסיפה צינור ב-x=w עם רווח אקראי (110, שוליים 20), כבידה 0.35 עד 10, תנועה, קידום צינורות במהירות 2.5 עם ניקוד, ומוות בפגיעה בצינור (תיבת פגיעה 24×18) או ברצפה/תקרה.

Write a Flappy(seed=0, w=480, h=320) class with a bird at x=90 (y in the middle, velocity 0), pipes, score, alive, and frame. flap() sets velocity -6. tick(): every 90 frames (from frame 0) adds a pipe at x=w with a random gap (110, margin 20), gravity 0.35 up to 10, movement, pipe advance at speed 2.5 with scoring, and death on hitting a pipe (a 24×18 hitbox) or the floor/ceiling.

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

class Flappy:
    def __init__(self, seed=0, w=480, h=320):
        self.rng = random.Random(seed)
        self.w, self.h = w, h
        self.y, self.vel = h / 2, 0.0
        self.pipes, self.score, self.alive, self.frame = [], 0, True, 0

    def flap(self):
        self.vel = -6.0

    def _rects(self, p):
        top_h = p["gap"] - 55
        return [(p["x"], 0, 40, top_h), (p["x"], p["gap"] + 55, 40, self.h - p["gap"] - 55)]

    def tick(self):
        if not self.alive:
            return
        if self.frame % 90 == 0:
            self.pipes.append({"x": float(self.w), "gap": self.rng.randint(75, self.h - 75), "scored": False})
        self.frame += 1
        self.vel = min(10.0, self.vel + 0.35)
        self.y += self.vel
        for p in self.pipes:
            p["x"] -= 2.5
            if not p["scored"] and p["x"] + 40 < 90:
                p["scored"], self.score = True, self.score + 1
        self.pipes = [p for p in self.pipes if p["x"] + 40 >= 0]
        box = (78, round(self.y - 9), 24, 18)
        hit = any(box[0] < x + w and x < box[0] + box[2] and box[1] < y + h and y < box[1] + box[3]
                  for p in self.pipes for x, y, w, h in self._rects(p))
        if hit or self.y < 0 or self.y > self.h:
            self.alive = False

g = Flappy(seed=8)
while g.alive and g.frame < 600:
    nxt = next((p for p in g.pipes if p["x"] + 40 >= 78), None)
    if g.y > (nxt["gap"] if nxt else g.h / 2) + 12 and g.vel > -1:
        g.flap()
    g.tick()
print(g.alive, g.score, g.frame)
פלטOutput
True 5 600

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

אתגרChallenge 1

קושי מתכוונןAdjustable difficulty

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

כתבו settings(level) שמחזירה מילון gap, speed, spawn_every לפי רמה 1–10 (אינטרפולציה ליניארית בין רמה 1: 140, 2.0, 110 לרמה 10: 90, 4.0, 70, ומעוגל: gap ו-spawn_every למספר שלם, speed ל-2). רמה מחוץ לטווח מוגבלת אליו. ואז reachable(gap, speed, spawn_every, flap=-6, gravity=0.35) שמחזירה True אם המרחק בין צינורות (speed × spawn_every) גדול ממרחק הקשת של קפיצה אחת (המרחק האופקי עד שהציפור חוזרת לגובה המקורי), כך שאפשר להספיק לתקן.

Write settings(level) returning a dict gap, speed, spawn_every for levels 1–10 (linear interpolation from level 1: 140, 2.0, 110 to level 10: 90, 4.0, 70, rounded: gap and spawn_every to integers, speed to 2). Levels outside are clamped. Then reachable(gap, speed, spawn_every, flap=-6, gravity=0.35) returning True if the distance between pipes (speed × spawn_every) exceeds one flap's arc distance (the horizontal distance until the bird returns to its starting height), so there's time to correct.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 settings(level):
    t = (max(1, min(10, level)) - 1) / 9
    lerp = lambda a, b: a + (b - a) * t
    return {"gap": round(lerp(140, 90)), "speed": round(lerp(2.0, 4.0), 2), "spawn_every": round(lerp(110, 70))}

def reachable(gap, speed, spawn_every, flap=-6, gravity=0.35):
    y, vel, frames = 0.0, float(flap), 0
    while True:
        vel += gravity
        y += vel
        frames += 1
        if y >= 0:
            break
    return speed * spawn_every > speed * frames

for lvl in (0, 1, 5, 10, 99):
    s = settings(lvl)
    print(lvl, s, reachable(**s))
פלטOutput
0 {'gap': 140, 'speed': 2.0, 'spawn_every': 110} True
1 {'gap': 140, 'speed': 2.0, 'spawn_every': 110} True
5 {'gap': 118, 'speed': 2.89, 'spawn_every': 92} True
10 {'gap': 90, 'speed': 4.0, 'spawn_every': 70} True
99 {'gap': 90, 'speed': 4.0, 'spawn_every': 70} True

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

אתגרChallenge 2

שיא נשמרA saved best score

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

כתבו update_best(path, score) ששומרת שיא בקובץ JSON ({"best": N, "games": N}): מגדילה את מספר המשחקים, מעדכנת שיא אם צריך, ומחזירה (best, is_new). קובץ חסר או פגום מתחיל מאפס, והכתיבה דרך קובץ זמני.

Write update_best(path, score) keeping a best score in a JSON file ({"best": N, "games": N}): increments the game count, updates the best if needed, and returns (best, is_new). A missing or broken file starts from zero, and writing goes through a temp file.

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

def update_best(path, score):
    p = Path(path)
    data = {"best": 0, "games": 0}
    try:
        data.update(json.loads(p.read_text()))
    except (FileNotFoundError, json.JSONDecodeError):
        pass
    data["games"] += 1
    is_new = score > data["best"]
    if is_new:
        data["best"] = score
    tmp = p.with_suffix(".tmp")
    tmp.write_text(json.dumps(data))
    tmp.replace(p)
    return data["best"], is_new

print([update_best("best.json", s) for s in (3, 7, 5, 7)], json.loads(Path("best.json").read_text()))
Path("best.json").write_text("{broken")
print(update_best("best.json", 2))
פלטOutput
[(3, True), (7, True), (7, False), (7, False)] {'best': 7, 'games': 4}
(2, True)

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

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