Space Shooter: יורה חללSpace Shooter
pygame.sprite, Groups, Mask, ירושה, גלים ובוס.
pygame.sprite, Groups, Mask, inheritance, waves and a boss.
01Sprite וקבוצותSprites and groups
כשיש עשרות עצמים, כדאי להיעזר במערכת של pygame. Sprite הוא מחלקה עם שתי תכונות חובה: image ו-rect. קבוצה מעדכנת ומציירת את כולם בשורה אחת, ו-kill() מוציא Sprite מכל קבוצה שהוא בה. זו ירושה (מפגש 16) בפעולה:
With dozens of objects, pygame's system helps. A Sprite is a class with two required attributes: image and rect. A group updates and draws all of them in one line, and kill() removes a Sprite from every group it's in. It's inheritance (session 16) in action:
import pygame
class Star(pygame.sprite.Sprite):
def __init__(self, x, y, speed):
super().__init__()
self.image = pygame.Surface((3, 3))
self.image.fill((255, 255, 255))
self.rect = self.image.get_rect(center=(x, y))
self.speed = speed
def update(self):
self.rect.y += self.speed
if self.rect.top > 100:
self.kill()
stars = pygame.sprite.Group(Star(10, 0, 30), Star(20, 0, 10), Star(30, 0, 60))
for frame in range(3):
stars.update()
print("frame", frame, "->", len(stars), "stars", sorted(s.rect.y for s in stars))frame 0 -> 3 stars [9, 29, 59] frame 1 -> 2 stars [19, 59] frame 2 -> 2 stars [29, 89]
קבוצת Sprites היא כמו מנצח על תזמורת: אומר "עכשיו כולם" פעם אחת, וכל נגן מנגן את התפקיד שלו.
A sprite group is like a conductor: says "everyone, now" once, and each player plays their own part.
שוכחים super().__init__() ב-Sprite.
Forgetting super().__init__() in a Sprite.
import pygame
class Rock(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.Surface((5, 5))
self.rect = self.image.get_rect()
pygame.sprite.Group(Rock())Traceback (most recent call last):
File "/Users/you/python-course/sprites.py", line 8, in <module>
pygame.sprite.Group(Rock())
~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pygame/sprite.py", line 661, in __init__
self.add(*sprites)
~~~~~~~~^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pygame/sprite.py", line 460, in add
sprite.add_internal(self)
~~~~~~~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/site-packages/pygame/sprite.py", line 176, in add_internal
self.__g[group] = 0
^^^^^^^^
AttributeError: 'Rock' object has no attribute '_Sprite__g'. Did you mean: '_Sprite__image'?AttributeError: 'Rock' object has no attribute '_Sprite__g': בלי super().__init__() ה-Sprite לא מוכן להיכנס לקבוצות. זו הסיבה לשורה הזו (מפגש 16).AttributeError: 'Rock' object has no attribute '_Sprite__g': without super().__init__() the Sprite isn't ready to join groups. That's why the line exists (session 16).02יריות עם המתנהShooting with a cooldown
אם יורים בכל פריים שבו מקש הירי לחוץ, יוצאות 60 יריות בשנייה ושום אתגר. זמן המתנה הוא מונה: אחרי ירייה קובעים אותו ל-12, הוא יורד ב-1 בכל פריים, ויורים רק כשהוא הגיע לאפס. ירייה שעברה את ראש המסך נמחקת, אחרת הקבוצה הייתה גדלה לנצח:
If you shoot every frame the fire key is held, 60 bullets a second fly out and there's no challenge. A cooldown is a counter: after a shot set it to 12, it drops by 1 every frame, and you fire only when it reaches zero. A bullet past the top of the screen is removed, otherwise the group would grow forever:
cooldown, shots, alive = 0, 0, []
for frame in range(120):
fire_held = True
cooldown -= 1
if fire_held and cooldown <= 0:
alive.append(300)
shots += 1
cooldown = 12
alive = [y - 8 for y in alive if y - 8 > 0]
print("2 seconds with fire held:", shots, "shots;", len(alive), "still on screen")2 seconds with fire held: 10 shots; 3 still on screen
cooldown הוא כמו מכונת קפה שצריכה להתחמם בין כוס לכוס: אפשר ללחוץ כמה שרוצים, היא תמזוג רק כשהיא מוכנה.
A cooldown is like a coffee machine that has to reheat between cups: press as much as you like, it pours only when ready.
מונה ההמתנה לא מתאפס, והנשק נתקע.
The cooldown never resets, so the gun jams.
cooldown, shots = 0, 0
for frame in range(60):
if cooldown <= 0:
shots += 1
cooldown = 12
assert shots > 1, f"{shots} shot in a second: the cooldown never counts down; add cooldown -= 1 every frame"Traceback (most recent call last):
File "/Users/you/python-course/cooldown.py", line 6, in <module>
assert shots > 1, f"{shots} shot in a second: the cooldown never counts down; add cooldown -= 1 every frame"
^^^^^^^^^
AssertionError: 1 shot in a second: the cooldown never counts down; add cooldown -= 1 every frameAssertionError: 1 shot in a second: ...: מורידים את המונה בכל פריים, אחרת הוא נשאר 12 לתמיד.AssertionError: 1 shot in a second: ...: lower the counter every frame, otherwise it stays at 12 forever.03פגיעות בין קבוצותHits between groups
pygame.sprite.groupcollide בודק כל אויב מול כל ירייה ומחזיר מילון: מפתח = אויב שנפגע, ערך = רשימת היריות שפגעו בו. שני הפרמטרים האחרונים אומרים אם למחוק את הנפגעים. spritecollide בודק Sprite אחד מול קבוצה, למשל החללית מול יריות אויב:
pygame.sprite.groupcollide checks every enemy against every bullet and returns a dict: key = an enemy that was hit, value = the list of bullets that hit it. The last two arguments say whether to remove what was hit. spritecollide checks one Sprite against a group, e.g. the ship against enemy bullets:
import pygame
def box(x, y, w, h):
s = pygame.sprite.Sprite()
s.image = pygame.Surface((w, h))
s.rect = pygame.Rect(x, y, w, h)
return s
enemies = pygame.sprite.Group(box(0, 0, 20, 20), box(50, 0, 20, 20), box(100, 0, 20, 20))
bullets = pygame.sprite.Group(box(5, 10, 4, 10), box(8, 12, 4, 10), box(105, 5, 4, 10), box(200, 0, 4, 10))
hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
print("enemies hit:", len(hits), " bullets per enemy:", sorted(len(v) for v in hits.values()))
print("left:", len(enemies), "enemies,", len(bullets), "bullets")enemies hit: 2 bullets per enemy: [1, 2] left: 1 enemies, 1 bullets
groupcollide הוא כמו שופט במשחק כדור-מחניים: עובר על כל הזוגות, מכריז מי נפגע, ושולח אותם החוצה.
groupcollide is like a dodgeball referee: checks every pair, announces who was hit, and sends them off.
מוחקים יריות בשתי הקבוצות ומקבלים נקודות כפולות.
Counting points per bullet, so one enemy gives double points.
hits = {"enemy1": ["bullet1", "bullet2"]}
score = sum(10 for bullets in hits.values() for b in bullets)
assert score == 10, f"one enemy gave {score} points because two bullets hit it at once: count the keys"Traceback (most recent call last):
File "/Users/you/python-course/groupcollide.py", line 3, in <module>
assert score == 10, f"one enemy gave {score} points because two bullets hit it at once: count the keys"
^^^^^^^^^^^
AssertionError: one enemy gave 20 points because two bullets hit it at once: count the keysAssertionError: one enemy gave 20 points ...: סופרים אויבים (len(hits)), לא יריות.AssertionError: one enemy gave 20 points ...: count enemies (len(hits)), not bullets.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04גלי אויביםEnemy waves
גל אויבים נבנה בלולאה כפולה (כמו לבני Brick Breaker). כל הגל זז יחד הצידה, וכשאחד נוגע בקצה כולם יורדים שורה והופכים כיוון. כשהקבוצה מתרוקנת, בונים גל חדש מהיר יותר. מספר הגל קובע את הקושי:
An enemy wave is built with a double loop (like Brick Breaker's bricks). The whole wave moves sideways together, and when one touches the edge they all drop a row and turn around. When the group empties, build a new, faster wave. The wave number sets the difficulty:
def wave(number, cols=7, rows=3):
speed = 1.0 + 0.4 * (number - 1)
enemies = [[60 + c * 50, 40 + r * 30] for r in range(rows + min(number - 1, 2)) for c in range(cols)]
return enemies, round(speed, 1)
def march(enemies, dx, width):
if any(x + dx < 10 or x + dx > width - 10 for x, _ in enemies):
return [[x, y + 10] for x, y in enemies], -dx
return [[x + dx, y] for x, y in enemies], dx
for n in (1, 2, 3, 5):
e, sp = wave(n)
print("wave", n, ":", len(e), "enemies at speed", sp)
e, dx = [[460, 40], [400, 40]], 6
for _ in range(3):
e, dx = march(e, dx, 480)
print(e, dx)wave 1 : 21 enemies at speed 1.0 wave 2 : 28 enemies at speed 1.4 wave 3 : 35 enemies at speed 1.8 wave 5 : 35 enemies at speed 2.6 [[466, 40], [406, 40]] 6 [[466, 50], [406, 50]] -6 [[460, 50], [400, 50]] -6
גל אויבים הוא כמו להקת ציפורים: כולן פונות יחד כשהראשונה מגיעה לקצה.
An enemy wave is like a flock of birds: they all turn together when the first reaches the edge.
כל אויב בודק את הקצה לבד, והגל מתפרק.
Each enemy checks the edge alone, so the wave falls apart.
xs, dxs = [468, 400, 350], [6, 6, 6]
for i in range(3):
if xs[i] + dxs[i] > 470:
dxs[i] = -dxs[i]
assert len(set(dxs)) == 1, f"directions {dxs}: one enemy turned and the others didn't; decide once for the whole wave"Traceback (most recent call last):
File "/Users/you/python-course/waves.py", line 5, in <module>
assert len(set(dxs)) == 1, f"directions {dxs}: one enemy turned and the others didn't; decide once for the whole wave"
^^^^^^^^^^^^^^^^^^
AssertionError: directions [-6, 6, 6]: one enemy turned and the others didn't; decide once for the whole waveAssertionError: directions [-6, 6, 6]: ...: בודקים אם מישהו בגל יגיע לקצה, ומשנים כיוון לכולם יחד.AssertionError: directions [-6, 6, 6]: ...: check whether anyone in the wave would reach the edge, and turn everyone together.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
כל גל מוסיף אויבים ומהירות.
Each wave adds enemies and speed.
for wave in range(1, 4):
enemies = 3 + wave * 2
speed = 1 + wave * 0.5
print(f"wave {wave}: {enemies} enemies at speed {speed}")wave 1: 5 enemies at speed 1.5 wave 2: 7 enemies at speed 2.0 wave 3: 9 enemies at speed 2.5
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05חלקיקים ורקע כוכביםParticles and a starfield
פיצוץ הוא כמה חלקיקים: לכל אחד מיקום, מהירות אקראית וזמן חיים שיורד. כשהזמן נגמר, החלקיק נמחק. צבע שתלוי בזמן החיים גורם לניצוץ לדעוך. ורקע של כוכבים שזזים במהירויות שונות נותן תחושת טיסה (זוכרים פרלקסה?):
An explosion is a few particles: each with a position, a random velocity and a lifetime that counts down. When time runs out, the particle is removed. A colour depending on lifetime makes the spark fade. And a background of stars moving at different speeds gives a sense of flight (remember parallax?):
import random
import pygame
random.seed(3)
pygame.init()
screen = pygame.display.set_mode((480, 200))
sparks = [[240, 100, random.uniform(-3, 3), random.uniform(-3, 3), 30] for _ in range(40)]
stars = [[random.randrange(480), random.randrange(200), random.choice([1, 2, 3])] for _ in range(50)]
for frame in range(14):
for p in sparks:
p[0] += p[2]
p[1] += p[3]
p[4] -= 1
sparks = [p for p in sparks if p[4] > 0]
screen.fill((6, 6, 18))
for x, y, speed in stars:
pygame.draw.circle(screen, (60 + speed * 60,) * 3, (x, y), 1)
for x, y, _, _, life in sparks:
pygame.draw.circle(screen, (255, 120 + life * 4, 60), (round(x), round(y)), 3)
print(len(sparks), "sparks still alive")
pygame.quit()40 sparks still alive
חלקיקים הם כמו זיקוקים: כל ניצוץ טס לבד, דועך, ונעלם, ויחד הם נראים כמו פיצוץ אחד.
Particles are like fireworks: each spark flies alone, fades and vanishes, and together they look like one burst.
חלקיקים שלא מתים, והמשחק מאט.
Particles that never die, so the game slows down.
sparks = []
for explosion in range(100):
sparks += [[0, 0, 1, 1, 20] for _ in range(12)]
for p in sparks:
p[0] += p[2]
assert len(sparks) < 200, f"{len(sparks)} particles: lower each life every frame and drop the dead ones"Traceback (most recent call last):
File "/Users/you/python-course/particles.py", line 6, in <module>
assert len(sparks) < 200, f"{len(sparks)} particles: lower each life every frame and drop the dead ones"
^^^^^^^^^^^^^^^^^
AssertionError: 1200 particles: lower each life every frame and drop the dead onesAssertionError: 1200 particles: ...: בלי ירידה של זמן החיים וסינון, כל פיצוץ נשאר לנצח.AssertionError: 1200 particles: ...: without lowering the lifetime and filtering, every explosion stays forever.06Space Shooter: המשחקSpace Shooter: the game
הכול יחד: חללית, יריות עם cooldown, גל אויבים שצועד ויורד, פגיעות עם groupcollide, ניצוצות פיצוץ, וכוכבים שזורמים למטה. כאן החללית מכוונת לבד לאויב הקרוב ויורה אוטומטית; במחשב שלכם החיצים והרווח:
Everything together: a ship, bullets with a cooldown, an enemy wave that marches and drops, hits with groupcollide, explosion sparks, and stars streaming down. Here the ship aims at the nearest enemy and fires automatically; on your computer, the arrows and space:
import random
import pygame
W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 26)
random.seed(5)
class Ship(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 24), pygame.SRCALPHA)
pygame.draw.polygon(self.image, (120, 220, 255), [(15, 0), (30, 24), (15, 18), (0, 24)])
self.rect = self.image.get_rect(midbottom=(W // 2, H - 8))
self.cooldown = 0
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((4, 12))
self.image.fill((255, 240, 120))
self.rect = self.image.get_rect(midbottom=(x, y))
def update(self):
self.rect.y -= 8
if self.rect.bottom < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((26, 18), pygame.SRCALPHA)
pygame.draw.rect(self.image, (255, 90, 120), (0, 4, 26, 10), border_radius=4)
pygame.draw.rect(self.image, (255, 160, 180), (8, 0, 10, 18), border_radius=3)
self.rect = self.image.get_rect(center=(x, y))
self.dx = 1.5
def update(self):
self.rect.x += round(self.dx)
if self.rect.left < 10 or self.rect.right > W - 10:
self.dx = -self.dx
self.rect.y += 10
stars = [[random.randrange(W), random.randrange(H), random.choice([1, 2, 3])] for _ in range(60)]
ship = Ship()
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group(Enemy(60 + c * 50, 40 + r * 30) for r in range(3) for c in range(7))
sparks, score = [], 0
for frame in range(260):
target = min(enemies, key=lambda e: abs(e.rect.centerx - ship.rect.centerx), default=None)
if target:
ship.rect.x += max(-4, min(4, target.rect.centerx - ship.rect.centerx))
ship.cooldown -= 1
if ship.cooldown <= 0:
bullets.add(Bullet(ship.rect.centerx, ship.rect.top))
ship.cooldown = 12
bullets.update()
enemies.update()
for enemy in pygame.sprite.groupcollide(enemies, bullets, True, True):
score += 10
sparks += [[enemy.rect.centerx, enemy.rect.centery, random.uniform(-3, 3), random.uniform(-3, 3), 20] for _ in range(12)]
for s in stars:
s[1] = (s[1] + s[2]) % H
for p in sparks:
p[0] += p[2]; p[1] += p[3]; p[4] -= 1
sparks = [p for p in sparks if p[4] > 0]
screen.fill((6, 6, 18))
for x, y, sp in stars:
pygame.draw.circle(screen, (90 + sp * 50,) * 3, (x, y), 1)
enemies.draw(screen)
bullets.draw(screen)
screen.blit(ship.image, ship.rect)
for x, y, _, _, life in sparks:
pygame.draw.circle(screen, (255, 180 + life * 3, 80), (round(x), round(y)), 2)
screen.blit(font.render(f"Score {score}", True, (220, 230, 255)), (8, 6))
pygame.display.flip()
print("enemies left:", len(enemies), "score:", score)
pygame.quit()enemies left: 8 score: 130
המשחק הזה הוא מה שקורה כשמחלקות, קבוצות ורשימות עובדות יחד: כל עצם יודע מה לעשות, והלולאה רק מתזמרת.
This game is what happens when classes, groups and lists work together: each object knows what to do, and the loop just conducts.
מציירים את ה-Sprites לפני שממלאים את הרקע.
Drawing the Sprites before filling the background.
order = ["enemies.draw", "bullets.draw", "screen.fill"]
assert order.index("screen.fill") == 0, f"draw order {order}: the fill wipes everything drawn before it"Traceback (most recent call last):
File "/Users/you/python-course/space_shooter.py", line 2, in <module>
assert order.index("screen.fill") == 0, f"draw order {order}: the fill wipes everything drawn before it"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: draw order ['enemies.draw', 'bullets.draw', 'screen.fill']: the fill wipes everything drawn before itAssertionError: קודם רקע, אחר כך הכול. מה שמצויר אחרון נמצא למעלה.AssertionError: background first, then everything else. What's drawn last is on top.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.