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

PythonPython
38
חלק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.

01מקלדתThe keyboard

יש שתי דרכים לקרוא מקלדת. אירוע `KEYDOWN` מגיע פעם אחת ברגע הלחיצה, ומתאים לפעולה בודדת כמו קפיצה. pygame.key.get_pressed() מחזיר את מצב כל המקשים עכשיו, ומתאים לתנועה רציפה כל עוד מחזיקים. כאן מדמים לחיצות כדי לראות את ההבדל:

There are two ways to read the keyboard. A `KEYDOWN` event arrives once at the moment of pressing, good for a single action like a jump. pygame.key.get_pressed() returns every key's state right now, good for continuous movement while held. Here we simulate presses to see the difference:

keys.py
import pygame

pygame.init()
screen = pygame.display.set_mode((200, 100))
jumps = 0
for frame in range(5):
    if frame == 1:
        pygame.event.post(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_SPACE))
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            jumps += 1
print("jumps:", jumps)
print("left key code:", pygame.K_LEFT, "space:", pygame.K_SPACE)
pygame.quit()
פלטOutput
jumps: 1
left key code: 1073741904 space: 32
screen.png
screen.png
אנלוגיה מהחייםReal-life analogy

KEYDOWN הוא כמו פעמון בדלת: מצלצל פעם אחת כשלוחצים. get_pressed הוא כמו להסתכל אם מישהו עדיין עומד ליד הדלת.

KEYDOWN is like a doorbell: it rings once when pressed. get_pressed is like looking whether someone is still standing at the door.

טעות נפוצהCommon mistake

קפיצה עם get_pressed, והדמות קופצת בכל פריים כל עוד מחזיקים.

A jump with get_pressed, so the character jumps every frame while held.

keys.py
held_frames = 30
jumps = 0
for frame in range(held_frames):
    space_down = True
    if space_down:
        jumps += 1
assert jumps == 1, f"{jumps} jumps from one press: use the KEYDOWN event for one-time actions"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/keys.py", line 7, in <module>
    assert jumps == 1, f"{jumps} jumps from one press: use the KEYDOWN event for one-time actions"
           ^^^^^^^^^^
AssertionError: 30 jumps from one press: use the KEYDOWN event for one-time actions
בעברית פשוטה: In plain words: 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.

02Rect ותנועה בגבולותRect and bounded movement

השחקן הוא Rect: קל להזיז אותו (basket.x += 6), וקל לבדוק את הקצוות. כדי שלא יברח מהמסך, מגבילים לטווח: max(0, min(W - width, x)). ל-Rect יש גם clamp_ip שעושה את זה בשבילכם:

The player is a Rect: easy to move (basket.x += 6), easy to check edges. So it doesn't escape the screen, clamp it: max(0, min(W - width, x)). A Rect also has clamp_ip that does it for you:

bounds.py
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)
screen_rect = pygame.Rect(0, 0, 480, 320)
basket.x = 999
basket.clamp_ip(screen_rect)
print(basket.topleft, basket.center)
פלטOutput
400 480
400 480
0 80
(400, 290) (440, 298)
אנלוגיה מהחייםReal-life analogy

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

Clamping is like a playground fence: kids run freely, but never out into the road.

טעות נפוצהCommon mistake

משנים את right בלי להבין שזה מזיז את כל המלבן.

Changing right without realising it moves the whole rectangle.

bounds.py
import pygame
r = pygame.Rect(0, 0, 80, 16)
r.right = 480
assert r.width == 480, f"width is still {r.width} and x is {r.x}: setting right moves the rect, it doesn't stretch it"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/bounds.py", line 4, in <module>
    assert r.width == 480, f"width is still {r.width} and x is {r.x}: setting right moves the rect, it doesn't stretch it"
           ^^^^^^^^^^^^^^
AssertionError: width is still 80 and x is 400: setting right moves the rect, it doesn't stretch it
בעברית פשוטה: In plain words: 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 = ....

03כוכבים נופליםFalling stars

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

Stars spawn at a random spot at the top every few frames, and fall. So the list doesn't grow forever, remove a star that leaves the bottom of the screen. random.seed fixes the randomness so every run is identical (handy for testing):

spawn.py
import random

