נבנה על ידי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.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

וקטורים בלי pygameVectors without pygame

תזכורת: מה ביקשוReminder: the task

כתבו מחלקה Vec(x, y) עם __add__, __sub__, __mul__ (במספר), length(), normalized() (ValueError לאורך 0) ו-__repr__ בצורה Vec(3.0, 4.0). ערכים נשמרים כ-float.

Write a Vec(x, y) class with __add__, __sub__, __mul__ (by a number), length(), normalized() (ValueError for length 0) and __repr__ like Vec(3.0, 4.0). Values are stored as floats.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import math

class Vec:
    def __init__(self, x, y):
        self.x, self.y = float(x), float(y)

    def __add__(self, o):
        return Vec(self.x + o.x, self.y + o.y)

    def __sub__(self, o):
        return Vec(self.x - o.x, self.y - o.y)

    def __mul__(self, k):
        return Vec(self.x * k, self.y * k)

    def length(self):
        return math.hypot(self.x, self.y)

    def normalized(self):
        L = self.length()
        if L == 0:
            raise ValueError("zero-length vector")
        return self * (1 / L)

    def __repr__(self):
        return f"Vec({self.x}, {self.y})"

print(Vec(1, 2) + Vec(2, 2), Vec(3, 4).length(), Vec(0, 5).normalized(), Vec(1, 1) * 3)
פלטOutput
Vec(3.0, 4.0) 5.0 Vec(0.0, 1.0) Vec(3.0, 3.0)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

נפילה חופשיתFree fall

תזכורת: מה ביקשוReminder: the task

כתבו fall_time(height, dt, g=9.8) שמסמלצת נפילה מגובה height (מהירות התחלתית 0, אוילר חצי-מרומז) ומחזירה את הזמן (בשניות, מעוגל ל-3) עד שהגובה ≤ 0. השוו לנוסחה המדויקת sqrt(2h / g): ככל ש-dt קטן, הם קרובים יותר.

Write fall_time(height, dt, g=9.8) simulating a fall from height (initial velocity 0, semi-implicit Euler) and returning the time (seconds, rounded to 3) until the height ≤ 0. Compare to the exact formula sqrt(2h / g): the smaller dt, the closer.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import math

def fall_time(height, dt, g=9.8):
    y, v, t = float(height), 0.0, 0.0
    while y > 0:
        v += g * dt
        y -= v * dt
        t += dt
    return round(t, 3)

exact = math.sqrt(2 * 20 / 9.8)
for dt in (0.1, 0.01, 0.001):
    print(dt, fall_time(20, dt), round(abs(fall_time(20, dt) - exact), 3))
פלטOutput
0.1 2.0 0.02
0.01 2.02 0.0
0.001 2.02 0.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

קפיץA spring

תזכורת: מה ביקשוReminder: the task

כתבו spring_steps(k, damping, x0, steps, dt=1/60) שמחזירה רשימת מיקומים (חוק הוק, v += -k*x*dt; v *= damping; x += v*dt), ו-settle_time(k, damping, x0, tolerance=1.0, dt=1/60) שמחזירה את מספר הצעד הראשון שאחריו |x| נשאר קטן מ-tolerance ב-60 הצעדים הבאים (עד 5000), או None.

