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

PythonPython
37
חלקPart 7: משחקים עם PygameGames with Pygame כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

ברוכים הבאים ל-Pygame: בועות קופצותWelcome to Pygame: Bubble Bounce

התקנת pygame-ce, לולאת המשחק, ציור, תנועה, כבידה ואירועי עכבר.

Installing pygame-ce, the game loop, drawing, movement, gravity and mouse events.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

צבעיםColours

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

כתבו mix(c1, c2) שמחזירה את הצבע שבאמצע בין שני צבעי RGB (ממוצע כל רכיב, מעוגל למטה), ו-darker(c, amount) שמורידה amount מכל רכיב בלי לרדת מתחת ל-0.

Write mix(c1, c2) returning the RGB colour halfway between two colours (each component averaged, rounded down), and darker(c, amount) subtracting amount from each component without going below 0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 mix(c1, c2):
    return tuple((a + b) // 2 for a, b in zip(c1, c2))

def darker(c, amount):
    return tuple(max(0, v - amount) for v in c)

print(mix((255, 0, 0), (0, 0, 255)), darker((90, 180, 255), 100))
פלטOutput
(127, 0, 127) (0, 80, 155)

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

תרגילExercise 2

הקפצהBouncing

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

כתבו bounce(pos, vel, r, size) שמזיזה בציר אחד ומחזירה (pos, vel) חדשים: אם הקצה עבר את 0 או את size, הבועה מוחזרת לגבול והמהירות מתהפכת.

Write bounce(pos, vel, r, size) that moves along one axis and returns the new (pos, vel): if the edge passed 0 or size, the bubble is put back on the boundary and the velocity flips.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 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

print(bounce(470, 15, 20, 480), bounce(25, -10, 20, 480), bounce(200, 4, 20, 480))
פלטOutput
(460, -15) (20, 10) (204, 4)

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

תרגילExercise 3

לחיצה על בועהClicking a bubble

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

כתבו hit(bubble, point) שמחזירה True אם נקודת הלחיצה בתוך העיגול (מרחק מהמרכז ≤ רדיוס), ו-pop_at(bubbles, point) שמוחקת את הבועה העליונה (האחרונה ברשימה, כי היא צוירה אחרונה) שנלחצה ומחזירה True, או False אם לא נלחצה אף אחת. בועה היא מילון עם x, y, r.

Write hit(bubble, point) returning True if the click is inside the circle (distance from the centre ≤ radius), and pop_at(bubbles, point) removing the topmost clicked bubble (the last in the list, since it was drawn last) and returning True, or False if none was clicked. A bubble is a dict with x, y, r.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 hit(bubble, point):
    dx, dy = point[0] - bubble["x"], point[1] - bubble["y"]
    return dx * dx + dy * dy <= bubble["r"] ** 2

def pop_at(bubbles, point):
    for i in range(len(bubbles) - 1, -1, -1):
        if hit(bubbles[i], point):
            del bubbles[i]
            return True
    return False

bubbles = [{"x": 100, "y": 100, "r": 30}, {"x": 120, "y": 100, "r": 20}]
print(pop_at(bubbles, (115, 105)), bubbles, pop_at(bubbles, (300, 300)))
פלטOutput
True [{'x': 100, 'y': 100, 'r': 30}] False

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

תרגילExercise 4

פריים בחלוןA frame in a window

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

בעזרת pygame: צרו חלון 200×120, מלאו בצבע (18, 24, 48), ציירו עיגול (255, 200, 60) ברדיוס 20 במרכז, והדפיסו את צבע הפיקסל במרכז ובפינה (screen.get_at, רק שלושת הרכיבים הראשונים).

With pygame: create a 200×120 window, fill it with (18, 24, 48), draw a (255, 200, 60) circle of radius 20 in the centre, and print the pixel colour at the centre and at the corner (screen.get_at, first three components only).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 pygame

pygame.init()
screen = pygame.display.set_mode((200, 120))
screen.fill((18, 24, 48))
pygame.draw.circle(screen, (255, 200, 60), (100, 60), 20)
print(tuple(screen.get_at((100, 60))[:3]), tuple(screen.get_at((0, 0))[:3]))
pygame.quit()
פלטOutput
(255, 200, 60) (18, 24, 48)
screen.png
screen.png

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

תרגילExercise 5

Bubble Bounce: מחלקת בועהBubble Bounce: a bubble class

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

כתבו מחלקה Bubble(x, y, r, vx, vy) עם update(w, h) (תנועה והקפצה משני הצירים, כולל החזרה לגבול) ו-hit(px, py). ואז step(bubbles, w, h, clicks) שמעדכנת את כל הבועות, מפוצצת לכל לחיצה את הבועה העליונה שנפגעה, ומחזירה כמה פוצצו.

Write a Bubble(x, y, r, vx, vy) class with update(w, h) (move and bounce on both axes, back to the boundary) and hit(px, py). Then step(bubbles, w, h, clicks) updating every bubble, popping the topmost hit bubble for each click, and returning how many popped.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
bubble_bounce.py
class Bubble:
    def __init__(self, x, y, r, vx, vy):
        self.x, self.y, self.r, self.vx, self.vy = x, y, r, vx, vy

    @staticmethod
    def _axis(pos, vel, r, size):
        pos += vel
        if pos - r < 0:
            return r, -vel
        if pos + r > size:
            return size - r, -vel
        return pos, vel

    def update(self, w, h):
        self.x, self.vx = self._axis(self.x, self.vx, self.r, w)
        self.y, self.vy = self._axis(self.y, self.vy, self.r, h)

    def hit(self, px, py):
        return (px - self.x) ** 2 + (py - self.y) ** 2 <= self.r ** 2

def step(bubbles, w, h, clicks):
    for b in bubbles:
        b.update(w, h)
    popped = 0
    for px, py in clicks:
        for i in range(len(bubbles) - 1, -1, -1):
            if bubbles[i].hit(px, py):
                del bubbles[i]
                popped += 1
                break
    return popped

bs = [Bubble(100, 100, 20, 3, 0), Bubble(470, 300, 15, 10, 10)]
print(step(bs, 480, 320, [(103, 100), (0, 0)]), len(bs), (bs[0].x, bs[0].y, bs[0].vx, bs[0].vy))
פלטOutput
1 1 (465, 305, -10, -10)

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

אתגרChallenge 1

כבידה וחיכוךGravity and friction

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

כתבו physics_step(b, w, h, gravity=0.5, bounce=0.8) לבועה (מילון x, y, r, vx, vy): מוסיפה gravity ל-vy, מזיזה, ובפגיעה ברצפה מחזירה לגבול והופכת את vy כפול bounce (איבוד אנרגיה). בקירות הצד: הקפצה רגילה. ואז frames_until_rest(b, w, h) שמחזירה אחרי כמה פריימים הבועה על הרצפה עם |vy| < 1 (עד 2000).

Write physics_step(b, w, h, gravity=0.5, bounce=0.8) for a bubble (a dict x, y, r, vx, vy): adds gravity to vy, moves, and on hitting the floor puts it back on the boundary and flips vy times bounce (losing energy). Side walls: a normal bounce. Then frames_until_rest(b, w, h) returning after how many frames the bubble sits on the floor with |vy| < 1 (up to 2000).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 physics_step(b, w, h, gravity=0.5, bounce=0.8):
    b["vy"] += gravity
    b["x"] += b["vx"]
    b["y"] += b["vy"]
    if b["y"] + b["r"] > h:
        b["y"] = h - b["r"]
        b["vy"] = -b["vy"] * bounce
    if b["x"] - b["r"] < 0 or b["x"] + b["r"] > w:
        b["x"] = min(max(b["x"], b["r"]), w - b["r"])
        b["vx"] = -b["vx"]

def frames_until_rest(b, w, h):
    for frame in range(1, 2001):
        physics_step(b, w, h)
        if b["y"] == h - b["r"] and abs(b["vy"]) < 1:
            return frame
    return None

ball = {"x": 50, "y": 40, "r": 10, "vx": 4, "vy": 0}
print(frames_until_rest(ball, 480, 320), round(ball["x"]), ball["y"])
פלטOutput
230 42 310

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

אתגרChallenge 2

התנגשות בין בועותBubbles colliding

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

כתבו collide(a, b) לשתי בועות (מילונים x, y, r, vx, vy, באותה מסה): אם הן חופפות (מרחק < r1 + r2), מחליפים ביניהן את רכיבי המהירות לאורך הקו שמחבר את המרכזים, ומרחיקים אותן כך שרק ייגעו. מחזירה True אם הייתה התנגשות. התנגשות חזיתית של בועות זהות מחליפה את המהירויות.

Write collide(a, b) for two bubbles (dicts x, y, r, vx, vy, equal mass): if they overlap (distance < r1 + r2), swap their velocity components along the line joining the centres, and push them apart so they just touch. Returns True if they collided. A head-on collision of identical bubbles swaps their velocities.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 collide(a, b):
    dx, dy = b["x"] - a["x"], b["y"] - a["y"]
    d = math.hypot(dx, dy)
    if d == 0 or d >= a["r"] + b["r"]:
        return False
    nx, ny = dx / d, dy / d
    pa = a["vx"] * nx + a["vy"] * ny
    pb = b["vx"] * nx + b["vy"] * ny
    a["vx"] += (pb - pa) * nx
    a["vy"] += (pb - pa) * ny
    b["vx"] += (pa - pb) * nx
    b["vy"] += (pa - pb) * ny
    push = (a["r"] + b["r"] - d) / 2
    a["x"] -= nx * push
    a["y"] -= ny * push
    b["x"] += nx * push
    b["y"] += ny * push
    return True

a = {"x": 100, "y": 100, "r": 20, "vx": 3, "vy": 0}
b = {"x": 130, "y": 100, "r": 20, "vx": -2, "vy": 0}
print(collide(a, b), (a["vx"], b["vx"]), (a["x"], b["x"]), collide(a, b))
פלטOutput
True (-2.0, 3.0) (95.0, 135.0) False

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

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