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

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

Physics Lab: מעבדת סימולציותPhysics Lab

חלקיקים, בד Verlet, משחק החיים ולהקות Boids.

Particles, Verlet cloth, the Game of Life and Boids flocks.

01וקטוריםVectors

עד עכשיו כתבנו כל דבר פעמיים: x += vx ו-y += vy. וקטור מחזיק את שניהם, ו-pygame נותן pygame.math.Vector2: מחברים וקטורים, כופלים במספר, מודדים אורך, ומנרמלים לכיוון באורך 1. מעבדת הפיזיקה שלנו בנויה עליו:

Until now we wrote everything twice: x += vx and y += vy. A vector holds both, and pygame provides pygame.math.Vector2: add vectors, multiply by a number, measure length, and normalise to a direction of length 1. Our physics lab is built on it:

vectors.py
from pygame.math import Vector2

pos = Vector2(100, 50)
vel = Vector2(3, 4)
print(pos + vel, vel * 2, vel.length())
target = Vector2(400, 290)
direction = (target - pos).normalize()
print(direction, round(direction.length(), 6))
print("distance:", round(pos.distance_to(target), 1), " angle:", round(Vector2(1, 0).angle_to(vel), 1))
פלטOutput
[103, 54] [6, 8] 5.0
[0.780869, 0.624695] 1.0
distance: 384.2  angle: 53.1
אנלוגיה מהחייםReal-life analogy

וקטור הוא כמו חץ על מפה: יש לו כיוון ויש לו אורך, ואפשר לשרשר חצים: "3 צפונה ואז 4 מזרחה" הוא חץ אחד באורך 5.

A vector is like an arrow on a map: it has a direction and a length, and arrows chain: "3 north then 4 east" is one arrow of length 5.

טעות נפוצהCommon mistake

מנרמלים וקטור באורך אפס.

Normalising a zero-length vector.

vectors.py
from pygame.math import Vector2
print(Vector2(0, 0).normalize())
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/vectors.py", line 2, in <module>
    print(Vector2(0, 0).normalize())
          ~~~~~~~~~~~~~~~~~~~~~~~^^
ValueError: Can't normalize Vector of length zero
בעברית פשוטה: In plain words: ValueError: Can't normalize Vector of length zero: אין כיוון לחץ באורך 0. בודקים if v.length() > 0: לפני.ValueError: Can't normalize Vector of length zero: an arrow of length 0 has no direction. Check if v.length() > 0: first.

וקטור הוא חץ. פיתגורס נותן את האורך.

A vector is an arrow. Pythagoras gives its length.

עוד דוגמה: אורך של חץOne more: the length of an arrow
example.py
import math
vx, vy = 3, 4
length = math.hypot(vx, vy)
print(length)
print(vx / length, vy / length)
פלטOutput
5.0
0.6 0.8
צפו בהרצה צעד אחר צעד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

02כוחות ותאוצהForces and acceleration

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

Every simulation is built on the same loop: add all the forces (gravity, wind, a push) into one vector, divide by mass to get acceleration, then with Euler integration update velocity and then position. Here a body in gravity and a side wind, with dt of 1/60 second:

forces.py
from pygame.math import Vector2

mass, dt = 2.0, 1 / 60
pos, vel = Vector2(0, 0), Vector2(0, 0)
gravity = Vector2(0, 9.8) * mass
wind = Vector2(3, 0)
for step in range(60):
    acc = (gravity + wind) / mass
    vel += acc * dt
    pos += vel * dt
print("after 1 second: pos", (round(pos.x, 2), round(pos.y, 2)), "vel", (round(vel.x, 2), round(vel.y, 2)))
פלטOutput
after 1 second: pos (0.76, 4.98) vel (1.5, 9.8)
אנלוגיה מהחייםReal-life analogy

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

A simulation is like walking in boots in the dark: every step you feel where the forces pull, adjust a little, and step again.

טעות נפוצהCommon mistake

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

Updating position before velocity, getting a different result.

forces.py
dt, g = 0.5, 10.0
y_a = v_a = 0.0
y_b = v_b = 0.0
for _ in range(4):
    v_a += g * dt; y_a += v_a * dt
    y_b += v_b * dt; v_b += g * dt