random.seed(1)
W, H = 480, 320
stars = []
max_alive = 0
for frame in range(300):
    if frame % 20 == 0:
        stars.append([random.randint(10, W - 10), 0])
    for s in stars:
        s[1] += 5
    stars = [s for s in stars if s[1] <= H]
    max_alive = max(max_alive, len(stars))
print("on screen now:", len(stars), "most at once:", max_alive)
פלטOutput
on screen now: 3 most at once: 4
אנלוגיה מהחייםReal-life analogy

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

Spawning is like a tennis ball machine: every few seconds a ball comes out, and balls off the court are collected so the court doesn't fill up.

טעות נפוצהCommon mistake

לא מוחקים כוכבים שיצאו, והמשחק מאט עם הזמן.

Not removing stars that left, so the game slows down over time.

spawn.py
stars = []
for frame in range(6000):
    if frame % 20 == 0:
        stars.append([0, 0])
    for s in stars:
        s[1] += 5
assert len(stars) < 50, f"{len(stars)} stars after 100 seconds, almost all off screen: remove them"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/spawn.py", line 7, in <module>
    assert len(stars) < 50, f"{len(stars)} stars after 100 seconds, almost all off screen: remove them"
           ^^^^^^^^^^^^^^^
AssertionError: 300 stars after 100 seconds, almost all off screen: remove them
בעברית פשוטה: In plain words: 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].

04התנגשותCollision

התנגשות בין שני מלבנים היא שאלה פשוטה: האם הם חופפים? colliderect עונה. collidepoint בודק נקודה (למשל לחיצת עכבר), ו-collidelist מחזיר את האינדקס של הראשון שמתנגש. בפנים זה רק ארבע השוואות:

A collision between two rectangles is a simple question: do they overlap? colliderect answers. collidepoint checks a point (like a mouse click), and collidelist returns the index of the first that collides. Inside, it's just four comparisons:

collide.py
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)]
for s in stars:
    print(s.topleft, basket.colliderect(s), overlap(basket, s))
print(basket.collidelist(stars), basket.collidepoint(240, 295))
פלטOutput
(210, 280) True True
(100, 280) False False
(279, 289) True True
0 True
אנלוגיה מהחייםReal-life analogy

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

Collision is like checking whether two rugs on the floor overlap: if one ends before the other starts, in any direction, they don't touch.

טעות נפוצהCommon mistake

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

Checking the collision before moving, and missing a hit.

collide.py
import pygame
basket = pygame.Rect(200, 290, 80, 16)
star = pygame.Rect(220, 270, 16, 16)
caught = star.colliderect(basket)
star.y += 10
assert caught, "checked before moving: the star now overlaps the basket but the catch was missed"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/collide.py", line 6, in <module>
    assert caught, "checked before moving: the star now overlaps the basket but the catch was missed"
           ^^^^^^
AssertionError: checked before moving: the star now overlaps the basket but the catch was missed
בעברית פשוטה: In plain words: AssertionError: checked before moving: ...: הסדר בפריים: קודם מזיזים, ורק אז בודקים התנגשויות.AssertionError: checked before moving: ...: the order in a frame: move first, then check collisions.

שני מלבנים נוגעים אם הם חופפים גם ב-x וגם ב-y.

Two rectangles touch if they overlap on both x and y.

עוד דוגמה: התנגשות בלי pygameOne more: a collision without pygame
example.py
def hit(a, b):
    ax, ay, aw, ah = a
    bx, by, bw, bh = b
    return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah

print(hit((0, 0, 10, 10), (5, 5, 10, 10)))
print(hit((0, 0, 10, 10), (20, 0, 5, 5)))
פלטOutput
True
False
צפו בהרצה צעד אחר צעד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

05ניקוד, חיים וסיוםScore, lives and game over

משחק צריך מטרה: תפיסה מוסיפה נקודה, פספוס מוריד חיים, ובאפס חיים עוברים למצב "סיום". משתנה state אומר באיזה מצב המשחק, והלולאה מתנהגת לפיו. מסך סיום מציג טקסט במרכז בעזרת get_rect(center=...):

A game needs a goal: a catch adds a point, a miss costs a life, and at zero lives switch to a "game over" state. A state variable says which mode the game is in, and the loop behaves accordingly. A game-over screen shows centred text using get_rect(center=...):

game_over.py
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"
for event in ["catch", "catch", "miss"]:
    if state != "playing":
        break
    if event == "catch":
        score += 1
    else:
        lives -= 1
        if lives == 0:
            state = "over"
