חלק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.
הנקודות החשובותKey points
- Vector2: חיבור, כפל, אורךVector2: add, scale, length
normalize()= כיוון באורך 1normalize()= a direction of length 1- כוח → תאוצה:
a = F / mForce → acceleration:a = F / m - אוילר:
v += a*dt,p += v*dtEuler:v += a*dt,p += v*dt - מהירות התחלתית לפי זוויתInitial velocity from an angle
- סימולציה מול נוסחהSimulation vs formula
- חוק הוק:
F = -k × מתיחהHooke's law:F = -k × stretch - ריסון:
vel *= 0.98damping:vel *= 0.98 - כבידה בין שני גופים:
G·M / r²Gravity between two bodies:G·M / r²
מונחיםTerms
- וקטורvector: זוג מספרים (x, y) שמייצג כיוון וגודל: מיקום, מהירות או כוח.
Vector2(3, 4).length()הוא 5.A pair of numbers (x, y) representing direction and size: a position, velocity or force.Vector2(3, 4).length()is 5. - כוחforce: דחיפה או משיכה. לפי ניוטון: תאוצה = כוח חלקי מסה (
a = F / m).A push or pull. By Newton: acceleration = force divided by mass (a = F / m). - שילוב אוילרEuler integration: הדרך הפשוטה לקדם סימולציה:
v += a * dtואזp += v * dt. ככל ש-dt קטן יותר, מדויק יותר.The simple way to advance a simulation:v += a * dtthenp += v * dt. The smaller dt, the more accurate. - אנרגיהenergy: גודל שבמערכת סגורה אמור להישמר. אם הוא גדל בסימולציה, זה סימן לשגיאה מספרית.A quantity that should stay constant in a closed system. If it grows in a simulation, that's a sign of numerical error.
- ריסוןdamping: איבוד אנרגיה הדרגתי, כמו חיכוך באוויר: כופלים מהירות במספר קטן מ-1 בכל צעד.A gradual loss of energy, like air friction: multiply velocity by a number below 1 each step.
Cheatsheet
וקטוריםVectors
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()כוחותForces
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):זריקהThrow
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):קפיץSpring
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):מסלולOrbit
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)מעבדהLab
import random
import pygame
from pygame.math import Vector2
W, H, R = 480, 320, 9
pygame.init()
screen = pygame.display.set_mode((W, H))שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
ValueError | מנרמלים וקטור באורך אפס.Normalising a zero-length vector. | 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. |
AssertionError | מעדכנים מיקום לפני מהירות, ומקבלים תוצאה שונה.Updating position before velocity, getting a different result. | 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. |
AssertionError | נותנים זווית במעלות לפונקציה שמצפה לרדיאנים.Passing degrees to a function expecting radians. | 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.) |
AssertionError | ריסון גדול מ-1 שמוסיף אנרגיה.A damping above 1 that adds energy. | AssertionError: מקדם ריסון חייב להיות קטן מ-1 (או שווה, בלי ריסון).AssertionError: a damping factor must be below 1 (or equal, for none). |
AssertionError | כוח שמחושב עם r ולא r², והמסלול מתפרק.A force computed with r instead of r², so the orbit falls apart. | 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. |
AssertionError | משנים וקטור משותף בטעות.Accidentally changing a shared vector. | 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. |