נבנה על ידי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.

01מסלול נקודות ציוןA waypoint path

ב-Tower Defense האויבים לא חופשיים: הם הולכים במסלול קבוע שמוגדר כרשימת נקודות ציון. בכל פריים מחשבים את הכיוון לנקודה הבאה, מנרמלים אותו (מחלקים באורך, כמו בפרק הווקטורים), וזזים צעד באורך המהירות. אם הנקודה קרובה יותר מצעד אחד, קופצים אליה ועוברים לבאה, כך שאין "ריצוד" סביב הנקודה:

In Tower Defense enemies aren't free: they walk a fixed path defined as a list of waypoints. Each frame, compute the direction to the next point, normalise it (divide by the length, as in the vectors lesson), and move one speed-length step. If the point is closer than one step, snap to it and move on, so there's no "jitter" around the point:

path.py
import math

PATH = [(0, 60), (140, 60), (140, 180), (320, 180)]

def walk(speed, frames):
    x, y = PATH[0]
    target = 1
    for frame in range(frames):
        if target == len(PATH):
            return f"reached the end on frame {frame}"
        tx, ty = PATH[target]
        dx, dy = tx - x, ty - y
        dist = math.hypot(dx, dy)
        if dist <= speed:
            x, y, target = tx, ty, target + 1
        else:
            x, y = x + dx / dist * speed, y + dy / dist * speed
    return f"at ({x:.0f}, {y:.0f}) heading to point {target}"

print(walk(2, 50))
print(walk(2, 200))
print(walk(3, 200))
פלטOutput
at (100, 60) heading to point 1
at (280, 180) heading to point 3
reached the end on frame 147
אנלוגיה מהחייםReal-life analogy

נקודות ציון הן כמו שלטים בשביל טיול: לא צריך לדעת את כל הדרך, רק לאן השלט הבא מצביע.

Waypoints are like trail markers: you don't need the whole route, just where the next marker points.

טעות נפוצהCommon mistake

זזים בכיוון לא מנורמל, והאויב מגיע בקפיצה אחת.

Moving by an un-normalised direction, so the enemy arrives in one jump.

path.py
import math
x, y, tx, ty, speed = 0, 60, 140, 60, 2
x, y = x + (tx - x) * speed, y + (ty - y) * speed
assert x <= 2, f"the enemy jumped to x={x}: divide dx, dy by the distance before multiplying by speed"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/path.py", line 4, in <module>
    assert x <= 2, f"the enemy jumped to x={x}: divide dx, dy by the distance before multiplying by speed"
           ^^^^^^
AssertionError: the enemy jumped to x=280: divide dx, dy by the distance before multiplying by speed
בעברית פשוטה: In plain words: AssertionError: the enemy jumped to x=280: ...: dx הוא כל המרחק. מחלקים ב-math.hypot(dx, dy) כדי לקבל כיוון באורך 1, ורק אז כופלים במהירות.AssertionError: the enemy jumped to x=280: ...: dx is the whole distance. Divide by math.hypot(dx, dy) for a length-1 direction, then multiply by speed.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02טווח ובחירת מטרהRange and targeting

מגדל רואה רק אויבים בתוך עיגול הטווח שלו: math.dist נותן מרחק בין שתי נקודות. מבין אלה שבטווח צריך לבחור מטרה. האסטרטגיה הנפוצה היא "הראשון": מי שהתקדם הכי רחוק במסלול, כי הוא הכי קרוב לגרום נזק. max עם key עושה את זה בשורה, ואפשר להחליף לקרוב ביותר או לחזק ביותר:

A tower sees only enemies inside its range circle: math.dist gives the distance between two points. Among those in range you need to pick a target. The common strategy is "first": whoever has travelled furthest along the path, since they're closest to doing damage. max with key does it in one line, and you can swap to closest or strongest:

targeting.py
import math

enemies = [
    {"name": "slime", "pos": (100, 60), "travelled": 100, "hp": 3},
    {"name": "golem", "pos": (140, 120), "travelled": 200, "hp": 9},
    {"name": "bat", "pos": (150, 175), "travelled": 255, "hp": 1},
    {"name": "far", "pos": (300, 180), "travelled": 400, "hp": 2},
]
tower, reach = (150, 110), 70
in_range = [e for e in enemies if math.dist(e["pos"], tower) <= reach]
print("in range:", [e["name"] for e in in_range])
print("first:", max(in_range, key=lambda e: e["travelled"])["name"])
print("closest:", min(in_range, key=lambda e: math.dist(e["pos"], tower))["name"])
print("strongest:", max(in_range, key=lambda e: e["hp"])["name"])
פלטOutput
in range: ['golem', 'bat']
first: bat
closest: golem
strongest: golem
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