screen.fill((10, 12, 30))
title = big.render("GAME OVER", True, (255, 90, 110))
screen.blit(title, title.get_rect(center=(240, 140)))
line = small.render(f"Score: {score}  -  press R to play again", True, (230, 230, 240))
screen.blit(line, line.get_rect(center=(240, 200)))
print(state, score)
pygame.quit()
פלטOutput
over 2
מסך סיום: GAME OVER באדום-ורוד גדול במרכז, ומתחתיו Score: 2 והוראה ללחוץ R.
screen.png
אנלוגיה מהחייםReal-life analogy

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

Game state is like a traffic light: green = playing, red = over. The loop looks at the light before deciding what to do.

טעות נפוצהCommon mistake

חיים יורדים מתחת לאפס כי אין בדיקת סיום.

Lives drop below zero because there's no game-over check.

game_over.py
lives = 1
for miss in range(3):
    lives -= 1
assert lives >= 0, f"lives = {lives}: switch to game over when lives reach 0"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/game_over.py", line 4, in <module>
    assert lives >= 0, f"lives = {lives}: switch to game over when lives reach 0"
           ^^^^^^^^^^
AssertionError: lives = -2: switch to game over when lives reach 0
בעברית פשוטה: In plain words: 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.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

06Star Catcher: המשחקStar Catcher: the game

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

Put it together: a basket moving with the arrows (here an "auto-player" heads for the nearest star, since nobody's pressing keys), diamond-shaped stars that spawn and fall, collision, score and lives. On your computer the arrow keys take over:

star_catcher.py
import random
import pygame

W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 28)
random.seed(3)

basket = pygame.Rect(W // 2 - 40, H - 30, 80, 16)
stars = []
score, lives = 0, 3
for frame in range(240):
    keys = pygame.key.get_pressed()
    move = 6 if keys[pygame.K_RIGHT] else -6 if keys[pygame.K_LEFT] else 0
    target = stars[0].centerx if stars else W // 2
    move = move or (6 if target > basket.centerx + 6 else -6 if target < basket.centerx - 6 else 0)
    basket.x = max(0, min(W - basket.width, basket.x + move))
    if frame % 25 == 0:
        stars.append(pygame.Rect(random.randint(10, W - 26), -16, 16, 16))
    for s in stars[:]:
        s.y += 4
        if s.colliderect(basket):
            stars.remove(s)
            score += 1
        elif s.top > H:
            stars.remove(s)
            lives -= 1
    screen.fill((10, 12, 30))
    for s in stars:
        pygame.draw.polygon(screen, (255, 220, 80), [(s.centerx, s.top), (s.right, s.centery), (s.centerx, s.bottom), (s.left, s.centery)])
    pygame.draw.rect(screen, (90, 200, 255), basket, border_radius=6)
    screen.blit(font.render(f"Score {score}   Lives {lives}", True, (255, 255, 255)), (10, 8))
    pygame.display.flip()
print("score:", score, "lives:", lives)
pygame.quit()
פלטOutput
score: 7 lives: 3
Star Catcher: כוכבים צהובים בצורת יהלום נופלים על רקע לילה, סל תכלת בתחתית, ובפינה Score ו-Lives.
screen.png
אנלוגיה מהחייםReal-life analogy

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

The whole game is three ideas you already know: movement, spawning and collision. Like a recipe combining three simple ingredients into a dish.

טעות נפוצהCommon mistake

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

Removing from the star list while looping over it, skipping a star.

star_catcher.py
stars = [5, 5, 300]
caught = 0
for s in stars:
    if s == 5:
        stars.remove(s)
        caught += 1
assert caught == 2, f"caught {caught}: looping over a list you remove from skips items; loop over stars[:]"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/star_catcher.py", line 7, in <module>
    assert caught == 2, f"caught {caught}: looping over a list you remove from skips items; loop over stars[:]"
           ^^^^^^^^^^^
AssertionError: caught 1: looping over a list you remove from skips items; loop over stars[:]
בעברית פשוטה: In plain words: AssertionError: caught 1: ...: עוברים על עותק (stars[:]) ומוחקים מהמקור, כמו בקוד המשחק.AssertionError: caught 1: ...: loop over a copy (stars[:]) and remove from the original, as in the game code.
צפו איפה זה נשבר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