Write spring_steps(k, damping, x0, steps, dt=1/60) returning a list of positions (Hooke's law, v += -k*x*dt; v *= damping; x += v*dt), and settle_time(k, damping, x0, tolerance=1.0, dt=1/60) returning the first step after which |x| stays below tolerance for the next 60 steps (up to 5000), or None.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def spring_steps(k, damping, x0, steps, dt=1 / 60):
    x, v, xs = float(x0), 0.0, []
    for _ in range(steps):
        v += -k * x * dt
        v *= damping
        x += v * dt
        xs.append(x)
    return xs

def settle_time(k, damping, x0, tolerance=1.0, dt=1 / 60):
    xs = spring_steps(k, damping, x0, 5060, dt)
    for i in range(5000):
        if all(abs(v) < tolerance for v in xs[i:i + 60]):
            return i
    return None

print(settle_time(40, 0.98, 100), settle_time(40, 0.95, 100), settle_time(40, 1.0, 100))
פלטOutput
453 165 None

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

אנרגיה כבדיקהEnergy as a check

תזכורת: מה ביקשוReminder: the task

כתבו orbit_drift(dt, steps, GM=4000.0, r=100.0) שמסמלצת כוכב לכת במסלול מעגלי (מתחיל ב-(0, -r) עם מהירות sqrt(GM/r) בציר x, שמש ב-(0,0)) ומחזירה את השינוי היחסי באנרגיה (|E_end - E_start| / |E_start|), כש-E = 0.5·v² - GM/r. dt קטן אמור לתת סחיפה קטנה יותר.

Write orbit_drift(dt, steps, GM=4000.0, r=100.0) simulating a planet on a circular orbit (starting at (0, -r) with speed sqrt(GM/r) along x, the sun at (0,0)) and returning the relative energy change (|E_end - E_start| / |E_start|), where E = 0.5·v² - GM/r. A smaller dt should drift less.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import math

def orbit_drift(dt, steps, GM=4000.0, r=100.0):
    x, y, vx, vy = 0.0, -r, math.sqrt(GM / r), 0.0
    energy = lambda: 0.5 * (vx * vx + vy * vy) - GM / math.hypot(x, y)
    e0 = energy()
    for _ in range(steps):
        d = math.hypot(x, y)
        vx += -GM * x / d ** 3 * dt
        vy += -GM * y / d ** 3 * dt
        x += vx * dt
        y += vy * dt
    return abs(energy() - e0) / abs(e0)

for dt in (0.5, 0.1, 0.02):
    print(dt, f"{orbit_drift(dt, round(200 / dt)):.5f}")
פלטOutput
0.5 0.00000
0.1 0.00000
0.02 0.00000

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

Physics Lab: עולם כדוריםPhysics Lab: a world of balls

תזכורת: מה ביקשוReminder: the task

כתבו מחלקה World(w, h, r=9, gravity=0.25, damping=0.999) עם add(x, y, vx, vy) ו-step(): לכל כדור כבידה, ריסון ותנועה, הקפצה מהקירות (×0.9) ומהרצפה (×0.85), והתנגשויות בין כדורים (החלפת רכיבי מהירות לאורך הקו + הרחקה). kinetic() מחזירה את סכום 0.5·v² מעוגל ל-2. כדור הוא רשימה [x, y, vx, vy].

Write a World(w, h, r=9, gravity=0.25, damping=0.999) class with add(x, y, vx, vy) and step(): gravity, damping and motion for each ball, bounces off walls (×0.9) and the floor (×0.85), and ball-to-ball collisions (swap velocity components along the line + separate). kinetic() returns the sum of 0.5·v² rounded to 2. A ball is a list [x, y, vx, vy].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
physics_lab.py
import math

class World:
    def __init__(self, w, h, r=9, gravity=0.25, damping=0.999):
        self.w, self.h, self.r, self.g, self.damp = w, h, r, gravity, damping
        self.balls = []

    def add(self, x, y, vx, vy):
        self.balls.append([float(x), float(y), float(vx), float(vy)])

    def step(self):
        r = self.r
        for b in self.balls:
            b[3] += self.g
            b[2] *= self.damp
            b[3] *= self.damp
            b[0] += b[2]
            b[1] += b[3]
            if b[0] < r or b[0] > self.w - r:
                b[0] = max(r, min(self.w - r, b[0]))
                b[2] = -b[2] * 0.9
            if b[1] > self.h - r:
                b[1] = self.h - r
                b[3] = -b[3] * 0.85
        for i in range(len(self.balls)):
            for j in range(i + 1, len(self.balls)):
                a, c = self.balls[i], self.balls[j]
                dx, dy = c[0] - a[0], c[1] - a[1]
                d = math.hypot(dx, dy)
                if 0 < d < 2 * r:
                    nx, ny = dx / d, dy / d
                    swap = (c[2] - a[2]) * nx + (c[3] - a[3]) * ny
                    if swap < 0:
                        a[2] += nx * swap; a[3] += ny * swap
                        c[2] -= nx * swap; c[3] -= ny * swap
                    push = (2 * r - d) / 2
                    a[0] -= nx * push; a[1] -= ny * push
                    c[0] += nx * push; c[1] += ny * push

    def kinetic(self):
        return round(sum(0.5 * (b[2] ** 2 + b[3] ** 2) for b in self.balls), 2)

w = World(200, 100, gravity=0)
w.add(50, 50, 2, 0)
w.add(70, 50, -2, 0)
w.step()
print([round(b[2], 2) for b in w.balls], w.kinetic())
פלטOutput
[-2.0, 2.0] 3.99

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

רונגה-קוטה מול אוילרRunge-Kutta vs Euler

תזכורת: מה ביקשוReminder: the task

אוילר צובר שגיאות. כתבו simulate(method, dt, t_end) לנפילה חופשית עם התנגדות אוויר (a = g - c·v², g=9.8, c=0.05) שמחזירה את המהירות ב-t_end, כש-method הוא "euler" או "rk4". ב-RK4 מחשבים ארבעה שיפועים: k1 = f(v), k2 = f(v + k1·dt/2), k3 = f(v + k2·dt/2), k4 = f(v + k3·dt) ו-v += dt·(k1 + 2k2 + 2k3 + k4)/6. המהירות הסופית המדויקת היא sqrt(g/c).

Euler accumulates errors. Write simulate(method, dt, t_end) for a free fall with air drag (a = g - c·v², g=9.8, c=0.05) returning the velocity at t_end, where method is "euler" or "rk4". In RK4 compute four slopes: k1 = f(v), k2 = f(v + k1·dt/2), k3 = f(v + k2·dt/2), k4 = f(v + k3·dt) and v += dt·(k1 + 2k2 + 2k3 + k4)/6. The exact terminal velocity is sqrt(g/c).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import math

def simulate(method, dt, t_end):
    f = lambda v: 9.8 - 0.05 * v * v
    v = 0.0
    for _ in range(round(t_end / dt)):
        if method == "euler":
            v += f(v) * dt
        else:
            k1 = f(v)
            k2 = f(v + k1 * dt / 2)
            k3 = f(v + k2 * dt / 2)
            k4 = f(v + k3 * dt)
            v += dt * (k1 + 2 * k2 + 2 * k3 + k4) / 6
    return v

exact_at_2 = math.sqrt(9.8 / 0.05) * math.tanh(2 * math.sqrt(9.8 * 0.05))
for m in ("euler", "rk4"):
    print(m, f"error {abs(simulate(m, 0.25, 2) - exact_at_2):.6f}")
print(round(simulate("rk4", 0.1, 30), 4), round(math.sqrt(9.8 / 0.05), 4))
פלטOutput
euler error 0.424475
rk4 error 0.000228
14.0 14.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

מערכת קפיציםA spring chain

תזכורת: מה ביקשוReminder: the task

כתבו chain(n, steps, k=30, damping=0.98, rest=20, dt=1/60, g=9.8): שרשרת של n משקולות תלויות זו מתחת לזו מנקודה קבועה ב-y=0, מחוברות בקפיצים באורך מנוחה rest. כל משקולת (מסה 1) מושפעת מכבידה ומשני הקפיצים שלה. מחזירה את מיקומי y של המשקולות (מעוגלים ל-1) אחרי steps צעדים. במנוחה, כל קפיץ נמתח לפי המשקל שמתחתיו.

Write chain(n, steps, k=30, damping=0.98, rest=20, dt=1/60, g=9.8): a chain of n weights hanging one below another from a fixed point at y=0, joined by springs of rest length rest. Each weight (mass 1) feels gravity and its two springs. Return the weights' y positions (rounded to 1) after steps steps. At rest, each spring stretches by the weight below it.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def chain(n, steps, k=30, damping=0.98, rest=20, dt=1 / 60, g=9.8):
    ys = [rest * (i + 1) for i in range(n)]
    vs = [0.0] * n
    for _ in range(steps):
        above = [0.0] + ys[:-1]
        forces = []
        for i in range(n):
            f = g - k * ((ys[i] - above[i]) - rest)
            if i + 1 < n:
                f += k * ((ys[i + 1] - ys[i]) - rest)
            forces.append(f)
        for i in range(n):
            vs[i] = (vs[i] + forces[i] * dt) * damping
            ys[i] += vs[i] * dt
    return [round(y, 1) for y in ys]

settled = chain(3, 4000)
expected = [round(sum(20 + 9.8 * (3 - j) / 30 for j in range(i + 1)), 1) for i in range(3)]
print(settled, expected)
פלטOutput
[21.0, 41.6, 62.0] [21.0, 41.6, 62.0]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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