זה כמו שוער שבוחר באיזה כדור לטפל: לא בכל מה שבמגרש, רק במה שקרוב לשער, ובדרך כלל במה שהכי קרוב להבקיע.

It's like a goalkeeper choosing which ball to handle: not everything on the pitch, just what's near the goal, usually whatever's closest to scoring.

טעות נפוצהCommon mistake

max על רשימה ריקה כשאין אף אויב בטווח.

max on an empty list when no enemy is in range.

targeting.py
in_range = []
target = max(in_range, key=lambda e: e["travelled"])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/targeting.py", line 2, in <module>
    target = max(in_range, key=lambda e: e["travelled"])
ValueError: max() iterable argument is empty
בעברית פשוטה: In plain words: ValueError: max() iterable argument is empty: בודקים if in_range: לפני הבחירה, או max(in_range, key=..., default=None).ValueError: max() iterable argument is empty: check if in_range: before choosing, or use max(in_range, key=..., default=None).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03קצב אשFire rate

בלי הגבלה מגדל היה יורה בכל פריים, 60 פעם בשנייה. זמן טעינה הוא מונה: כשיורים מציבים בו מספר, בכל פריים מורידים אחד, ויורים שוב רק כשהגיע לאפס. ההבדל בין מגדל מהיר לאיטי הוא רק המספר הזה. הנה שלושה מגדלים לאורך שתי שניות:

Without a limit a tower would fire every frame, 60 times a second. A cooldown is a counter: on firing you set it, each frame you subtract one, and you fire again only when it reaches zero. The only difference between a fast and a slow tower is that number. Here are three towers over two seconds:

cooldown.py
def shots(cooldown_frames, seconds, fps=60):
    timer, fired = 0, 0
    for _ in range(seconds * fps):
        timer = max(0, timer - 1)
        if timer == 0:
            fired += 1
            timer = cooldown_frames
    return fired

for name, cd in [("arrow", 15), ("cannon", 45), ("laser", 4)]:
    print(f"{name:<7} cooldown {cd:>2} -> {shots(cd, 2)} shots in 2 s ({60 / cd:.1f}/s)")
פלטOutput
arrow   cooldown 15 -> 8 shots in 2 s (4.0/s)
cannon  cooldown 45 -> 3 shots in 2 s (1.3/s)
laser   cooldown  4 -> 30 shots in 2 s (15.0/s)
אנלוגיה מהחייםReal-life analogy

זמן טעינה הוא כמו מכונת קפה: לוחצים, מקבלים כוס, ועד שהיא מוכנה שוב שום לחיצה לא תעזור.

A cooldown is like a coffee machine: press, get a cup, and until it's ready again no press will help.

טעות נפוצהCommon mistake

שוכחים להוריד את המונה, והמגדל יורה פעם אחת בלבד.

Forgetting to count down, so the tower fires only once.

cooldown.py
timer, fired = 0, 0
for _ in range(120):
    if timer == 0:
        fired += 1
        timer = 15
assert fired > 1, "the timer never went down: subtract one every frame before checking it"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/cooldown.py", line 6, in <module>
    assert fired > 1, "the timer never went down: subtract one every frame before checking it"
           ^^^^^^^^^
AssertionError: the timer never went down: subtract one every frame before checking it
בעברית פשוטה: In plain words: AssertionError: the timer never went down: ...: בכל פריים timer = max(0, timer - 1), ורק אז בודקים.AssertionError: the timer never went down: ...: every frame timer = max(0, timer - 1), and only then check.

המגדל יורה רק כשהמונה מגיע לאפס.

The tower fires only when the counter reaches zero.

עוד דוגמה: מגדל עם זמן טעינהOne more: a tower with a cooldown
example.py
timer, shots = 0, []
for frame in range(10):
    timer = max(0, timer - 1)
    if timer == 0:
        shots.append(frame)
        timer = 4
print("fired on frames", shots)
פלטOutput
fired on frames [0, 4, 8]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04קליעים מונחיםHoming projectiles

קליע ישר עלול לפספס אויב זז. קליע מונחה מחשב בכל פריים מחדש את הכיוון אל המטרה ומתקדם אליה, בדיוק כמו אויב שהולך לנקודת ציון, רק שהנקודה זזה. כשהמרחק קטן מסף, זו פגיעה. ואם מישהו אחר כבר הרג את המטרה? מוחקים את הקליע, אחרת הוא ירדוף אחרי רוח:

A straight bullet may miss a moving enemy. A homing bullet recomputes the direction to its target every frame and moves toward it, exactly like an enemy walking to a waypoint, except the point moves. When the distance drops below a threshold, it's a hit. And if someone else already killed the target? Delete the bullet, or it chases a ghost:

homing.py
import math

