Brick Breaker: שובר לבניםBrick Breaker
מחלקות במשחק, שלבים מנתוני טקסט, power-ups ומטמון תמונות.
Classes in a game, levels from text data, power-ups and an image cache.
01שלב מתוך טקסטA level from text
במקום למקם כל לבנה ביד, מציירים את השלב כמפה של מחרוזות: כל תו הוא לבנה, ונקודה היא ריק. לולאה כפולה עם enumerate הופכת כל תו למלבן במקום הנכון. ככה מוסיפים שלב חדש בלי לגעת בקוד:
Instead of placing every brick by hand, draw the level as a map of strings: each character is a brick, and a dot is empty. A double loop with enumerate turns each character into a rectangle in the right place. That way you add a new level without touching the code:
import pygame
LEVEL = [
"RRRRRRRRRR",
"OOOO..OOOO",
"YYYYYYYYYY",
"GG.GGGG.GG",
]
COLORS = {"R": (240, 80, 90), "O": (250, 150, 60), "Y": (250, 220, 80), "G": (90, 210, 120)}
pygame.init()
screen = pygame.display.set_mode((480, 120))
screen.fill((20, 16, 34))
bricks = []
for r, row in enumerate(LEVEL):
for c, ch in enumerate(row):
if ch != ".":
rect = pygame.Rect(8 + c * 46.4, 10 + r * 18, 44, 14)
bricks.append(rect)
pygame.draw.rect(screen, COLORS[ch], rect, border_radius=3)
print(len(bricks), "bricks; first", bricks[0], "last", bricks[-1].topleft)
pygame.quit()36 bricks; first Rect(8, 10, 44, 14) last (425, 64)
מפת שלב היא כמו תווים של שיר: סדרה של סימנים פשוטים שמישהו אחר (הקוד) יודע לנגן.
A level map is like sheet music: a series of simple symbols someone else (the code) knows how to play.
שורות באורך שונה במפה.
Rows of different lengths in the map.
LEVEL = ["RRRR", "OO", "YYYY"]
widths = {len(row) for row in LEVEL}
assert len(widths) == 1, f"row lengths {sorted(widths)}: a short row shifts nothing but silently drops bricks; keep every row the same width"Traceback (most recent call last):
File "/Users/you/python-course/level.py", line 3, in <module>
assert len(widths) == 1, f"row lengths {sorted(widths)}: a short row shifts nothing but silently drops bricks; keep every row the same width"
^^^^^^^^^^^^^^^^
AssertionError: row lengths [2, 4]: a short row shifts nothing but silently drops bricks; keep every row the same widthAssertionError: row lengths [2, 4]: ...: מוסיפים נקודות לשורה הקצרה. בדיקה כזו בתחילת הטעינה חוסכת באגים מוזרים.AssertionError: row lengths [2, 4]: ...: pad the short row with dots. A check like this when loading saves odd bugs.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02מאיזה צד הייתה הפגיעה?Which side was hit?
כשהכדור פוגע בלבנה, צריך לדעת אם להפוך את vx (פגיעה מהצד) או את vy (מלמעלה או מלמטה). הטריק הפשוט: הפרדת צירים. מזיזים רק ב-x ובודקים התנגשות; אם יש, זו פגיעה מהצד. אחר כך מזיזים ב-y ובודקים שוב; אם יש, זו פגיעה מלמעלה/מלמטה:
When the ball hits a brick, you need to know whether to flip vx (a side hit) or vy (from above or below). The simple trick: axis separation. Move only along x and check collisions; if there's one, it was a side hit. Then move along y and check again; if there's one, it was a top/bottom hit:
import pygame
def move_ball(ball, vx, vy, bricks):
ball.x += vx
i = ball.collidelist(bricks)
if i >= 0:
bricks.pop(i)
vx = -vx
ball.x += vx
ball.y += vy
i = ball.collidelist(bricks)
if i >= 0:
bricks.pop(i)
vy = -vy
ball.y += vy
return vx, vy
from_below = [pygame.Rect(100, 50, 40, 14)]
print("from below:", move_ball(pygame.Rect(110, 66, 10, 10), 0, -4, from_below), len(from_below))
from_side = [pygame.Rect(100, 50, 40, 14)]
print("from the side:", move_ball(pygame.Rect(88, 52, 10, 10), 4, 0, from_side), len(from_side))from below: (0, 4) 0 from the side: (-4, 0) 0
הפרדת צירים היא כמו לבדוק דלת בשני שלבים: קודם דוחפים ימינה ורואים אם נתקעים, אחר כך דוחפים קדימה. כך יודעים בדיוק איפה המכשול.
Axis separation is like testing a door in two steps: push right and see if you're blocked, then push forward. That's how you know exactly where the obstacle is.
הופכים את שני הכיוונים בכל פגיעה.
Flipping both directions on every hit.
vx, vy = 3, -4
hit_from_below = True
if hit_from_below:
vx, vy = -vx, -vy
assert vx == 3, f"vx became {vx}: a hit from below should only flip vy, or the ball flies back the way it came"Traceback (most recent call last):
File "/Users/you/python-course/sides.py", line 5, in <module>
assert vx == 3, f"vx became {vx}: a hit from below should only flip vy, or the ball flies back the way it came"
^^^^^^^
AssertionError: vx became -3: a hit from below should only flip vy, or the ball flies back the way it cameAssertionError: vx became -3: ...: הכדור חוזר בדיוק במסלול שבא, וזה נראה לא טבעי. הופכים רק את הציר שבו הייתה הפגיעה.AssertionError: vx became -3: ...: the ball goes straight back the way it came, which looks unnatural. Flip only the axis that was hit.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03מהירות ומנהורSpeed and tunneling
אם הכדור זז 20 פיקסלים בפריים ולבנה עבה 14 פיקסלים, הוא יכול להיות לפני הלבנה בפריים אחד ואחריה בפריים הבא, בלי לגעת בה אף פעם: מנהור. פתרון פשוט: מחלקים את התנועה לכמה צעדים קטנים בכל פריים, ובודקים התנגשות אחרי כל אחד:
If the ball moves 20 pixels a frame and a brick is 14 pixels thick, it can be in front of the brick on one frame and past it on the next, never touching it: tunneling. A simple fix: split the motion into several small steps each frame, checking for collisions after each:
import pygame
brick = pygame.Rect(100, 50, 40, 14)
def crosses(y, vy, steps):
ball = pygame.Rect(110, y, 10, 10)
for _ in range(steps):
ball.y += vy // steps
if ball.colliderect(brick):
return True
return False
print("one big step:", crosses(72, -42, 1), " three small steps:", crosses(72, -42, 3))one big step: False three small steps: True
מנהור הוא כמו לצלם רץ מהיר פעם בשנייה: בתמונה אחת הוא לפני המכשול ובבאה אחריו, ונראה שקפץ דרכו.
Tunneling is like photographing a sprinter once a second: in one shot they're before the hurdle and in the next past it, as if they went through it.
מגבירים מהירות בלי לחשוב על עובי הלבנים.
Raising the speed without thinking about brick thickness.
speed, brick_h, ball_h = 30, 14, 10
assert speed <= brick_h + ball_h, f"speed {speed} > {brick_h + ball_h}: the ball can pass a brick between frames; use sub-steps or cap the speed"Traceback (most recent call last):
File "/Users/you/python-course/tunnel.py", line 2, in <module>
assert speed <= brick_h + ball_h, f"speed {speed} > {brick_h + ball_h}: the ball can pass a brick between frames; use sub-steps or cap the speed"
^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: speed 30 > 24: the ball can pass a brick between frames; use sub-steps or cap the speedAssertionError: speed 30 > 24: ...: מגבילים מהירות, או מחלקים לצעדים כמו בדוגמה.AssertionError: speed 30 > 24: ...: cap the speed, or split into sub-steps as in the example.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04חיזוקיםPower-ups
חיזוקים מוסיפים עניין: כשלבנה נשברת, בהסתברות קטנה נופל פריט. אם המחבט תופס אותו, מקבלים אפקט, למשל מחבט רחב, ל-300 פריימים. את הזמן סופרים במונה שיורד בכל פריים, וכשמגיע לאפס מחזירים את הרוחב:
Power-ups add interest: when a brick breaks, there's a small chance an item drops. If the paddle catches it, you get an effect, say a wide paddle, for 300 frames. Count the time with a counter that goes down each frame, and when it reaches zero, restore the width:
import random
random.seed(6)
wide_timer = 0
paddle_w = 80
drops = 0
for frame in range(600):
if frame % 40 == 0 and random.random() < 0.3:
drops += 1
wide_timer = 300
if wide_timer > 0:
wide_timer -= 1
paddle_w = 130
else:
paddle_w = 80
if frame in (0, 100, 599):
print(f"frame {frame}: width {paddle_w}, timer {wide_timer}")
print("power-ups caught:", drops)frame 0: width 80, timer 0 frame 100: width 80, timer 0 frame 599: width 130, timer 100 power-ups caught: 3
חיזוק זמני הוא כמו כרטיס "פי שניים נקודות לשעה" בפארק שעשועים: יש שעון, וכשהוא נגמר הכול חוזר לרגיל.
A temporary power-up is like a "double points for an hour" pass at a fun fair: there's a clock, and when it runs out everything goes back to normal.
מגדילים את הרוחב בכל איסוף, בלי גבול.
Widening on every pickup, without limit.
paddle_w = 80
for pickup in range(8):
paddle_w += 50
assert paddle_w <= 200, f"paddle is {paddle_w}px wide on a 480px screen: set the width, don't keep adding"Traceback (most recent call last):
File "/Users/you/python-course/powerups.py", line 4, in <module>
assert paddle_w <= 200, f"paddle is {paddle_w}px wide on a 480px screen: set the width, don't keep adding"
^^^^^^^^^^^^^^^
AssertionError: paddle is 480px wide on a 480px screen: set the width, don't keep addingAssertionError: paddle is 480px wide ...: קובעים רוחב (paddle_w = 130) ומאפסים את הטיימר, במקום להוסיף שוב ושוב.AssertionError: paddle is 480px wide ...: set the width (paddle_w = 130) and reset the timer, instead of adding again and again.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05חיים ושלביםLives and levels
המשחק צריך התקדמות: כשהכדור נופל מתחת למחבט מאבדים חיים ומגישים מחדש; כשכל הלבנים נשברו, טוענים את המפה הבאה מרשימת השלבים. אם נגמרו השלבים, ניצחון. כל זה הוא מכונת מצבים קטנה:
The game needs progress: when the ball falls below the paddle you lose a life and re-serve; when every brick is broken, load the next map from the list of levels. If the levels run out, victory. It's all a small state machine:
LEVELS = [["RR", ".."], ["RRR", "OOO"], ["Y.Y"]]
level, lives, state = 0, 3, "playing"
bricks = sum(row.count("R") + row.count("O") + row.count("Y") for row in LEVELS[level])
for event in ["break", "break", "fall", "break"] + ["break"] * 6 + ["break", "break"]:
if state != "playing":
break
if event == "fall":
lives -= 1
state = "over" if lives == 0 else state
else:
bricks -= 1
if bricks == 0:
level += 1
if level == len(LEVELS):
state = "won"
else:
bricks = sum(sum(ch != "." for ch in row) for row in LEVELS[level])
print("level", level + 1, "with", bricks, "bricks")
print(state, "lives", lives)level 2 with 6 bricks level 3 with 2 bricks won lives 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
שלבים הם כמו פרקים בספר: כשמסיימים אחד, מדפדפים לבא, ובסוף הספר מגיע הסוף הטוב.
Levels are like chapters in a book: finish one, turn to the next, and at the end comes the happy ending.
עוברים שלב בלי לטעון את הלבנים החדשות.
Advancing a level without loading the new bricks.
LEVELS = [["RR"], ["OOO"]]
level, bricks = 0, []
level += 1
assert bricks, f"level {level + 1} started with {len(bricks)} bricks: build them from LEVELS[level]"Traceback (most recent call last):
File "/Users/you/python-course/levels.py", line 4, in <module>
assert bricks, f"level {level + 1} started with {len(bricks)} bricks: build them from LEVELS[level]"
^^^^^^
AssertionError: level 2 started with 0 bricks: build them from LEVELS[level]AssertionError: level 2 started with 0 bricks: ...: אחרי level += 1 בונים מחדש את רשימת הלבנים מהמפה החדשה.AssertionError: level 2 started with 0 bricks: ...: after level += 1 rebuild the brick list from the new map.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
כל פספוס מוריד חיים. באפס, המשחק נגמר.
Every miss costs a life. At zero, the game is over.
lives = 3
for missed in [False, True, True, False, True]:
if missed:
lives -= 1
if lives == 0:
print("GAME OVER")
break
print("lives:", lives)lives: 3 lives: 2 lives: 1 lives: 1 GAME OVER
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06Brick Breaker: המשחקBrick Breaker: the game
הכול יחד: שלב שנבנה מהמפה, כדור שמשתמש בהפרדת צירים מול הלבנים, זווית לפי נקודת הפגיעה במחבט (כמו ב-Pong), וניקוד. כאן המחבט עוקב אחרי הכדור לבד; במחשב שלכם העכבר או החיצים מזיזים אותו:
All together: a level built from the map, a ball using axis separation against bricks, an angle by where it hits the paddle (as in Pong), and score. Here the paddle follows the ball by itself; on your computer the mouse or arrows move it:
import pygame
W, H = 480, 320
LEVEL = [
"RRRRRRRRRR",
"OOOO..OOOO",
"YYYYYYYYYY",
"GG.GGGG.GG",
]
COLORS = {"R": (240, 80, 90), "O": (250, 150, 60), "Y": (250, 220, 80), "G": (90, 210, 120)}
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 26)
bricks = [(pygame.Rect(8 + c * 46.4, 30 + r * 18, 44, 14), COLORS[ch]) for r, row in enumerate(LEVEL) for c, ch in enumerate(row) if ch != "."]
paddle = pygame.Rect(W // 2 - 40, H - 22, 80, 10)
ball = pygame.Rect(W // 2 - 5, H - 60, 10, 10)
bx, by, vx, vy = float(ball.x), float(ball.y), 3.0, -4.0
score = 0
for frame in range(500):
paddle.centerx = max(40, min(W - 40, round(bx) + 5))
bx += vx
ball.x = round(bx)
hit = ball.collidelist([b for b, _ in bricks])
if hit >= 0:
bricks.pop(hit)
vx, score = -vx, score + 10
by += vy
ball.y = round(by)
hit = ball.collidelist([b for b, _ in bricks])
if hit >= 0:
bricks.pop(hit)
vy, score = -vy, score + 10
if ball.left <= 0 or ball.right >= W:
vx = -vx
if ball.top <= 0:
vy = abs(vy)
if ball.colliderect(paddle) and vy > 0:
vx, vy = (ball.centerx - paddle.centerx) / 40 * 5, -abs(vy)
screen.fill((20, 16, 34))
for b, color in bricks:
pygame.draw.rect(screen, color, b, border_radius=3)
pygame.draw.rect(screen, (220, 220, 255), paddle, border_radius=5)
pygame.draw.ellipse(screen, (255, 255, 255), ball)
screen.blit(font.render(f"Score {score}", True, (230, 230, 255)), (8, 6))
pygame.display.flip()
print("bricks left:", len(bricks), "score:", score)
pygame.quit()bricks left: 30 score: 60
Brick Breaker משלב את כל מה שבנינו: Rect, התנגשויות, זווית, מצבים. כמו מתכון שמשתמש בכל הכלים במטבח.
Brick Breaker combines everything we've built: Rects, collisions, angles, states. Like a recipe that uses every tool in the kitchen.
שוברים כמה לבנים בפגיעה אחת ומהפכים את הכיוון כמה פעמים.
Breaking several bricks in one hit and flipping the direction several times.
vy, hits = -4, [0, 1]
for i in hits:
vy = -vy
assert vy > 0, f"two bricks hit in the same frame flipped vy twice, back to {vy}: flip once per axis per frame"Traceback (most recent call last):
File "/Users/you/python-course/brick_breaker.py", line 4, in <module>
assert vy > 0, f"two bricks hit in the same frame flipped vy twice, back to {vy}: flip once per axis per frame"
^^^^^^
AssertionError: two bricks hit in the same frame flipped vy twice, back to -4: flip once per axis per frameAssertionError: two bricks hit in the same frame flipped vy twice, back to -4: ...: גם אם נשברו שתי לבנים, הופכים את הציר פעם אחת בלבד.AssertionError: two bricks hit in the same frame flipped vy twice, back to -4: ...: even if two bricks broke, flip the axis only once.צפו איפה זה נשבר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.