assert y_a == y_b, f"{y_a} vs {y_b}: the order matters; update velocity first (semi-implicit Euler is more stable)"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/forces.py", line 7, in <module>
    assert y_a == y_b, f"{y_a} vs {y_b}: the order matters; update velocity first (semi-implicit Euler is more stable)"
           ^^^^^^^^^^
AssertionError: 25.0 vs 15.0: the order matters; update velocity first (semi-implicit Euler is more stable)
בעברית פשוטה: In plain words: AssertionError: 25.0 vs 15.0: ...: הסדר משנה. מהירות קודם ואז מיקום ("אוילר חצי-מרומז") יציב יותר במשחקים.AssertionError: 25.0 vs 15.0: ...: the order matters. Velocity first then position ("semi-implicit Euler") is more stable in games.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

03זריקה ומסלולThrowing and trajectory

זורקים כדור בזווית: המהירות ההתחלתית היא וקטור שאורכו המהירות וכיוונו הזווית (Vector2.from_polar). כאן מריצים סימולציה עם שני ערכי dt ומשווים לנוסחה המדויקת של טווח זריקה, v² × sin(2θ) / g. הגרף מראה את המסלולים:

Throw a ball at an angle: the initial velocity is a vector whose length is the speed and whose direction is the angle (Vector2.from_polar). Here we run the simulation with two dt values and compare to the exact range formula, v² × sin(2θ) / g. The chart shows the paths:

throw.py
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pygame.math import Vector2

def throw(speed, angle, dt, g=9.8):
    pos, vel = Vector2(0, 0), Vector2()
    vel.from_polar((speed, angle))
    path = [Vector2(pos)]
    while pos.y >= 0:
        vel.y -= g * dt
        pos += vel * dt
        path.append(Vector2(pos))
    return path

exact = 20 ** 2 * math.sin(math.radians(2 * 45)) / 9.8
fig, ax = plt.subplots(figsize=(6, 2.8))
for dt in (0.2, 0.01):
    path = throw(20, 45, dt)
    ax.plot([p.x for p in path], [max(p.y, 0) for p in path], label=f"dt={dt}")
    print(f"dt={dt}: lands at {path[-1].x:.1f} m (exact {exact:.1f})")
ax.legend()
ax.set_xlabel("distance (m)")
ax.set_ylabel("height (m)")
fig.savefig("throw.png", dpi=80, bbox_inches="tight")
פלטOutput
dt=0.2: lands at 39.6 m (exact 40.8)
dt=0.01: lands at 40.7 m (exact 40.8)
גרף של שני מסלולי זריקה: עם dt=0.2 הקשת מחוספסת ונוחתת מעט רחוק מדי, ועם dt=0.01 היא חלקה ונוחתת קרוב ל-40.8 מטר.
throw.png
אנלוגיה מהחייםReal-life analogy

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

dt is like the frame count in a slow-motion video: few frames = jumps and errors, many frames = smooth, accurate motion.

טעות נפוצהCommon mistake

נותנים זווית במעלות לפונקציה שמצפה לרדיאנים.

Passing degrees to a function expecting radians.

throw.py
import math
angle = 45
assert abs(math.sin(angle) - 0.7071) < 0.01, f"sin(45) = {math.sin(angle):.3f}: math.sin wants radians; use math.radians(45)"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/throw.py", line 3, in <module>
    assert abs(math.sin(angle) - 0.7071) < 0.01, f"sin(45) = {math.sin(angle):.3f}: math.sin wants radians; use math.radians(45)"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: sin(45) = 0.851: math.sin wants radians; use math.radians(45)