def chase(bullet, target, target_vel, speed=6, frames=60):
    bx, by = bullet
    tx, ty = target
    for frame in range(frames):
        tx, ty = tx + target_vel[0], ty + target_vel[1]
        dx, dy = tx - bx, ty - by
        dist = math.hypot(dx, dy)
        if dist < 6:
            return f"hit on frame {frame} at ({tx:.0f}, {ty:.0f})"
        bx, by = bx + dx / dist * speed, by + dy / dist * speed
    return "missed"

print(chase((0, 0), (100, 0), (0, 0)))
print(chase((0, 0), (100, 0), (0, 2)))
print(chase((0, 0), (100, 0), (7, 0)))
פלטOutput
hit on frame 16 at (100, 0)
hit on frame 18 at (100, 38)
missed
אנלוגיה מהחייםReal-life analogy

קליע מונחה הוא כמו כלב שרודף אחרי כדור מתגלגל: הוא לא מחשב מראש, רק מסתכל שוב ושוב איפה הכדור עכשיו.

A homing bullet is like a dog chasing a rolling ball: no planning ahead, just looking again and again at where the ball is now.

טעות נפוצהCommon mistake

מוחקים מהרשימה אויב שכבר נמחק.

Removing an enemy that's already been removed.

homing.py
enemies = ["slime"]
hits = ["slime", "slime"]
for target in hits:
    enemies.remove(target)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/homing.py", line 4, in <module>
    enemies.remove(target)
    ~~~~~~~~~~~~~~^^^^^^^^
ValueError: list.remove(x): x not in list
בעברית פשוטה: In plain words: ValueError: list.remove(x): x not in list: שני קליעים פגעו באותו אויב באותו פריים. בודקים if target in enemies: לפני remove.ValueError: list.remove(x): x not in list: two bullets hit the same enemy in one frame. Check if target in enemies: before remove.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05גלים וכלכלהWaves and economy

משחק Tower Defense הוא איזון: גלים שמתחזקים, מול זהב שמרוויחים על כל הריגה וקונים בו מגדלים. נוח לתאר גלים כנתונים (רשימת מילונים) ולא כקוד, כך שקל לכוונן. הפונקציה הזאת מייצרת לוח זמנים של הופעות ומחשבת כמה זהב אפשר להרוויח בכל גל:

Tower Defense is a balance: waves that grow stronger, against gold you earn per kill and spend on towers. It's convenient to describe waves as data (a list of dicts) rather than code, so they're easy to tune. This function builds a spawn schedule and works out how much gold each wave can earn:

waves.py
WAVES = [
    {"count": 5, "gap": 40, "hp": 3, "reward": 5},
    {"count": 8, "gap": 30, "hp": 5, "reward": 6},
    {"count": 12, "gap": 20, "hp": 8, "reward": 8},
]

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

plan = schedule(WAVES)
print(len(plan), "enemies; last one on frame", plan[-1][0])
for number, w in enumerate(WAVES, start=1):
    print(f"wave {number}: total hp {w['count'] * w['hp']:>3}, gold {w['count'] * w['reward']}")
פלטOutput
25 enemies; last one on frame 900
wave 1: total hp  15, gold 25
wave 2: total hp  40, gold 48
wave 3: total hp  96, gold 96
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

גלים הם כמו שיעורי כושר: מתחילים קל, מוסיפים משקל בהדרגה, ונותנים מנוחה קצרה בין סטים.

Waves are like a workout: start light, add weight gradually, and rest briefly between sets.

טעות נפוצהCommon mistake

קונים מגדל בלי לבדוק שיש מספיק זהב.

Buying a tower without checking there's enough gold.

waves.py
gold, cost = 30, 50
gold -= cost
assert gold >= 0, f"gold went to {gold}: check gold >= cost before buying"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/waves.py", line 3, in <module>
    assert gold >= 0, f"gold went to {gold}: check gold >= cost before buying"
           ^^^^^^^^^
AssertionError: gold went to -20: check gold >= cost before buying
בעברית פשוטה: In plain words: AssertionError: gold went to -20: ...: בודקים if gold >= cost: ורק אז מורידים ובונים.AssertionError: gold went to -20: ...: check if gold >= cost: and only then subtract and build.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06Tower Defense: המשחקTower Defense: the game

המשחק כולו: גלים של אויבים שהולכים במסלול, ארבעה מגדלים שבוחרים את הראשון בטווח ויורים קליעים מונחים עם זמן טעינה, פס חיים מעל כל אויב, וחיים שיורדים כשמישהו מגיע לסוף. במחשב שלכם הוסיפו בניית מגדל בלחיצת עכבר אם יש זהב:

The whole game: waves of enemies walking the path, four towers picking the first in range and firing homing bullets with a cooldown, a health bar above each enemy, and lives dropping when someone reaches the end. On your computer, add building a tower with a mouse click if there's enough gold:

