ברוכים הבאים ל-Pygame: בועות קופצותWelcome to Pygame: Bubble Bounce
התקנת pygame-ce, לולאת המשחק, ציור, תנועה, כבידה ואירועי עכבר.
Installing pygame-ce, the game loop, drawing, movement, gravity and mouse events.
01חלון ראשוןA first window
ברוכים הבאים לחלק המשחקים! pygame פותח חלון, ומאפשר לצייר בו ולהגיב למקלדת ולעכבר. מתקינים את pygame-ce, הגרסה המתוחזקת (מייבאים אותה בשם pygame). צבעים כותבים כשלשה של אדום, ירוק וכחול, כל אחד מ-0 עד 255. באתר הלולאה רצה מספר קבוע של פריימים ואז נעצרת, והתמונה מתחת לקוד היא הפריים האחרון. על המחשב שלכם נפתח חלון אמיתי שרץ עד שסוגרים אותו.
Welcome to the games part! pygame opens a window and lets you draw in it and react to the keyboard and mouse. Install pygame-ce, the maintained version (you import it as pygame). Colours are a triple of red, green and blue, each 0 to 255. On this site the loop runs a fixed number of frames and then stops, and the picture under the code is the last frame. On your computer a real window opens and runs until you close it.
pip install pygame-ce
python3 -c "import pygame; print(pygame.version.ver)"pygame-ce 2.5.8 (SDL 2.32.10, Python 3.12.7) 2.5.8
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
pygame.display.set_caption("Bubble Bounce")
screen.fill((18, 24, 48))
pygame.draw.circle(screen, (90, 180, 255), (240, 160), 50)
pygame.display.flip()
print(screen.get_size())
pygame.quit()(480, 320)
החלון הוא כמו לוח ציור, ו-flip() הוא הרגע שבו מסובבים את הלוח לקהל: כל מה שציירתם מופיע בבת אחת.
The window is like an easel, and flip() is the moment you turn the canvas to the audience: everything you drew appears at once.
צבע עם ערך מעל 255.
A colour value above 255.
import pygame
pygame.init()
screen = pygame.display.set_mode((100, 100))
screen.fill((300, 0, 0))Traceback (most recent call last):
File "/Users/you/python-course/window.py", line 4, in <module>
screen.fill((300, 0, 0))
~~~~~~~~~~~^^^^^^^^^^^^^
ValueError: invalid color (color sequence must have size 3 or 4, and each element must be an integer in the range [0, 255])ValueError: invalid color (color sequence must have size 3 or 4, and each element must be an integer in the range [0, 255]): כל רכיב צבע הוא מ-0 עד 255.ValueError: invalid color (color sequence must have size 3 or 4, and each element must be an integer in the range [0, 255]): each colour component is 0 to 255.02לולאת המשחקThe game loop
כל משחק בנוי על לולאת משחק שרצה שוב ושוב: (1) קוראים אירועים (האם המשתמש סגר את החלון? לחץ?), (2) מעדכנים מיקומים וניקוד, (3) מוחקים את המסך ומציירים מחדש. כל סיבוב הוא פריים, ו-clock.tick(60) דואג שלא יהיו יותר מ-60 בשנייה. במחשב שלכם זה while running:; כאן נריץ 90 פריימים:
Every game is built on a game loop running again and again: (1) read events (did the user close the window? click?), (2) update positions and score, (3) clear the screen and redraw. Each pass is a frame, and clock.tick(60) keeps it to at most 60 a second. On your computer it's while running:; here we run 90 frames:
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
clock = pygame.time.Clock()
x = 40
running = True
frames = 0
while running and frames < 90:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
x += 4
screen.fill((18, 24, 48))
pygame.draw.circle(screen, (255, 200, 60), (x, 160), 24)
pygame.display.flip()
clock.tick(60)
frames += 1
print("frames:", frames, "x:", x)
pygame.quit()frames: 90 x: 400
לולאת משחק היא כמו ספר דפדוף: כל דף הוא פריים, וכשמדפדפים מהר העין רואה תנועה.
A game loop is like a flip book: each page is a frame, and flipping fast makes the eye see motion.
שוכחים למלא את המסך מחדש, וכל עיגול משאיר שובל.
Forgetting to clear the screen, so every circle leaves a trail.
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 100))
screen.fill((0, 0, 0))
for x in range(20, 180, 20):
pygame.draw.circle(screen, (255, 255, 255), (x, 50), 8)
circles = sum(1 for x in range(0, 200, 20) if screen.get_at((x, 50))[0] > 200)
assert circles <= 1, f"{circles} circles on screen: fill the background at the start of every frame"Traceback (most recent call last):
File "/Users/you/python-course/loop.py", line 8, in <module>
assert circles <= 1, f"{circles} circles on screen: fill the background at the start of every frame"
^^^^^^^^^^^^
AssertionError: 8 circles on screen: fill the background at the start of every frameAssertionError: 8 circles on screen: ...: בלי screen.fill בתחילת כל פריים, הציורים הקודמים נשארים. ממלאים רקע ואז מציירים.AssertionError: 8 circles on screen: ...: without screen.fill at the start of each frame, earlier drawings stay. Fill the background, then draw.03קואורדינטות וצורותCoordinates and shapes
בקואורדינטות של מסך הראשית בפינה השמאלית העליונה, ו-y גדל כלפי מטה, הפוך מהמתמטיקה בבית הספר. pygame.Rect(x, y, w, h) הוא מלבן שיודע את הקצוות שלו (left, right, top, bottom, center), ונשתמש בו הרבה.
In screen coordinates the origin is the top-left corner, and y grows down, the opposite of school maths. pygame.Rect(x, y, w, h) is a rectangle that knows its edges (left, right, top, bottom, center), and we'll use it a lot.
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
screen.fill((245, 240, 230))
ground = pygame.Rect(0, 270, 480, 50)
pygame.draw.rect(screen, (60, 160, 90), ground)
pygame.draw.rect(screen, (200, 70, 60), pygame.Rect(60, 190, 80, 80), border_radius=8)
pygame.draw.polygon(screen, (120, 80, 200), [(260, 270), (320, 160), (380, 270)])
pygame.draw.line(screen, (30, 30, 30), (0, 0), (480, 320), 3)
pygame.draw.circle(screen, (255, 190, 40), (420, 60), 30)
print(ground.top, ground.bottom, ground.center)
pygame.quit()270 320 (240, 295)
מסך מחשב הוא כמו דף במחברת: מתחילים לכתוב בפינה העליונה, ושורה חדשה היא למטה, לא למעלה.
A computer screen is like a notebook page: you start writing at the top corner, and a new line is lower down, not higher up.
חושבים ש-y גדל כלפי מעלה.
Thinking y grows upward.
sky_y, ground_y = 300, 20
assert sky_y < ground_y, "the sky was drawn at y=300 and the ground at y=20: in pygame bigger y is lower on screen"Traceback (most recent call last):
File "/Users/you/python-course/shapes.py", line 2, in <module>
assert sky_y < ground_y, "the sky was drawn at y=300 and the ground at y=20: in pygame bigger y is lower on screen"
^^^^^^^^^^^^^^^^
AssertionError: the sky was drawn at y=300 and the ground at y=20: in pygame bigger y is lower on screenAssertionError: the sky was drawn at y=300 ...: ב-pygame y גדול = נמוך יותר במסך. הקרקע בערכי y גבוהים.AssertionError: the sky was drawn at y=300 ...: in pygame a bigger y is lower on screen. The ground has high y values.ב-pygame ה-y גדל כלפי מטה. בודקים מה בתוך החלון.
In pygame, y grows downward. Check what's inside the window.
W, H = 320, 200
for x, y in [(10, 10), (330, 50), (100, 250)]:
inside = 0 <= x < W and 0 <= y < H
print((x, y), "inside" if inside else "outside")(10, 10) inside (330, 50) outside (100, 250) outside
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04תנועה ומהירותMotion and velocity
תנועה היא חיבור של מהירות למיקום בכל פריים: x += vx, y += vy. מהירות של 3 ב-60 פריימים בשנייה היא 180 פיקסלים בשנייה. בדוגמה מציירים את המסלול של בועה כדי לראות את התנועה בתמונה אחת:
Motion is adding velocity to position every frame: x += vx, y += vy. A velocity of 3 at 60 frames a second is 180 pixels a second. In the example we draw a bubble's path so you can see the motion in one picture:
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
screen.fill((18, 24, 48))
x, y, vx, vy = 30, 280, 5, -3
for frame in range(80):
x += vx
y += vy
if frame % 8 == 0:
pygame.draw.circle(screen, (90, 180, 255), (x, y), 6)
pygame.draw.circle(screen, (255, 255, 255), (x, y), 14)
print(f"after 80 frames: x={x}, y={y}")
pygame.quit()after 80 frames: x=430, y=40
מהירות היא כמו הוראה לצב: "כל צעד, 5 משבצות ימינה ו-3 למעלה". אחרי 10 צעדים יודעים בדיוק איפה הוא.
Velocity is like an instruction to a robot turtle: "each step, 5 squares right and 3 up". After 10 steps you know exactly where it is.
משנים מיקום למספר עשרוני ומעבירים ישר לציור.
Turning a position into a float and passing it straight to drawing.
x = 10
for _ in range(3):
x += 0.4
assert isinstance(x, int), f"x is {x!r}: keep the exact float for motion and use round(x) only when drawing"Traceback (most recent call last):
File "/Users/you/python-course/move.py", line 4, in <module>
assert isinstance(x, int), f"x is {x!r}: keep the exact float for motion and use round(x) only when drawing"
~~~~~~~~~~^^^^^^^^
AssertionError: x is 11.200000000000001: keep the exact float for motion and use round(x) only when drawingAssertionError: x is 11.2...: מחזיקים מיקום עשרוני לתנועה חלקה, ומעגלים (round) רק בשורת הציור.AssertionError: x is 11.2...: keep a float position for smooth motion, and round (round) only on the drawing line.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05להקפיץ מהקירותBouncing off the walls
כשבועה נוגעת בקיר, הופכים את המהירות באותו ציר: vx = -vx. בודקים את הקצה של העיגול (x + r מול רוחב החלון), לא את המרכז. טריק חשוב: מחזירים את הבועה פנימה לגבול, אחרת היא עלולה להיתקע בתוך הקיר ולרטוט. הנה הפונקציה, שאפשר לבדוק בלי חלון בכלל:
When a bubble touches a wall, flip the velocity on that axis: vx = -vx. Check the circle's edge (x + r against the window width), not its centre. An important trick: push the bubble back to the boundary, otherwise it can get stuck in the wall and jitter. Here's the function, testable without any window:
def bounce(pos, vel, r, size):
pos += vel
if pos - r < 0:
pos, vel = r, -vel
elif pos + r > size:
pos, vel = size - r, -vel
return pos, vel
x, vx = 440, 15
for _ in range(6):
x, vx = bounce(x, vx, 20, 480)
print(x, vx)455 15 460 -15 445 -15 430 -15 415 -15 400 -15
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
להקפיץ זה כמו כדור שולחן: הוא פוגע בדופן, והכיוון מתהפך, אבל המהירות נשארת אותה מהירות.
Bouncing is like a pool ball: it hits the cushion and the direction flips, but the speed stays the same.
בודקים את המרכז במקום את הקצה, והבועה נכנסת חצי לתוך הקיר.
Checking the centre instead of the edge, so the bubble sinks halfway into the wall.
x, r, width = 470, 20, 480
hits_wall = x > width
assert hits_wall, f"centre at x={x} says no wall, but the edge is at {x + r}: check x + r > width"Traceback (most recent call last):
File "/Users/you/python-course/bounce.py", line 3, in <module>
assert hits_wall, f"centre at x={x} says no wall, but the edge is at {x + r}: check x + r > width"
^^^^^^^^^
AssertionError: centre at x=470 says no wall, but the edge is at 490: check x + r > widthAssertionError: centre at x=470 says no wall, but the edge is at 490: ...: הבועה כבר חצתה את הקיר. בודקים x + r > width.AssertionError: centre at x=470 says no wall, but the edge is at 490: ...: the bubble already crossed the wall. Check x + r > width.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06Bubble Bounce: המשחקBubble Bounce: the game
מחברים הכול למשחק: מחלקה Bubble (מפגש 15) שיודעת לזוז, לצייר את עצמה ולבדוק אם נקודה בתוכה (מרחק מהמרכז קטן מהרדיוס). רשימה של 12 בועות, ובכל לחיצת עכבר מוחקים את הבועה שנלחצה ומוסיפים נקודה. כאן מדמים שלוש לחיצות:
Put it all together into a game: a Bubble class (session 15) that can move, draw itself and check whether a point is inside it (distance from the centre less than the radius). A list of 12 bubbles, and every mouse click removes the clicked bubble and adds a point. Here we simulate three clicks:
import random
import pygame
class Bubble:
def __init__(self, x, y, r, vx, vy, color):
self.x, self.y, self.r = x, y, r
self.vx, self.vy = vx, vy
self.color = color
def update(self, w, h):
self.x += self.vx
self.y += self.vy
if self.x - self.r < 0 or self.x + self.r > w:
self.vx = -self.vx
if self.y - self.r < 0 or self.y + self.r > h:
self.vy = -self.vy
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.r)
pygame.draw.circle(screen, (255, 255, 255), (int(self.x - self.r / 3), int(self.y - self.r / 3)), max(2, self.r // 5))
def hit(self, px, py):
return (px - self.x) ** 2 + (py - self.y) ** 2 <= self.r ** 2
pygame.init()
W, H = 480, 320
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 30)
random.seed(7)
colors = [(90, 180, 255), (255, 120, 160), (120, 220, 150), (255, 200, 60)]
bubbles = [Bubble(random.randint(40, W - 40), random.randint(40, H - 40), random.randint(14, 30),
random.choice([-3, -2, 2, 3]), random.choice([-3, -2, 2, 3]), random.choice(colors)) for _ in range(12)]
score = 0
for frame in range(120):
if frame in (30, 60, 90):
target = bubbles[0]
click = pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=(int(target.x), int(target.y)), button=1)
pygame.event.post(click)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for b in bubbles:
if b.hit(*event.pos):
bubbles.remove(b)
score += 1
break
for b in bubbles:
b.update(W, H)
screen.fill((18, 24, 48))
for b in bubbles:
b.draw(screen)
screen.blit(font.render(f"Popped: {score}", True, (255, 255, 255)), (12, 10))
pygame.display.flip()
print("bubbles left:", len(bubbles), "score:", score)
pygame.quit()bubbles left: 9 score: 3
כל בועה היא כמו שחקן שמכיר את התפקיד שלו: המשחק רק אומר לכולם "זוזו" ו"ציירו את עצמכם", וכל אחד יודע איך.
Each bubble is like an actor who knows its part: the game just tells everyone "move" and "draw yourselves", and each knows how.
מוחקים מרשימה בזמן שעוברים עליה בלולאה.
Removing from a list while looping over it.
bubbles = [1, 2, 3, 4]
for b in bubbles:
bubbles.remove(b)
assert bubbles == [], f"left {bubbles}: removing while looping skips items"Traceback (most recent call last):
File "/Users/you/python-course/bubble_bounce.py", line 4, in <module>
assert bubbles == [], f"left {bubbles}: removing while looping skips items"
^^^^^^^^^^^^^
AssertionError: left [2, 4]: removing while looping skips itemsAssertionError: left [2, 4]: removing while looping skips items: אחרי מחיקה הרשימה מתקצרת והלולאה מדלגת. לפוצץ אחת: break מיד אחרי remove (כמו בקוד), או לבנות רשימה חדשה.AssertionError: left [2, 4]: removing while looping skips items: after removing, the list shrinks and the loop skips one. To pop one: break right after remove (as in the code), or build a new list.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.