חלקPart 7: משחקים עם PygameGames with Pygame
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Star Catcher: תופסים כוכביםStar Catcher
Rect, מקלדת, התנגשויות, טקסט, מצבי משחק ושיא בקובץ.
Rect, keyboard, collisions, text, game states and a saved high score.
הנקודות החשובותKey points
- `KEYDOWN`: פעם אחת בלחיצה`KEYDOWN`: once per press
get_pressed(): כל עוד מחזיקיםget_pressed(): as long as held- `Rect` יודע
left,right,centerxA `Rect` knowsleft,right,centerx - הגבלה לטווח שומרת בתוך המסךClamping keeps it on screen
- הופעה כל N פריימיםspawn every N frames
random.randintלמיקוםrandom.randintfor positiona.colliderect(b)→ True/Falsea.colliderect(b)→ True/Falsecollidelist/collidepointcollidelist/collidepoint- ניקוד עולה בתפיסהScore goes up on a catch
מונחיםTerms
- RectRect: מלבן של pygame עם x, y, רוחב וגובה, שיודע את הקצוות שלו ולבדוק חפיפה.
pygame.Rect(x, y, w, h).A pygame rectangle with x, y, width and height that knows its edges and can check overlap.pygame.Rect(x, y, w, h). - התנגשותcollision: מצב שבו שני עצמים במשחק חופפים. ב-pygame:
a.colliderect(b).When two game objects overlap. In pygame:a.colliderect(b). - KEYDOWNKEYDOWN: אירוע שקורה פעם אחת ברגע שלוחצים על מקש. מתאים לקפיצה או ירייה בודדת.An event that fires once at the moment a key is pressed. Good for a single jump or shot.
- הגבלה לטווח (clamp)clamp: להחזיר ערך לתוך גבולות:
max(low, min(high, value)). שומר על השחקן בתוך המסך.Forcing a value into bounds:max(low, min(high, value)). Keeps the player on screen. - הופעה (spawn)spawn: יצירת עצם חדש במשחק, כמו כוכב שנופל, לרוב בזמנים או מקומות אקראיים.Creating a new object in the game, like a falling star, often at random times or places.
Cheatsheet
מקלדתKeyboard
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 100))
jumps = 0
for frame in range(5):
if frame == 1:RectRect
import pygame
W = 480
basket = pygame.Rect(400, 290, 80, 16)
for move in [30, 30, -500]:
basket.x = max(0, min(W - basket.width, basket.x + move))
print(basket.x, basket.right)הופעהSpawning
import random
random.seed(1)
W, H = 480, 320
stars = []
max_alive = 0
for frame in range(300):התנגשותCollision
import pygame
def overlap(a, b):
return a.left < b.right and b.left < a.right and a.top < b.bottom and b.top < a.bottom
basket = pygame.Rect(200, 290, 80, 16)
stars = [pygame.Rect(210, 280, 16, 16), pygame.Rect(100, 280, 16, 16), pygame.Rect(279, 289, 16, 16)]מצבState
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
big = pygame.font.Font(None, 64)
small = pygame.font.Font(None, 30)
score, lives, state = 0, 1, "playing"משחקGame
import random
import pygame
W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 28)שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
AssertionError | קפיצה עם get_pressed, והדמות קופצת בכל פריים כל עוד מחזיקים.A jump with get_pressed, so the character jumps every frame while held. | AssertionError: 30 jumps from one press: ...: get_pressed אמת בכל פריים. לפעולה חד-פעמית משתמשים באירוע KEYDOWN.AssertionError: 30 jumps from one press: ...: get_pressed is true every frame. For one-time actions use the KEYDOWN event. |
AssertionError | משנים את right בלי להבין שזה מזיז את כל המלבן.Changing right without realising it moves the whole rectangle. | AssertionError: width is still 80 and x is 400: ...: שינוי right מזיז את המלבן כך שהקצה הימני יהיה שם. לשינוי גודל: r.width = ....AssertionError: width is still 80 and x is 400: ...: setting right moves the rect so its right edge lands there. To resize: r.width = .... |
AssertionError | לא מוחקים כוכבים שיצאו, והמשחק מאט עם הזמן.Not removing stars that left, so the game slows down over time. | AssertionError: 300 stars after 100 seconds, ...: כל כוכב שיצא עדיין מעודכן בכל פריים. מסננים: [s for s in stars if s[1] <= H].AssertionError: 300 stars after 100 seconds, ...: every star that left is still updated each frame. Filter: [s for s in stars if s[1] <= H]. |
AssertionError | בודקים התנגשות לפני שמזיזים, ומפספסים פגיעה.Checking the collision before moving, and missing a hit. | AssertionError: checked before moving: ...: הסדר בפריים: קודם מזיזים, ורק אז בודקים התנגשויות.AssertionError: checked before moving: ...: the order in a frame: move first, then check collisions. |
AssertionError | חיים יורדים מתחת לאפס כי אין בדיקת סיום.Lives drop below zero because there's no game-over check. | AssertionError: lives = -2: ...: אחרי כל הורדה בודקים if lives <= 0: state = "over", ובמצב over לא מעדכנים יותר את המשחק.AssertionError: lives = -2: ...: after each loss check if lives <= 0: state = "over", and in the over state stop updating the game. |
AssertionError | מוחקים מרשימת הכוכבים תוך כדי לולאה עליה, ומדלגים על כוכב.Removing from the star list while looping over it, skipping a star. | AssertionError: caught 1: ...: עוברים על עותק (stars[:]) ומוחקים מהמקור, כמו בקוד המשחק.AssertionError: caught 1: ...: loop over a copy (stars[:]) and remove from the original, as in the game code. |