Flappy: ציפור מעופפתFlappy
Sprite sheet, אנימציית פריימים, Parallax ו-dt.
Sprite sheets, frame animation, parallax and dt.
01כבידה וקפיצהGravity and jumping
עד עכשיו המהירות הייתה קבועה. ב-Flappy המהירות האנכית משתנה: כבידה מוסיפה קבוע קטן בכל פריים, כך שהציפור נופלת מהר יותר ויותר. לחיצה נותנת דחיפה: קובעים את המהירות לערך שלילי (למעלה). התוצאה היא קשת טבעית. הגרף מראה את הגובה לאורך הזמן עם שלוש לחיצות:
So far speed was constant. In Flappy the vertical velocity changes: gravity adds a small constant every frame, so the bird falls faster and faster. A press gives an impulse: set the velocity to a negative value (upward). The result is a natural arc. The chart shows the height over time with three presses:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
GRAVITY, FLAP = 0.35, -6.0
y, vel, heights = 160.0, 0.0, []
for frame in range(120):
if frame in (10, 45, 80):
vel = FLAP
vel += GRAVITY
y += vel
heights.append(y)
fig, ax = plt.subplots(figsize=(6, 2.6))
ax.plot(heights, color="#f08c00")
ax.invert_yaxis()
ax.set_xlabel("frame")
ax.set_ylabel("y (down is bigger)")
fig.savefig("arc.png", dpi=80, bbox_inches="tight")
print("lowest y:", round(max(heights)), "highest y:", round(min(heights)))lowest y: 247 highest y: 131
כבידה היא כמו מדרון בלתי נראה: כל רגע המהירות כלפי מטה גדלה קצת. קפיצה היא בעיטה כלפי מעלה, והמדרון מיד מתחיל להאט אותה.
Gravity is like an invisible slope: every moment the downward speed grows a little. A jump is a kick upward, and the slope immediately starts slowing it.
מוסיפים את הכבידה למיקום במקום למהירות.
Adding gravity to the position instead of the velocity.
y, GRAVITY = 0.0, 0.5
steps = []
for _ in range(3):
y += GRAVITY
steps.append(y)
gaps = [b - a for a, b in zip([0.0] + steps, steps)]
assert gaps[0] < gaps[-1], f"falls {gaps}: the same amount every frame, so it never speeds up; add gravity to vel, then vel to y"Traceback (most recent call last):
File "/Users/you/python-course/gravity.py", line 7, in <module>
assert gaps[0] < gaps[-1], f"falls {gaps}: the same amount every frame, so it never speeds up; add gravity to vel, then vel to y"
^^^^^^^^^^^^^^^^^^
AssertionError: falls [0.5, 0.5, 0.5]: the same amount every frame, so it never speeds up; add gravity to vel, then vel to yAssertionError: falls [0.5, 0.5, 0.5]: ...: בלי מהירות אין האצה. vel += GRAVITY ואז y += vel.AssertionError: falls [0.5, 0.5, 0.5]: ...: without velocity there's no acceleration. vel += GRAVITY then y += vel.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
בכל פריים הכבידה מוסיפה למהירות, והמהירות למיקום.
Each frame gravity adds to speed, and speed to position.
y, vy = 0.0, -6.0
for frame in range(5):
vy += 1.5
y += vy
print(frame, round(y, 1), vy)0 -4.5 -4.5 1 -7.5 -3.0 2 -9.0 -1.5 3 -9.0 0.0 4 -7.5 1.5
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02צינורותPipes
כל צינור הוא בעצם שני מלבנים עם רווח ביניהם. מספיק לשמור את המיקום האופקי ואת מרכז הרווח, ולחשב את שני המלבנים בזמן הציור. זו גלילה: הציפור נשארת באותו x, והעולם זז שמאלה. מרכז הרווח אקראי, אבל בגבולות שמשאירים אותו בתוך המסך:
Every pipe is really two rectangles with a gap between them. It's enough to store the horizontal position and the gap's centre, and compute both rectangles when drawing. That's scrolling: the bird stays at the same x, and the world moves left. The gap centre is random, but within bounds that keep it on screen:
import random
import pygame
H, GAP = 320, 110
random.seed(2)
def pipe_rects(x, gap_y, width=40):
top = pygame.Rect(x, 0, width, gap_y - GAP // 2)
bottom = pygame.Rect(x, gap_y + GAP // 2, width, H - (gap_y + GAP // 2))
return top, bottom
for _ in range(3):
gap_y = random.randint(70, H - 70)
top, bottom = pipe_rects(300, gap_y)
print(gap_y, "top ends", top.bottom, "bottom starts", bottom.top, "gap", bottom.top - top.bottom)84 top ends 29 bottom starts 139 gap 110 93 top ends 38 bottom starts 148 gap 110 91 top ends 36 bottom starts 146 gap 110
צינורות הם כמו שערים במסלול סקי: לא מזיזים את הגולש, מזיזים את ההר מתחתיו.
Pipes are like gates on a ski slope: you don't move the skier, you move the mountain under them.
רווח אקראי שיוצא חלקית מהמסך.
A random gap partly off screen.
import random
random.seed(1)
H, GAP = 320, 110
gaps = [random.randint(0, H) for _ in range(50)]
bad = [g for g in gaps if g - GAP // 2 < 0 or g + GAP // 2 > H]
assert not bad, f"{len(bad)} of 50 gaps go off screen: pick from randint(GAP // 2 + margin, H - GAP // 2 - margin)"Traceback (most recent call last):
File "/Users/you/python-course/pipes.py", line 6, in <module>
assert not bad, f"{len(bad)} of 50 gaps go off screen: pick from randint(GAP // 2 + margin, H - GAP // 2 - margin)"
^^^^^^^
AssertionError: 19 of 50 gaps go off screen: pick from randint(GAP // 2 + margin, H - GAP // 2 - margin)AssertionError: מגבילים את טווח ההגרלה כך שהרווח כולו בתוך המסך, עם שוליים.AssertionError: limit the random range so the whole gap is on screen, with a margin.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03ניקוד והתנגשותScoring and collision
נקודה מקבלים כשצינור עבר את הציפור. אבל הבדיקה "הצינור משמאל לציפור" נכונה בכל פריים מאותו רגע, ולכן שומרים דגל scored שמונע לספור שוב. להתנגשות משתמשים בתיבת פגיעה קטנה מעט מהציור: נגיעה של פיקסל בכנף לא תסיים את המשחק, וזה מרגיש הוגן:
You get a point when a pipe has passed the bird. But the check "the pipe is left of the bird" is true every frame from that moment on, so keep a scored flag to prevent counting again. For collisions use a hitbox slightly smaller than the drawing: a one-pixel wing touch won't end the game, and that feels fair:
import pygame
BIRD_X = 90
bird_draw = pygame.Rect(0, 0, 30, 22)
bird_draw.center = (BIRD_X, 150)
hitbox = bird_draw.inflate(-8, -6)
print("drawing", bird_draw.size, "hitbox", hitbox.size)
pipe = {"x": 120.0, "scored": False}
score = 0
for frame in range(40):
pipe["x"] -= 2.5
if not pipe["scored"] and pipe["x"] + 40 < BIRD_X:
pipe["scored"] = True
score += 1
print("score after 40 frames:", score)drawing (30, 22) hitbox (22, 16) score after 40 frames: 1
הדגל scored הוא כמו חותמת על כרטיס: אחרי שהחתימו, אותו כרטיס לא נותן כניסה שנייה.
The scored flag is like a stamp on a ticket: once stamped, the same ticket doesn't get you in twice.
סופרים נקודה בכל פריים שהצינור משמאל.
Counting a point every frame the pipe is to the left.
pipe_x, BIRD_X, score = 120.0, 90, 0
for frame in range(40):
pipe_x -= 2.5
if pipe_x + 40 < BIRD_X:
score += 1
assert score == 1, f"one pipe gave {score} points: add a scored flag"Traceback (most recent call last):
File "/Users/you/python-course/score.py", line 6, in <module>
assert score == 1, f"one pipe gave {score} points: add a scored flag"
^^^^^^^^^^
AssertionError: one pipe gave 12 points: add a scored flagAssertionError: one pipe gave 12 points: add a scored flag: התנאי נשאר אמת, אז מסמנים את הצינור אחרי הנקודה הראשונה.AssertionError: one pipe gave 12 points: add a scored flag: the condition stays true, so mark the pipe after the first point.04סיבוב הציפורRotating the bird
ציפור שמסתובבת לפי הכיוון נראית חיה: עולה = אף למעלה, נופלת = אף למטה. מציירים אותה פעם אחת על Surface שקוף, ובכל פריים מסובבים עם transform.rotate בזווית שתלויה במהירות. סיבוב משנה את גודל התמונה, ולכן ממקמים לפי המרכז (get_rect(center=...)), לא לפי הפינה:
A bird that tilts with its direction looks alive: rising = beak up, falling = beak down. Draw it once on a transparent Surface, and each frame rotate with transform.rotate at an angle depending on the velocity. Rotation changes the image size, so position by the centre (get_rect(center=...)), not the corner:
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 160))
screen.fill((120, 200, 240))
bird = pygame.Surface((30, 22), pygame.SRCALPHA)
pygame.draw.ellipse(bird, (255, 210, 60), (0, 0, 30, 22))
pygame.draw.circle(bird, (30, 30, 30), (22, 8), 3)
pygame.draw.polygon(bird, (250, 120, 40), [(28, 11), (36, 13), (28, 15)])
for i, vel in enumerate([-6, -3, 0, 3, 6, 10]):
angle = max(-60, min(25, -vel * 4))
tilted = pygame.transform.rotate(bird, angle)
screen.blit(tilted, tilted.get_rect(center=(50 + i * 75, 80)))
print(vel, angle, tilted.get_size())
pygame.quit()-6 24 (36, 32) -3 12 (33, 27) 0 0 (30, 22) 3 -12 (33, 27) 6 -24 (36, 32) 10 -40 (37, 36)
סיבוב הוא כמו להטות תמונה ממוסגרת על הקיר: המסגרת שצריך כדי להכיל אותה גדלה, אז תולים לפי המרכז.
Rotation is like tilting a framed picture on the wall: the box needed to contain it gets bigger, so you hang it by the centre.
מסובבים את התמונה המסובבת שוב ושוב.
Rotating the already-rotated image again and again.
import pygame
img = pygame.Surface((30, 22))
for frame in range(20):
img = pygame.transform.rotate(img, 10)
assert img.get_width() < 100, f"after 20 frames the image is {img.get_size()}: always rotate the original"Traceback (most recent call last):
File "/Users/you/python-course/rotate.py", line 5, in <module>
assert img.get_width() < 100, f"after 20 frames the image is {img.get_size()}: always rotate the original"
^^^^^^^^^^^^^^^^^^^^^
AssertionError: after 20 frames the image is (435, 435): always rotate the originalAssertionError: after 20 frames the image is (435, 435): always rotate the original: כל סיבוב מגדיל ומטשטש. שומרים את המקור ומסובבים אותו בכל פריים לזווית המלאה.AssertionError: after 20 frames the image is (435, 435): always rotate the original: each rotation grows and blurs it. Keep the original and rotate it each frame to the full angle.05רקע בשכבותA layered background
כשאתם נוסעים ברכבת, העמודים ליד המסילה רצים והרים רחוקים כמעט עומדים. זו פרלקסה, והיא נותנת עומק למשחק דו-ממדי. כל שכבה זזה במהירות אחרת, ו-% גורם לה לחזור מהצד השני, כך שהרקע אינסופי:
On a train, the poles by the track race past while distant mountains barely move. That's parallax, and it gives a 2D game depth. Each layer moves at a different speed, and % brings it back from the other side, so the background never ends:
import pygame
pygame.init()
W, H = 480, 200
screen = pygame.display.set_mode((W, H))
layers = [((180, 210, 240), 0.2, 70, 90), ((130, 190, 140), 0.5, 45, 60), ((80, 150, 90), 1.0, 25, 40)]
offset = 0.0
for frame in range(60):
offset += 4
screen.fill((200, 230, 255))
for color, speed, height, spacing in layers:
shift = (offset * speed) % (spacing * 2)
for x in range(-spacing * 2, W + spacing * 2, spacing * 2):
pygame.draw.ellipse(screen, color, (x - shift, H - height, spacing * 3, height * 2))
print(f"layer speed {speed}: moved {offset * speed:.0f}px")
pygame.quit()layer speed 0.2: moved 48px layer speed 0.5: moved 120px layer speed 1.0: moved 240px
פרלקסה היא כמו לנסוע ולראות שהירח "נוסע" איתכם: כל מה שרחוק יותר זז פחות, והמוח מבין עומק.
Parallax is like driving and seeing the moon "follow" you: the farther something is, the less it moves, and the brain reads depth.
כל השכבות באותה מהירות, והרקע נראה שטוח.
All layers at the same speed, so the background looks flat.
speeds = [1.0, 1.0, 1.0]
assert len(set(speeds)) == len(speeds), "every layer moves at 1.0: farther layers should move slower to feel deep"Traceback (most recent call last):
File "/Users/you/python-course/parallax.py", line 2, in <module>
assert len(set(speeds)) == len(speeds), "every layer moves at 1.0: farther layers should move slower to feel deep"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: every layer moves at 1.0: farther layers should move slower to feel deepAssertionError: every layer moves at 1.0: ...: נותנים לכל שכבה מהירות אחרת, הרחוקה האיטית ביותר.AssertionError: every layer moves at 1.0: ...: give each layer its own speed, the farthest slowest.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06Flappy: המשחקFlappy: the game
המשחק כולו: ציפור עם כבידה ודחיפות, צינורות עם רווח אקראי כל 90 פריימים, ניקוד עם דגל, ציפור שמסתובבת לפי המהירות, וגבעות שזזות לאט מאחור. כאן "שחקן אוטומטי" דוחף כשהציפור מתחת לרווח הבא; במחשב שלכם רווח או לחיצת עכבר:
The whole game: a bird with gravity and flaps, pipes with a random gap every 90 frames, scoring with a flag, a bird tilting with its velocity, and hills drifting slowly behind. Here an "auto-player" flaps when the bird is below the next gap; on your computer, space or a mouse click:
import random
import pygame
W, H = 480, 320
GRAVITY, FLAP, SPEED, GAP = 0.35, -6.0, 2.5, 110
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 40)
random.seed(8)
bird_y, vel = H / 2, 0.0
pipes = []
score = 0
hills = [(x, random.randint(40, 90)) for x in range(0, W + 120, 120)]
for frame in range(420):
if frame % 90 == 0:
pipes.append({"x": W, "gap_y": random.randint(70, H - 70), "scored": False})
target = pipes[0]["gap_y"] if pipes else H / 2
if bird_y > target + 12 and vel > -1:
vel = FLAP
vel += GRAVITY
bird_y += vel
for p in pipes:
p["x"] -= SPEED
if not p["scored"] and p["x"] + 40 < 90:
p["scored"] = True
score += 1
pipes = [p for p in pipes if p["x"] > -50]
hills = [((x - SPEED * 0.3) % (W + 120), h) for x, h in hills]
screen.fill((120, 200, 240))
for x, h in hills:
pygame.draw.ellipse(screen, (110, 190, 120), (x - 80, H - h, 200, h * 2))
for p in pipes:
top = pygame.Rect(p["x"], 0, 40, p["gap_y"] - GAP // 2)
bottom = pygame.Rect(p["x"], p["gap_y"] + GAP // 2, 40, H)
for r in (top, bottom):
pygame.draw.rect(screen, (70, 170, 70), r)
pygame.draw.rect(screen, (40, 120, 40), r, 3)
bird = pygame.Surface((30, 22), pygame.SRCALPHA)
pygame.draw.ellipse(bird, (255, 210, 60), (0, 0, 30, 22))
pygame.draw.circle(bird, (30, 30, 30), (22, 8), 3)
pygame.draw.polygon(bird, (250, 120, 40), [(28, 11), (36, 13), (28, 15)])
tilted = pygame.transform.rotate(bird, max(-60, min(25, -vel * 4)))
screen.blit(tilted, tilted.get_rect(center=(90, round(bird_y))))
text = font.render(str(score), True, (255, 255, 255))
screen.blit(text, text.get_rect(center=(W // 2, 28)))
pygame.display.flip()
print("score:", score, "pipes on screen:", len(pipes))
pygame.quit()score: 3 pipes on screen: 2
Flappy מראה שמשחק ממכר לא צריך להיות מסובך: כבידה, לחיצה אחת, ומכשולים. השאר הוא כוונון של מספרים.
Flappy shows an addictive game needn't be complicated: gravity, one button, obstacles. The rest is tuning numbers.
מהירות נפילה בלי גבול, והציפור עוברת דרך צינורות.
Unlimited falling speed, so the bird passes through pipes.
vel, GRAVITY = 0.0, 0.35
for frame in range(200):
vel += GRAVITY
assert vel < 12, f"after 200 frames vel is {vel:.0f} pixels a frame: cap it, e.g. vel = min(vel, 10)"Traceback (most recent call last):
File "/Users/you/python-course/flappy.py", line 4, in <module>
assert vel < 12, f"after 200 frames vel is {vel:.0f} pixels a frame: cap it, e.g. vel = min(vel, 10)"
^^^^^^^^
AssertionError: after 200 frames vel is 70 pixels a frame: cap it, e.g. vel = min(vel, 10)AssertionError: after 200 frames vel is 70 pixels a frame: ...: מגבילים מהירות סופית (min(vel, 10)), אחרת הנפילה מהירה מדי ונוצר מנהור.AssertionError: after 200 frames vel is 70 pixels a frame: ...: cap the terminal velocity (min(vel, 10)), otherwise falling gets too fast and tunneling appears.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.