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

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

Tower Defense: הגנת מגדליםTower Defense

מסלול עם BFS, גלים, בחירת מטרה, כלכלה וממשק כפתורים.

Pathing with BFS, waves, targeting, an economy and a button UI.

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

אורך מסלולPath length

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

כתבו path_length(points) שמחזירה את אורך המסלול (סכום המרחקים בין נקודות עוקבות), ו-frames_to_finish(points, speed) שמחזירה כמה פריימים צריך כדי לעבור אותו (מעוגל למעלה, math.ceil).

Write path_length(points) returning the path's length (the sum of distances between consecutive points), and frames_to_finish(points, speed) returning how many frames it takes to cover it (rounded up, math.ceil).

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

def path_length(points):
    return sum(math.dist(a, b) for a, b in zip(points, points[1:]))

def frames_to_finish(points, speed):
    return math.ceil(path_length(points) / speed)

PATH = [(0, 60), (140, 60), (140, 180), (320, 180), (320, 60), (480, 60)]
print(path_length(PATH), frames_to_finish(PATH, 1.5), frames_to_finish([(0, 0), (3, 4)], 2))
פלטOutput
720.0 480 3

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

תרגילExercise 2

הליכה במסלולWalking the path

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

כתבו מחלקה Walker(path, speed) עם x, y (מתחיל בנקודה הראשונה), target (אינדקס הנקודה הבאה, מתחיל ב-1) ו-done. update() מתקדמת צעד: אם הנקודה הבאה במרחק <= speed, קופצים אליה ומקדמים את target; אחרת זזים צעד מנורמל. כשעוברים את הנקודה האחרונה, done הופך ל-True ו-update לא עושה כלום.

Write a Walker(path, speed) class with x, y (starting at the first point), target (index of the next point, starting at 1) and done. update() takes one step: if the next point is <= speed away, snap to it and advance target; otherwise move a normalised step. Once past the last point, done becomes True and update does nothing.

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

class Walker:
    def __init__(self, path, speed):
        self.path, self.speed = path, speed
        self.x, self.y = path[0]
        self.target, self.done = 1, len(path) < 2

    def update(self):
        if self.done:
            return
        tx, ty = self.path[self.target]
        dx, dy = tx - self.x, ty - self.y
        dist = math.hypot(dx, dy)
        if dist <= self.speed:
            self.x, self.y = tx, ty
            self.target += 1
            self.done = self.target == len(self.path)
        else:
            self.x += dx / dist * self.speed
            self.y += dy / dist * self.speed

w = Walker([(0, 0), (10, 0), (10, 10)], 3)
steps = 0
while not w.done:
    w.update()
    steps += 1
print(steps, (w.x, w.y))
פלטOutput
8 (10, 10)

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

תרגילExercise 3

בחירת מטרהChoosing a target

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

כתבו pick(tower, reach, enemies, mode) כש-enemies רשימת מילונים עם pos, travelled, hp. מחזירה את האויב שנבחר מבין אלה במרחק <= reach, או None אם אין. mode הוא "first" (הכי רחוק במסלול), "close" (הכי קרוב למגדל) או "strong" (הכי הרבה hp).

Write pick(tower, reach, enemies, mode) where enemies is a list of dicts with pos, travelled, hp. Return the chosen enemy among those <= reach away, or None if none. mode is "first" (furthest along), "close" (nearest the tower) or "strong" (most hp).

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

def pick(tower, reach, enemies, mode="first"):
    in_range = [e for e in enemies if math.dist(e["pos"], tower) <= reach]
    keys = {
        "first": lambda e: e["travelled"],
        "close": lambda e: -math.dist(e["pos"], tower),
        "strong": lambda e: e["hp"],
    }
    return max(in_range, key=keys[mode], default=None)

enemies = [{"id": 1, "pos": (100, 60), "travelled": 100, "hp": 3}, {"id": 2, "pos": (140, 120), "travelled": 200, "hp": 9}, {"id": 3, "pos": (150, 175), "travelled": 255, "hp": 1}]
print([pick((150, 110), 70, enemies, m)["id"] for m in ("first", "close", "strong")], pick((0, 0), 10, enemies))
פלטOutput
[3, 2, 2] None

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

תרגילExercise 4

לוח גליםA wave schedule

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

