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

PythonPython
39
חלקPart 7: משחקים עם PygameGames with Pygame כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Neon PongNeon Pong

Vector2, פיזיקת כדור, יריב מחשב, טיימרים וצלילים מסונתזים.

Vector2, ball physics, a computer opponent, timers and synthesized sound.

01המגרש והמחבטיםThe court and paddles

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

Pong is one of the first video games ever, and still one of the best to learn from. Start with the court: two paddles as rectangles at the sides, a small ball in the middle, and a dashed centre line drawn in a loop. The window size lives in constants W, H so every calculation is based on them:

court.py
import pygame

W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
left = pygame.Rect(16, H // 2 - 35, 10, 70)
right = pygame.Rect(W - 26, H // 2 - 35, 10, 70)
ball = pygame.Rect(W // 2 - 6, H // 2 - 6, 12, 12)
screen.fill((8, 6, 20))
for y in range(0, H, 20):
    pygame.draw.rect(screen, (60, 50, 90), (W // 2 - 1, y, 2, 10))
for r, c in ((left, (0, 240, 255)), (right, (255, 60, 200)), (ball, (255, 255, 120))):
    pygame.draw.rect(screen, c, r, border_radius=4)
print(left.centery, right.left, ball.center)
pygame.quit()
פלטOutput
160 454 (240, 160)
מגרש Pong: מחבט תכלת משמאל, מחבט ורוד מימין, כדור צהוב במרכז וקו אמצע מקווקו על רקע כמעט שחור.
screen.png
אנלוגיה מהחייםReal-life analogy

קבועים כמו W ו-H הם כמו מידות המגרש בספר החוקים: כל השחקנים נמדדים לפיהם, ואם מגדילים את המגרש, הכול מתעדכן.

Constants like W and H are like the court dimensions in the rule book: every player is measured against them, and if you enlarge the court, everything follows.

טעות נפוצהCommon mistake

מספרים קבועים מפוזרים בקוד במקום קבוע אחד.

Magic numbers scattered in the code instead of one constant.

court.py
W = 640
right_paddle_x = 480 - 26
assert right_paddle_x == W - 26, f"the window grew to {W} but the paddle is still at {right_paddle_x}: use W - 26"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/court.py", line 3, in <module>
    assert right_paddle_x == W - 26, f"the window grew to {W} but the paddle is still at {right_paddle_x}: use W - 26"
           ^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the window grew to 640 but the paddle is still at 454: use W - 26
בעברית פשוטה: In plain words: AssertionError: the window grew to 640 but the paddle is still at 454: ...: כותבים W - 26, ואז שינוי גודל לא שובר את המשחק.AssertionError: the window grew to 640 but the paddle is still at 454: ...: write W - 26, and resizing won't break 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

02כדור במהירות עשרוניתA ball with float speed

Rect שומר רק מספרים שלמים. אם מוסיפים לו 2.5 בכל פריים, החלק העשרוני הולך לאיבוד והתנועה "נתקעת". הפתרון: שומרים מיקום עשרוני נפרד (bx, by), ומעתיקים ל-Rect אחרי עיגול. כך גם מהירות כמו 2.5 עובדת:

A Rect stores only whole numbers. Add 2.5 to it every frame and the fraction is lost, so motion "sticks". The fix: keep a separate float position (bx, by), and copy into the Rect after rounding. That way even a speed like 2.5 works:

float_pos.py
import pygame

rect = pygame.Rect(0, 0, 12, 12)
for _ in range(10):
    rect.x += 0.5
print("rect only:", rect.x)

bx = 0.0
for _ in range(10):
    bx += 0.5
    rect.x = round(bx)
print("float + round:", bx, rect.x)
פלטOutput
rect only: 0
float + round: 5.0 5
אנלוגיה מהחייםReal-life analogy

מיקום עשרוני הוא כמו מד מרחק ברכב שסופר מטרים, בזמן שהשלט בצד הדרך מראה רק קילומטרים שלמים.

A float position is like a car's odometer counting metres, while the roadside sign shows only whole kilometres.

טעות נפוצהCommon mistake

מוסיפים מהירות קטנה ישר ל-Rect.

Adding a small speed straight to a Rect.

float_pos.py
import pygame
ball = pygame.Rect(0, 0, 12, 12)
for _ in range(60):
    ball.x += 0.4
assert ball.x > 0, f"after 60 frames ball.x is {ball.x}: Rect drops the fraction each time"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/float_pos.py", line 5, in <module>
    assert ball.x > 0, f"after 60 frames ball.x is {ball.x}: Rect drops the fraction each time"
           ^^^^^^^^^^
AssertionError: after 60 frames ball.x is 0: Rect drops the fraction each time
בעברית פשוטה: In plain words: AssertionError: after 60 frames ball.x is 0: ...: כל הוספה של 0.4 נחתכת ל-0. שומרים מיקום עשרוני נפרד.AssertionError: after 60 frames ball.x is 0: ...: each 0.4 is truncated to 0. Keep a separate float position.

כשהכדור נוגע בקיר, הופכים את כיוון התנועה.

When the ball touches a wall, flip its direction.

עוד דוגמה: כדור שקופץ מהקירOne more: a ball bouncing off the wall
example.py
x, vx, W = 90, 4, 100
for frame in range(6):
    x += vx
    if x >= W or x <= 0:
        vx = -vx
    print(frame, x, vx)
פלטOutput
0 94 4
1 98 4
2 102 -4
3 98 -4
4 94 -4
5 90 -4
צפו בהרצה צעד אחר צעד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

03זווית לפי נקודת הפגיעהAngle by hit point

אם הכדור תמיד חוזר באותה זווית, המשחק משעמם. הטריק של Pong: מחשבים איפה הכדור פגע במחבט, כמספר בין -1 (קצה עליון) ל-1 (קצה תחתון), וקובעים לפיו את vy. כך לשחקן יש שליטה, ופגיעה בקצה שולחת את הכדור בזווית חדה. מאיצים גם מעט (×1.05) בכל החזרה:

If the ball always returns at the same rebound angle, the game is dull. Pong's trick: compute where the ball hit the paddle, as a number from -1 (top edge) to 1 (bottom edge), and set vy from it. That gives the player control, and an edge hit sends the ball off sharply. Also speed up a little (×1.05) on each return:

rebound.py
def rebound(ball_y, paddle_y, paddle_h, vx, max_vy=5):
    offset = (ball_y - paddle_y) / (paddle_h / 2)
    offset = max(-1.0, min(1.0, offset))
    return round(-vx * 1.05, 2), round(offset * max_vy, 2)

for hit in [160, 175, 194, 126]:
    print(hit, "->", rebound(hit, 160, 70, 5))
פלטOutput
160 -> (-5.25, 0.0)
175 -> (-5.25, 2.14)
194 -> (-5.25, 4.86)
126 -> (-5.25, -4.86)
צפו בהרצה צעד אחר צעד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

אנלוגיה מהחייםReal-life analogy

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

It's like hitting a tennis ball: a centre hit returns it straight, an edge hit sends it sideways.

טעות נפוצהCommon mistake

הכדור נתקע בתוך המחבט ומתהפך שוב ושוב.

The ball gets stuck inside the paddle and flips again and again.

rebound.py
vx, flips = 5, 0
for frame in range(4):
    inside = True
    if inside:
        vx = -vx
        flips += 1
assert flips == 1, f"vx flipped {flips} times while the ball sat inside the paddle: only bounce when moving toward it"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/rebound.py", line 7, in <module>
    assert flips == 1, f"vx flipped {flips} times while the ball sat inside the paddle: only bounce when moving toward it"
           ^^^^^^^^^^
AssertionError: vx flipped 4 times while the ball sat inside the paddle: only bounce when moving toward it
בעברית פשוטה: In plain words: AssertionError: vx flipped 4 times ...: מחזירים רק אם הכדור נע לכיוון המחבט (vx < 0 למחבט השמאלי), כמו בקוד המשחק.AssertionError: vx flipped 4 times ...: bounce only if the ball moves toward the paddle (vx < 0 for the left one), 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

04יריב ממוחשבAn AI opponent

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

A simple AI opponent: if the paddle's centre is above the ball, move down; if below, move up. Two tweaks make it fair: a top speed lower than the ball's (otherwise it's unbeatable), and a "dead zone" of a few pixels where it doesn't move, so the paddle doesn't jitter up and down:

ai.py
def ai_move(paddle_y, ball_y, speed, dead=4):
    if paddle_y < ball_y - dead:
        return paddle_y + min(speed, ball_y - paddle_y)
    if paddle_y > ball_y + dead:
        return paddle_y - min(speed, paddle_y - ball_y)
    return paddle_y

y = 160
path = []
for ball_y in [160, 200, 200, 200, 120, 162]:
    y = ai_move(y, ball_y, speed=15)
    path.append(y)
print(path)
פלטOutput
[160, 175, 190, 200, 185, 170]
צפו בהרצה צעד אחר צעד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

אנלוגיה מהחייםReal-life analogy

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

A good AI opponent is like a tennis coach playing with a kid: could return every ball, but leaves room to win.

טעות נפוצהCommon mistake

יריב בלי הגבלת מהירות שאי אפשר לנצח.

An opponent without a speed limit that can't be beaten.

ai.py
def ai_move(paddle_y, ball_y):
    return ball_y

misses = sum(1 for ball_y in range(0, 320, 7) if ai_move(160, ball_y) != ball_y)
assert misses > 0, "the AI teleports to every ball: it never misses, so the game is no fun"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/ai.py", line 5, in <module>
    assert misses > 0, "the AI teleports to every ball: it never misses, so the game is no fun"
           ^^^^^^^^^^
AssertionError: the AI teleports to every ball: it never misses, so the game is no fun
בעברית פשוטה: In plain words: AssertionError: the AI teleports to every ball: ...: מגבילים מהירות (min(speed, ...)) כדי שיהיה סיכוי לנצח.AssertionError: the AI teleports to every ball: ...: cap the speed (min(speed, ...)) so there's a chance to win.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

05זמן פריים ושקיפותDelta time and transparency

אם המהירות היא "5 פיקסלים לפריים", במחשב איטי (30 FPS) המשחק איטי פי שניים. פתרון: זמן פריים. dt = clock.tick(60) / 1000 נותן שניות, והמהירות היא בפיקסלים לשנייה: x += speed * dt. ולאפקט הניאון: מציירים צורות חצי-שקופות על Surface עם SRCALPHA, גדולות מעט מהמקור, ומניחים מעל:

If the speed is "5 pixels per frame", on a slow computer (30 FPS) the game runs half as fast. Fix: delta time (dt). dt = clock.tick(60) / 1000 gives seconds, and speed is in pixels per second: x += speed * dt. For the neon effect: draw half-transparent shapes on a Surface with SRCALPHA, slightly larger than the original, and layer it on top:

dt.py
def run(fps, seconds=2, speed=300):
    x, dt = 0.0, 1 / fps
    for _ in range(int(fps * seconds)):
        x += speed * dt
    return round(x)

print("60 FPS:", run(60), " 30 FPS:", run(30), " 144 FPS:", run(144))

import pygame
glow = pygame.Surface((40, 40), pygame.SRCALPHA)
pygame.draw.rect(glow, (0, 240, 255, 60), (0, 0, 40, 40))
print(glow.get_at((5, 5)), glow.get_flags() & pygame.SRCALPHA != 0)
פלטOutput
60 FPS: 600  30 FPS: 600  144 FPS: 600
Color(0, 240, 255, 60) True
אנלוגיה מהחייםReal-life analogy

dt הוא כמו לחשב מהירות של מכונית בקמ"ש ולא ב"קפיצות": לא משנה כמה פעמים בודקים את המד, המרחק לשעה זהה.

dt is like measuring a car's speed in km/h rather than "jumps": however often you check the meter, the distance per hour is the same.

טעות נפוצהCommon mistake

צבע עם שקיפות על Surface רגיל.

A transparent colour on a plain Surface.

dt.py
import pygame
s = pygame.Surface((10, 10))
s.fill((0, 240, 255, 60))
assert s.get_at((0, 0)).a < 255, f"alpha is {s.get_at((0, 0)).a}: a plain Surface ignores alpha, create it with pygame.SRCALPHA"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/dt.py", line 4, in <module>
    assert s.get_at((0, 0)).a < 255, f"alpha is {s.get_at((0, 0)).a}: a plain Surface ignores alpha, create it with pygame.SRCALPHA"
           ^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: alpha is 255: a plain Surface ignores alpha, create it with pygame.SRCALPHA
בעברית פשוטה: In plain words: AssertionError: alpha is 255: ...: Surface רגיל מתעלם מהשקיפות. יוצרים pygame.Surface(size, pygame.SRCALPHA).AssertionError: alpha is 255: ...: a plain Surface ignores alpha. Create pygame.Surface(size, pygame.SRCALPHA).

06Neon Pong: המשחקNeon Pong: the game

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

All the pieces together: paddles, a float-position ball, angle by hit point, AI players (here both are AI, the left one a bit faster), scoring, re-serving toward whoever conceded, and a neon glow. On your computer swap the left paddle for the W/S keys:

neon_pong.py
import pygame

W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 48)
glow = pygame.Surface((W, H), pygame.SRCALPHA)


def neon_rect(rect, color):
    for grow, alpha in ((10, 40), (5, 80)):
        pygame.draw.rect(glow, (*color, alpha), rect.inflate(grow, grow), border_radius=6)
    pygame.draw.rect(screen, color, rect, border_radius=4)


left = pygame.Rect(16, H // 2 - 35, 10, 70)
right = pygame.Rect(W - 26, H // 2 - 35, 10, 70)
ball = pygame.Rect(W // 2 - 6, H // 2 - 6, 12, 12)
vx, vy = 5.0, 2.0
bx, by = float(ball.x), float(ball.y)
score = [0, 0]
for frame in range(400):
    for paddle, speed in ((left, 4), (right, 3)):
        if paddle.centery < ball.centery - 4:
            paddle.y += speed
        elif paddle.centery > ball.centery + 4:
            paddle.y -= speed
        paddle.clamp_ip(screen.get_rect())
    bx += vx
    by += vy
    ball.topleft = (round(bx), round(by))
    if ball.top <= 0 or ball.bottom >= H:
        vy = -vy
    for paddle in (left, right):
        if ball.colliderect(paddle) and (vx < 0) == (paddle is left):
            offset = (ball.centery - paddle.centery) / (paddle.height / 2)
            vx, vy = -vx * 1.05, offset * 5
    if ball.right < 0 or ball.left > W:
        score[0 if ball.left > W else 1] += 1
        bx, by, vx, vy = W / 2 - 6, H / 2 - 6, (5.0 if vx < 0 else -5.0), 2.0
    glow.fill((0, 0, 0, 0))
    screen.fill((8, 6, 20))
    for y in range(0, H, 20):
        pygame.draw.rect(screen, (60, 50, 90), (W // 2 - 1, y, 2, 10))
    neon_rect(left, (0, 240, 255))
    neon_rect(right, (255, 60, 200))
    neon_rect(ball, (255, 255, 120))
    screen.blit(glow, (0, 0))
    screen.blit(font.render(f"{score[0]}   {score[1]}", True, (220, 220, 255)), (W // 2 - 42, 12))
    pygame.display.flip()
print("score:", score)
pygame.quit()
פלטOutput
score: [1, 0]
Neon Pong: מחבט תכלת זוהר משמאל ומחבט ורוד זוהר מימין, כדור צהוב זוהר, קו אמצע מקווקו וניקוד למעלה.
screen.png
אנלוגיה מהחייםReal-life analogy

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

The glow layer is like tracing paper over a drawing: the colours behind show through, softened.

טעות נפוצהCommon mistake

ניקוד לצד הלא נכון.

Scoring for the wrong side.

neon_pong.py
score = [0, 0]
ball_left_x = 500
W = 480
score[0 if ball_left_x < 0 else 1] += 1
assert score == [1, 0], f"the ball went out on the right, so the LEFT player scores, got {score}"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/neon_pong.py", line 5, in <module>
    assert score == [1, 0], f"the ball went out on the right, so the LEFT player scores, got {score}"
           ^^^^^^^^^^^^^^^
AssertionError: the ball went out on the right, so the LEFT player scores, got [0, 1]
בעברית פשוטה: In plain words: AssertionError: כדור שיצא מימין = נקודה לשחקן השמאלי. בודקים את התנאי עם דוגמה ביד.AssertionError: a ball out on the right = a point for the left player. Check the condition with an example by hand.
צפו איפה זה נשבר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