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

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • מסלול = רשימת נקודות ציוןA path = a list of waypoints
  • צעד לעבר הנקודה הבאה בכיוון מנורמלStep toward the next point in a normalised direction
  • בטווח = math.dist(...) <= rangeIn range = math.dist(...) <= range
  • בחירה: הראשון במסלולChoosing: the first on the path
  • זמן טעינה יורד בכל פרייםA cooldown counts down each frame
  • יורים רק ב-0, ומאפסיםFire only at 0, then reset
  • קליע מונחה מכוון מחדש בכל פרייםA homing bullet re-aims every frame
  • פגיעה = מרחק קטן מסףA hit = distance below a threshold
  • גל = כמה אויבים, מרווח, עוצמהA wave = how many, the gap, the strength

מונחיםTerms

  • נקודת ציוןwaypoint: נקודה במסלול שהאויב הולך אליה. כשמגיעים, ממשיכים לנקודה הבאה ברשימה.A point on a path that an enemy walks toward. On arrival, move on to the next one in the list.
  • בחירת מטרהtargeting: הכלל שלפיו מגדל בוחר במי לירות מבין האויבים בטווח: הראשון, הקרוב, החזק.The rule a tower uses to choose whom to shoot among enemies in range: first, closest, strongest.
  • פס חייםhealth bar: מלבן שרוחבו יחסי ל-hp שנותר, מצויר מעל דמות. רוחב = רוחב מלא × hp / max_hp.A rectangle whose width is proportional to the remaining hp, drawn above a character. Width = full width × hp / max_hp.
  • קליע מונחהhoming: קליע שמכוון את עצמו מחדש בכל פריים לעבר המטרה הזזה.A projectile that re-aims every frame at its moving target.

Cheatsheet

מסלולPath
import math

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

def walk(speed, frames):
    x, y = PATH[0]
    target = 1
טווחRange
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},
קצבRate
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
קליעיםBullets
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]
גליםWaves
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):
משחקGame
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()

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorזזים בכיוון לא מנורמל, והאויב מגיע בקפיצה אחת.Moving by an un-normalised direction, so the enemy arrives in one jump.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.
ValueErrormax על רשימה ריקה כשאין אף אויב בטווח.max on an empty list when no enemy is in range.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).
AssertionErrorשוכחים להוריד את המונה, והמגדל יורה פעם אחת בלבד.Forgetting to count down, so the tower fires only once.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.
ValueErrorמוחקים מהרשימה אויב שכבר נמחק.Removing an enemy that's already been removed.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.
AssertionErrorקונים מגדל בלי לבדוק שיש מספיק זהב.Buying a tower without checking there's enough gold.AssertionError: gold went to -20: ...: בודקים if gold >= cost: ורק אז מורידים ובונים.AssertionError: gold went to -20: ...: check if gold >= cost: and only then subtract and build.
AssertionErrorמעדכנים רשימה בזמן שעוברים עליה.Changing a list while looping over it.AssertionError: [1] left: ...: מחיקה תוך כדי לולאה מדלגת על איברים. עוברים על עותק: for e in enemies[:]:.AssertionError: [1] left: ...: removing while looping skips items. Loop over a copy: for e in enemies[:]:.

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