כתבו schedule(waves, pause=120) כש-waves רשימת מילונים עם count, gap, hp. מחזירה רשימת טאפלים (frame, wave_number, hp) לכל אויב, כשגל מתחיל pause פריימים אחרי שהאויב האחרון של הקודם הוצב (כלומר אחרי gap שלו). ו-total_hp(waves) שמחזירה מילון {wave_number: hp_total}.

Write schedule(waves, pause=120) where waves is a list of dicts with count, gap, hp. Return a list of (frame, wave_number, hp) tuples for every enemy, with a wave starting pause frames after the previous wave's last spawn (that is, after its gap). And total_hp(waves) returning a dict {wave_number: hp_total}.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 schedule(waves, pause=120):
    frame, spawns = 0, []
    for number, w in enumerate(waves, start=1):
        for _ in range(w["count"]):
            spawns.append((frame, number, w["hp"]))
            frame += w["gap"]
        frame += pause
    return spawns

def total_hp(waves):
    return {n: w["count"] * w["hp"] for n, w in enumerate(waves, start=1)}

waves = [{"count": 2, "gap": 30, "hp": 3}, {"count": 3, "gap": 10, "hp": 5}]
print(schedule(waves))
print(total_hp(waves))
פלטOutput
[(0, 1, 3), (30, 1, 3), (180, 2, 5), (190, 2, 5), (200, 2, 5)]
{1: 6, 2: 15}

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

תרגילExercise 5

Tower Defense: הסימולציהTower Defense: the simulation

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

כתבו simulate(path, towers, waves, frames) בלי pygame. אויבים (Walker מתרגיל 2 עם hp) מופיעים לפי schedule מתרגיל 4 במהירות 1.5. כל מגדל (x, y) עם טווח 70 ו-cooldown 18 פוגע מיד (בלי קליע) באויב "הראשון" בטווח, ומוריד 1 hp. אויב עם 0 hp מת (+5 זהב); אויב שמסיים את המסלול מוריד חיים. מחזירה מילון lives (מתחיל ב-10), gold (מתחיל ב-0), killed, alive.