בעברית פשוטה: In plain words: AssertionError: sin(45) = 0.851: ...: math עובד ברדיאנים. ממירים עם math.radians. (from_polar של pygame דווקא מקבל מעלות.)AssertionError: sin(45) = 0.851: ...: math works in radians. Convert with math.radians. (pygame's from_polar does take degrees.)
צפו איפה זה נשבר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קפיץ וריסוןA spring and damping

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

A spring pulls back with a force that grows the more you stretch it: F = -k × (distance - rest length). Without friction it oscillates forever. A little damping, multiplying velocity by 0.98 each step, makes the oscillation die down like in reality. The same code moves a "soft" camera in games:

spring.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

def spring(k, damping, steps=300, dt=1 / 60):
    x, v, xs = 100.0, 0.0, []
    for _ in range(steps):
        v += -k * x * dt
        v *= damping
        x += v * dt
        xs.append(x)
    return xs

fig, ax = plt.subplots(figsize=(6, 2.6))
for damping in (1.0, 0.98):
    xs = spring(40, damping)
    ax.plot(xs, label=f"damping {damping}")
    print(f"damping {damping}: last swing {max(abs(x) for x in xs[-60:]):.1f}")
ax.legend()
fig.savefig("spring.png", dpi=80, bbox_inches="tight")
פלטOutput
damping 1.0: last swing 100.1
damping 0.98: last swing 8.8
שני גלים: בלי ריסון התנודה נשארת בגובה קבוע, ועם ריסון 0.98 היא דועכת בהדרגה לאפס.
spring.png
אנלוגיה מהחייםReal-life analogy

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

Damping is like a playground swing: if nobody pushes, it swings less and less until it stops.

טעות נפוצהCommon mistake

ריסון גדול מ-1 שמוסיף אנרגיה.

A damping above 1 that adds energy.

spring.py
x, v = 100.0, 0.0
for _ in range(600):
    v += -40 * x / 60
    v *= 1.02
    x += v / 60
assert abs(x) < 1000, f"x = {x:.0f}: a damping factor above 1 pumps energy in and the spring explodes"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/spring.py", line 6, in <module>
    assert abs(x) < 1000, f"x = {x:.0f}: a damping factor above 1 pumps energy in and the spring explodes"
           ^^^^^^^^^^^^^
AssertionError: x = 31170: a damping factor above 1 pumps energy in and the spring explodes
בעברית פשוטה: In plain words: AssertionError: מקדם ריסון חייב להיות קטן מ-1 (או שווה, בלי ריסון).AssertionError: a damping factor must be below 1 (or equal, for none).

05מסלול כוכב לכתA planet's orbit

כבידה בין שני גופים חלשה עם המרחק: G·M / r², וכיוונה אל השמש. אם נותנים לכוכב הלכת מהירות צידה בדיוק נכונה, הוא לא נופל ולא בורח, אלא מקיף. כאן מציירים את המסלול בחלון pygame. מדד טוב לבדיקת סימולציה: האנרגיה הכוללת צריכה להישאר כמעט קבועה:

Gravity between two bodies weakens with distance: G·M / r², pointing toward the sun. Give the planet exactly the right sideways speed and it neither falls in nor escapes, but orbits. Here we draw the orbit in a pygame window. A good measure for checking a simulation: total energy should stay nearly constant:

orbit.py
import pygame
from pygame.math import Vector2

pygame.init()
screen = pygame.display.set_mode((480, 320))
screen.fill((6, 6, 18))
sun = Vector2(240, 160)
GM = 4000.0
pos = Vector2(240, 60)
vel = Vector2((GM / 100) ** 0.5, 0)
dt = 0.05

def energy(p, v):
    return 0.5 * v.length_squared() - GM / p.distance_to(sun)

start = energy(pos, vel)
for step in range(4000):
    to_sun = sun - pos
    acc = to_sun.normalize() * GM / to_sun.length_squared()
    vel += acc * dt
    pos += vel * dt
    if step % 8 == 0:
        pygame.draw.circle(screen, (110, 170, 255), pos, 1)
pygame.draw.circle(screen, (255, 210, 80), sun, 14)
pygame.draw.circle(screen, (140, 200, 255), pos, 6)
print(f"energy drift: {abs(energy(pos, vel) - start) / abs(start):.3%}")
pygame.quit()
פלטOutput
energy drift: 0.000%
שמש צהובה במרכז ומסלול עגול של נקודות כחולות סביבה, עם כוכב לכת כחול על המסלול.
screen.png
אנלוגיה מהחייםReal-life analogy

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

An orbit is like throwing a ball so hard sideways that while it falls, the Earth curves away beneath it, and it never lands.

טעות נפוצהCommon mistake

כוח שמחושב עם r ולא r², והמסלול מתפרק.

A force computed with r instead of r², so the orbit falls apart.

orbit.py
from pygame.math import Vector2
sun, GM = Vector2(0, 0), 4000.0
pos, vel = Vector2(0, -100), Vector2((GM / 100) ** 0.5, 0)
for _ in range(2000):
    d = sun - pos
    vel += d.normalize() * GM / d.length() * 0.05
    pos += vel * 0.05
assert 80 < pos.length() < 120, f"radius drifted to {pos.length():.0f}: gravity divides by r squared"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/orbit.py", line 8, in <module>
    assert 80 < pos.length() < 120, f"radius drifted to {pos.length():.0f}: gravity divides by r squared"
           ^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: radius drifted to 164: gravity divides by r squared
בעברית פשוטה: In plain words: AssertionError: radius drifted to 164: gravity divides by r squared: חוק הכבידה של ניוטון מחלק בריבוע המרחק. טעות בחזקה משנה את כל הפיזיקה.AssertionError: radius drifted to 164: gravity divides by r squared: Newton's law of gravity divides by the distance squared. A wrong power changes all the physics.

06Physics Lab: מעבדה בחלוןPhysics Lab: a lab in a window

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

The lab ties it all together: dozens of balls with gravity, light damping, wall bounces (from this part's first session), and ball-to-ball collisions (session 37's challenge). Each ball is coloured by its speed, from slow blue to fast red, and the total energy is shown in the corner:

physics_lab.py
import random
import pygame
from pygame.math import Vector2

W, H, R = 480, 320, 9
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 24)
random.seed(11)
balls = [[Vector2(random.uniform(20, W - 20), random.uniform(20, 160)), Vector2(random.uniform(-4, 4), 0)] for _ in range(30)]
gravity = Vector2(0, 0.25)
for frame in range(300):
    for p, v in balls:
        v += gravity
        v *= 0.999
        p += v
        if p.x < R or p.x > W - R:
            p.x = max(R, min(W - R, p.x)); v.x = -v.x * 0.9
        if p.y > H - R:
            p.y = H - R; v.y = -v.y * 0.85
    for i in range(len(balls)):
        for j in range(i + 1, len(balls)):
            (pa, va), (pb, vb) = balls[i], balls[j]
            d = pb - pa
            if 0 < d.length() < 2 * R:
                n = d.normalize()
                swap = (vb - va).dot(n)
                if swap < 0:
                    va += n * swap; vb -= n * swap
                push = n * (2 * R - d.length()) / 2
                pa -= push; pb += push