tower_defense.py
import math
import pygame

PATH = [(0, 60), (140, 60), (140, 180), (320, 180), (320, 60), (480, 60)]
TOWERS = [(90, 110), (230, 130), (270, 230), (380, 110)]
W, H = 480, 260
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 22)


class Enemy:
    def __init__(self, hp, speed):
        self.x, self.y = PATH[0]
        self.target, self.hp, self.max_hp, self.speed = 1, hp, hp, speed
        self.travelled = 0.0

    def update(self):
        tx, ty = 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
        else:
            self.x += dx / dist * self.speed
            self.y += dy / dist * self.speed
        self.travelled += self.speed
        return self.target >= len(PATH)


towers = [{"pos": p, "range": 70, "cooldown": 0} for p in TOWERS]
enemies, bullets, lives, killed, gold = [], [], 10, 0, 50
for frame in range(900):
    if frame % 40 == 0 and frame < 640:
        wave = frame // 200
        enemies.append(Enemy(hp=3 + wave * 2, speed=1.2 + wave * 0.2))
    for e in enemies[:]:
        if e.update():
            enemies.remove(e)
            lives -= 1
    for t in towers:
        t["cooldown"] = max(0, t["cooldown"] - 1)
        tx, ty = t["pos"]
        in_range = [e for e in enemies if math.dist((e.x, e.y), (tx, ty)) <= t["range"]]
        if in_range and t["cooldown"] == 0:
            target = max(in_range, key=lambda e: e.travelled)
            bullets.append([tx, ty, target])
            t["cooldown"] = 18
    for b in bullets[:]:
        x, y, target = b
        dx, dy = target.x - x, target.y - y
        dist = math.hypot(dx, dy)
        if dist < 6:
            bullets.remove(b)
            target.hp -= 1
            if target.hp == 0 and target in enemies:
                enemies.remove(target)
                killed, gold = killed + 1, gold + 5
        elif target not in enemies:
            bullets.remove(b)
        else:
            b[0], b[1] = x + dx / dist * 6, y + dy / dist * 6
    screen.fill((28, 36, 30))
    pygame.draw.lines(screen, (120, 100, 70), False, PATH, 22)
    for t in towers:
        pygame.draw.circle(screen, (60, 80, 70), t["pos"], t["range"], 1)
        pygame.draw.rect(screen, (90, 170, 255), (t["pos"][0] - 9, t["pos"][1] - 9, 18, 18), border_radius=4)
    for e in enemies:
        pygame.draw.circle(screen, (235, 90, 90), (round(e.x), round(e.y)), 7)
        pygame.draw.rect(screen, (70, 220, 120), (e.x - 8, e.y - 13, 16 * e.hp / e.max_hp, 3))
    for x, y, _ in bullets:
        pygame.draw.circle(screen, (255, 230, 120), (round(x), round(y)), 3)
    screen.blit(font.render(f"Lives {lives}   Gold {gold}   Defeated {killed}", True, (240, 240, 240)), (8, 236))
    pygame.display.flip()
    if frame == 520:
        break
print("lives:", lives, "defeated:", killed, "gold:", gold, "on the path:", len(enemies))
pygame.quit()
פלטOutput
lives: 10 defeated: 7 gold: 85 on the path: 7
Tower Defense: מסלול חום מתפתל על רקע ירוק כהה, ארבעה מגדלים כחולים עם עיגולי טווח, אויבים אדומים עם פסי חיים ירוקים, קליעים צהובים ושורת חיים, זהב והריגות.
screen.png
אנלוגיה מהחייםReal-life analogy

Tower Defense הוא כמו לתכנן מחסומים בכביש: אתם לא שולטים במכוניות, רק בוחרים איפה להציב את השוטרים.

Tower Defense is like planning checkpoints on a road: you don't control the cars, you only choose where to station the officers.

טעות נפוצהCommon mistake

מעדכנים רשימה בזמן שעוברים עליה.

Changing a list while looping over it.

tower_defense.py
enemies = [1, 1, 1]
for e in enemies:
    if e == 1:
        enemies.remove(e)
assert not enemies, f"{enemies} left: loop over enemies[:] (a copy) when removing"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/tower_defense.py", line 5, in <module>
    assert not enemies, f"{enemies} left: loop over enemies[:] (a copy) when removing"
           ^^^^^^^^^^^
AssertionError: [1] left: loop over enemies[:] (a copy) when removing
בעברית פשוטה: In plain words: AssertionError: [1] left: ...: מחיקה תוך כדי לולאה מדלגת על איברים. עוברים על עותק: for e in enemies[:]:.AssertionError: [1] left: ...: removing while looping skips items. Loop over a copy: for e in enemies[:]:.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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