חלקPart 7: משחקים עם PygameGames with Pygame
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Space Shooter: יורה חללSpace Shooter
pygame.sprite, Groups, Mask, ירושה, גלים ובוס.
pygame.sprite, Groups, Mask, inheritance, waves and a boss.
הנקודות החשובותKey points
- Sprite =
image+rect+updateA Sprite =image+rect+update - קבוצה:
group.update(),group.draw(screen)A group:group.update(),group.draw(screen) - cooldown: ירייה כל N פריימיםA cooldown: a shot every N frames
- ירייה = Sprite שזז למעלהA bullet = a Sprite moving up
groupcollide(a, b, kill_a, kill_b)groupcollide(a, b, kill_a, kill_b)- מחזיר מילון: מי פגע במיReturns a dict: who hit whom
- גל = מערך של אויביםA wave = a formation of enemies
- זזים יחד, יורדים בקצהMove together, drop at the edge
- חלקיק: מיקום, מהירות, זמן חייםA particle: position, velocity, lifetime
מונחיםTerms
- SpriteSprite: עצם במשחק שיש לו
image(מה מציירים) ו-rect(איפה), ולרוב מתודתupdate. יורשים מ-pygame.sprite.Sprite.A game object with animage(what to draw) and arect(where), usually with anupdatemethod. Inherit frompygame.sprite.Sprite. - קבוצת Spritessprite Group: אוסף שיודע לעדכן ולצייר את כל החברים בו בבת אחת, ולבדוק התנגשויות.
kill()מוציא Sprite מכל הקבוצות.A collection that updates and draws all its members at once, and checks collisions.kill()removes a Sprite from every group. - זמן המתנה (cooldown)cooldown: מונה שמונע פעולה חוזרת מהר מדי, למשל ירייה אחת כל 12 פריימים.A counter preventing an action from repeating too fast, e.g. one shot every 12 frames.
- חלקיקparticle: נקודה קטנה עם מיקום, מהירות וזמן חיים. הרבה חלקיקים יחד יוצרים פיצוץ, עשן או ניצוצות.A small dot with a position, velocity and lifetime. Many together make an explosion, smoke or sparks.
- גלwave: קבוצת אויבים שמופיעה יחד. כשמחסלים גל, מגיע הבא, לרוב קשה יותר.A group of enemies appearing together. Clear a wave and the next arrives, usually harder.
Cheatsheet
SpritesSprites
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))יריShooting
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פגיעותHits
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גליםWaves
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):חלקיקיםParticles
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)]משחקGame
import random
import pygame
W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 26)שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
AttributeError | שוכחים super().__init__() ב-Sprite.Forgetting super().__init__() in a Sprite. | 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). |
AssertionError | מונה ההמתנה לא מתאפס, והנשק נתקע.The cooldown never resets, so the gun jams. | AssertionError: 1 shot in a second: ...: מורידים את המונה בכל פריים, אחרת הוא נשאר 12 לתמיד.AssertionError: 1 shot in a second: ...: lower the counter every frame, otherwise it stays at 12 forever. |
AssertionError | מוחקים יריות בשתי הקבוצות ומקבלים נקודות כפולות.Counting points per bullet, so one enemy gives double points. | AssertionError: one enemy gave 20 points ...: סופרים אויבים (len(hits)), לא יריות.AssertionError: one enemy gave 20 points ...: count enemies (len(hits)), not bullets. |
AssertionError | כל אויב בודק את הקצה לבד, והגל מתפרק.Each enemy checks the edge alone, so the wave falls apart. | AssertionError: directions [-6, 6, 6]: ...: בודקים אם מישהו בגל יגיע לקצה, ומשנים כיוון לכולם יחד.AssertionError: directions [-6, 6, 6]: ...: check whether anyone in the wave would reach the edge, and turn everyone together. |
AssertionError | חלקיקים שלא מתים, והמשחק מאט.Particles that never die, so the game slows down. | AssertionError: 1200 particles: ...: בלי ירידה של זמן החיים וסינון, כל פיצוץ נשאר לנצח.AssertionError: 1200 particles: ...: without lowering the lifetime and filtering, every explosion stays forever. |
AssertionError | מציירים את ה-Sprites לפני שממלאים את הרקע.Drawing the Sprites before filling the background. | AssertionError: קודם רקע, אחר כך הכול. מה שמצויר אחרון נמצא למעלה.AssertionError: background first, then everything else. What's drawn last is on top. |