screen.fill((14, 16, 28))
kinetic = 0.0
for p, v in balls:
    speed = min(1.0, v.length() / 6)
    kinetic += 0.5 * v.length_squared()
    pygame.draw.circle(screen, (int(80 + 175 * speed), 120, int(255 - 175 * speed)), p, R)
screen.blit(font.render(f"kinetic energy {kinetic:.1f}", True, (220, 220, 240)), (8, 6))
print("balls resting on the floor:", sum(1 for p, v in balls if p.y > H - R - 1 and v.length() < 1))
pygame.quit()
פלטOutput
balls resting on the floor: 3
מעבדת פיזיקה: עשרות כדורים שהצטברו בתחתית החלון בגוונים של כחול וסגול, וטקסט אנרגיה בפינה.
screen.png
אנלוגיה מהחייםReal-life analogy

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

The lab is like an aquarium: set simple rules for each fish, and get complex group behaviour nobody programmed directly.

טעות נפוצהCommon mistake

משנים וקטור משותף בטעות.

Accidentally changing a shared vector.

physics_lab.py
from pygame.math import Vector2
start = Vector2(0, 0)
balls = [start, start]
balls[0] += Vector2(5, 0)
assert balls[1] == Vector2(0, 0), f"ball 2 moved to {balls[1]}: both entries are the same Vector2 object"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/physics_lab.py", line 5, in <module>
    assert balls[1] == Vector2(0, 0), f"ball 2 moved to {balls[1]}: both entries are the same Vector2 object"
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: ball 2 moved to [5, 0]: both entries are the same Vector2 object
בעברית פשוטה: In plain words: AssertionError: ball 2 moved to [5, 0]: ...: += על Vector2 משנה במקום, ושני האיברים מצביעים לאותו אובייקט (זוכרים את מפגש 6?). יוצרים Vector2(start) לכל אחד.AssertionError: ball 2 moved to [5, 0]: ...: += on a Vector2 changes it in place, and both entries point to the same object (remember session 6?). Create Vector2(start) for each.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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