Write simulate(path, towers, waves, frames) without pygame. Enemies (exercise 2's Walker with hp) spawn per exercise 4's schedule at speed 1.5. Each tower (x, y) with range 70 and cooldown 18 instantly hits (no bullet) the "first" enemy in range, removing 1 hp. An enemy at 0 hp dies (+5 gold); an enemy finishing the path costs a life. Return a dict of lives (starting at 10), gold (starting at 0), killed, alive.

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

class Walker:
    def __init__(self, path, speed, hp):
        self.path, self.speed, self.hp = path, speed, hp
        self.x, self.y = path[0]
        self.target, self.done, self.travelled = 1, False, 0.0

    def update(self):
        tx, ty = self.path[self.target]
        dx, dy = tx - self.x, ty - self.y
        dist = math.hypot(dx, dy)
        if dist <= self.speed:
            self.x, self.y = tx, ty
            self.target += 1
            self.done = self.target == len(self.path)
        else:
            self.x += dx / dist * self.speed
            self.y += dy / dist * self.speed
        self.travelled += self.speed

def schedule(waves, pause=120):
    frame, spawns = 0, []
    for number, w in enumerate(waves, start=1):
        for _ in range(w["count"]):
            spawns.append((frame, number, w["hp"]))
            frame += w["gap"]
        frame += pause
    return spawns

def simulate(path, towers, waves, frames):
    plan = schedule(waves)
    enemies, timers = [], [0] * len(towers)
    lives, gold, killed = 10, 0, 0
    for frame in range(frames):
        enemies += [Walker(path, 1.5, hp) for f, _, hp in plan if f == frame]
        for e in enemies[:]:
            e.update()
            if e.done:
                enemies.remove(e)
                lives -= 1
        for i, tower in enumerate(towers):
            timers[i] = max(0, timers[i] - 1)
            in_range = [e for e in enemies if math.dist((e.x, e.y), tower) <= 70]
            if in_range and timers[i] == 0:
                target = max(in_range, key=lambda e: e.travelled)
                target.hp -= 1
                timers[i] = 18
                if target.hp <= 0:
                    enemies.remove(target)
                    gold, killed = gold + 5, killed + 1
    return {"lives": lives, "gold": gold, "killed": killed, "alive": len(enemies)}

PATH = [(0, 60), (140, 60), (140, 180), (320, 180), (320, 60), (480, 60)]
WAVES = [{"count": 5, "gap": 40, "hp": 3}, {"count": 6, "gap": 30, "hp": 6}]
print(simulate(PATH, [(90, 110), (230, 130)], WAVES, 1200))
print(simulate(PATH, [(90, 110), (230, 130), (270, 230), (380, 110)], WAVES, 1200))
print(simulate(PATH, [], WAVES, 1200))
פלטOutput
{'lives': 6, 'gold': 35, 'killed': 7, 'alive': 0}
{'lives': 10, 'gold': 55, 'killed': 11, 'alive': 0}
{'lives': -1, 'gold': 0, 'killed': 0, 'alive': 0}

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

אתגרChallenge 1

ירי עם הקדמהLeading the shot

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

קליע ישר (לא מונחה) צריך לכוון לאן שהאויב יהיה. כתבו lead(shooter, target, vel, speed) שמחזירה את נקודת המפגש: הזמן t החיובי הקטן ביותר שבו |target + vel*t - shooter| = speed*t. זו משוואה ריבועית a t² + b t + c = 0 עם a = vx²+vy²-speed², b = 2(dx·vx + dy·vy), c = dx²+dy². החזירו (x, y) מעוגלים לספרה אחת, או None אם אין פתרון חיובי.

A straight (non-homing) bullet must aim where the enemy will be. Write lead(shooter, target, vel, speed) returning the meeting point: the smallest positive t with |target + vel*t - shooter| = speed*t. It's a quadratic a t² + b t + c = 0 with a = vx²+vy²-speed², b = 2(dx·vx + dy·vy), c = dx²+dy². Return (x, y) rounded to one decimal, or None if there's no positive solution.

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

def lead(shooter, target, vel, speed):
    dx, dy = target[0] - shooter[0], target[1] - shooter[1]
    vx, vy = vel
    a = vx * vx + vy * vy - speed * speed
    b = 2 * (dx * vx + dy * vy)
    c = dx * dx + dy * dy
    if abs(a) < 1e-9:
        times = [-c / b] if b else []
    else:
        disc = b * b - 4 * a * c
        if disc < 0:
            return None
        root = math.sqrt(disc)
        times = [(-b - root) / (2 * a), (-b + root) / (2 * a)]
    times = [t for t in times if t > 0]
    if not times:
        return None
    t = min(times)
    return round(target[0] + vx * t, 1), round(target[1] + vy * t, 1)

print(lead((0, 0), (100, 0), (0, 3), 5))
print(lead((0, 0), (100, 0), (0, 0), 5))
print(lead((0, 0), (100, 0), (10, 0), 5))
פלטOutput
(100.0, 75.0)
(100.0, 0.0)
None

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

אתגרChallenge 2

איפה לבנות?Where to build?

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

כתבו best_spot(path, spots, reach, step=2): לכל מקום אפשרי ב-spots, מדדו כמה מהמסלול נמצא בטווח שלו. דוגמים נקודות לאורך המסלול כל step פיקסלים (כולל נקודת ההתחלה של כל קטע), וסופרים כמה במרחק <= reach. מחזירה (spot, count) של המקום הטוב ביותר (בתיקו, הראשון).

Write best_spot(path, spots, reach, step=2): for each candidate in spots, measure how much of the path is within range. Sample points along the path every step pixels (including each segment's start), and count how many are <= reach away. Return (spot, count) for the best spot (on a tie, the first).

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

def samples(path, step):
    points = []
    for a, b in zip(path, path[1:]):
        length = math.dist(a, b)
        for i in range(int(length // step)):
            f = i * step / length
            points.append((a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f))
    return points

def best_spot(path, spots, reach, step=2):
    pts = samples(path, step)
    scored = [(s, sum(math.dist(p, s) <= reach for p in pts)) for s in spots]
    return max(scored, key=lambda pair: pair[1])

PATH = [(0, 60), (140, 60), (140, 180), (320, 180), (320, 60), (480, 60)]
print(best_spot(PATH, [(90, 110), (230, 130), (270, 230), (380, 110), (230, 60)], 70))
פלטOutput
((90, 110), 98)

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

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