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

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

Neon PongNeon Pong

Vector2, פיזיקת כדור, יריב מחשב, טיימרים וצלילים מסונתזים.

Vector2, ball physics, a computer opponent, timers and synthesized sound.

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

זווית החזרהRebound angle

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

כתבו rebound(ball_y, paddle_center, paddle_h, vx, max_vy=5) שמחזירה (new_vx, new_vy): vx מתהפך ומואץ פי 1.05, ו-vy הוא offset * max_vy כש-offset הוא המיקום היחסי (בין -1 ל-1, מוגבל). עגלו שניהם ל-2.

Write rebound(ball_y, paddle_center, paddle_h, vx, max_vy=5) returning (new_vx, new_vy): vx flips and speeds up ×1.05, and vy is offset * max_vy where offset is the relative position (from -1 to 1, clamped). Round both to 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 rebound(ball_y, paddle_center, paddle_h, vx, max_vy=5):
    offset = max(-1.0, min(1.0, (ball_y - paddle_center) / (paddle_h / 2)))
    return round(-vx * 1.05, 2), round(offset * max_vy, 2)

print(rebound(160, 160, 70, 5), rebound(195, 160, 70, -5), rebound(400, 160, 70, 5))
פלטOutput
(-5.25, 0.0) (5.25, 5.0) (-5.25, 5.0)

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

תרגילExercise 2

יריב הוגןA fair opponent

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

כתבו ai_move(paddle_y, ball_y, speed, dead=4) שמחזירה את מיקום המחבט החדש: מתקרב לכדור לכל היותר speed פיקסלים, לא עובר אותו, ולא זז אם ההפרש קטן או שווה ל-dead.

Write ai_move(paddle_y, ball_y, speed, dead=4) returning the paddle's new position: moves toward the ball by at most speed pixels, never past it, and doesn't move if the gap is at most dead.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 ai_move(paddle_y, ball_y, speed, dead=4):
    gap = ball_y - paddle_y
    if abs(gap) <= dead:
        return paddle_y
    return paddle_y + max(-speed, min(speed, gap))

print([ai_move(160, b, 6) for b in (162, 200, 100, 165)])
פלטOutput
[160, 166, 154, 165]

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

תרגילExercise 3

ניקוד והגשהScoring and serving

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

כתבו check_point(ball_x, width, score) שמקבלת את x של הכדור ורשימת ניקוד [left, right]: אם הכדור יצא משמאל (x < 0) נקודה לימני, ואם מימין (x > width) נקודה לשמאלי. היא מעדכנת את הרשימה ומחזירה את כיוון ההגשה הבא: 1 (ימינה), -1 (שמאלה) או 0 אם אין נקודה. מגישים לכיוון מי שספג.

Write check_point(ball_x, width, score) taking the ball's x and a score list [left, right]: if the ball went out on the left (x < 0) the right player scores, and on the right (x > width) the left player scores. It updates the list and returns the next serve direction: 1 (right), -1 (left) or 0 if no point. Serve toward whoever conceded.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 check_point(ball_x, width, score):
    if ball_x < 0:
        score[1] += 1
        return -1
    if ball_x > width:
        score[0] += 1
        return 1
    return 0

score = [0, 0]
print([check_point(x, 480, score) for x in (-5, 240, 500, 490)], score)
פלטOutput
[-1, 0, 1, 1] [2, 1]

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

תרגילExercise 4

קצב קבועA steady pace

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

כתבו simulate(fps, seconds, speed, width) שמזיזה כדור מ-x=0 ימינה ב-speed פיקסלים לשנייה עם dt = 1/fps, מקפיצה מהקיר הימני ומהשמאלי (רדיוס 0), ומחזירה את x הסופי מעוגל. התוצאה צריכה להיות כמעט זהה ב-30 וב-120 FPS.

Write simulate(fps, seconds, speed, width) moving a ball from x=0 rightward at speed pixels per second with dt = 1/fps, bouncing off the right and left walls (radius 0), returning the final x rounded. The result should be almost the same at 30 and 120 FPS.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 simulate(fps, seconds, speed, width):
    x, v, dt = 0.0, float(speed), 1 / fps
    for _ in range(round(fps * seconds)):
        x += v * dt
        if x > width:
            x, v = 2 * width - x, -v
        elif x < 0:
            x, v = -x, -v
    return round(x)

print(simulate(30, 3, 200, 480), simulate(120, 3, 200, 480), simulate(60, 1, 200, 480))
פלטOutput
360 360 200

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

תרגילExercise 5

Neon Pong: מנוע המשחקNeon Pong: the game engine

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

כתבו מחלקה Pong(w=480, h=320) עם ball (מילון x, y, vx, vy, size=12), left ו-right (מרכזי y של מחבטים בגובה 70, ב-x=16 ו-x=w-26, רוחב 10), ו-score = [0, 0]. step(left_move, right_move): מזיזה מחבטים (מוגבלים למסך), את הכדור, מקפיצה מתקרה ורצפה, מחזירה מהמחבטים עם זווית (כמו ב-rebound), ובנקודה מעדכנת ניקוד ומגישה מהמרכז לכיוון מי שספג.

Write a Pong(w=480, h=320) class with a ball (dict x, y, vx, vy, size=12), left and right (paddle centre ys, height 70, at x=16 and x=w-26, width 10), and score = [0, 0]. step(left_move, right_move): moves paddles (clamped to the screen), moves the ball, bounces off ceiling and floor, returns off paddles with an angle (as in rebound), and on a point updates the score and serves from the centre toward whoever conceded.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
neon_pong.py
class Pong:
    def __init__(self, w=480, h=320):
        self.w, self.h = w, h
        self.left = self.right = h / 2
        self.score = [0, 0]
        self.serve(1)

    def serve(self, direction):
        self.ball = {"x": self.w / 2, "y": self.h / 2, "vx": 5.0 * direction, "vy": 2.0, "size": 12}

    def _paddle(self, y, move):
        return max(35, min(self.h - 35, y + move))

    def _hits(self, center, x0):
        b = self.ball
        return x0 - b["size"] / 2 <= b["x"] <= x0 + 10 + b["size"] / 2 and abs(b["y"] - center) < 35 + b["size"] / 2

    def step(self, left_move, right_move):
        self.left = self._paddle(self.left, left_move)
        self.right = self._paddle(self.right, right_move)
        b = self.ball
        b["x"] += b["vx"]
        b["y"] += b["vy"]
        if b["y"] < b["size"] / 2 or b["y"] > self.h - b["size"] / 2:
            b["vy"] = -b["vy"]
        for center, x0, toward in ((self.left, 16, -1), (self.right, self.w - 26, 1)):
            if (b["vx"] > 0) == (toward > 0) and self._hits(center, x0):
                offset = max(-1.0, min(1.0, (b["y"] - center) / 35))
                b["vx"], b["vy"] = -b["vx"] * 1.05, offset * 5
        if b["x"] < 0:
            self.score[1] += 1
            self.serve(-1)
        elif b["x"] > self.w:
            self.score[0] += 1
            self.serve(1)

g = Pong()
for _ in range(300):
    g.step(0, 0)
print(g.score, round(g.ball["x"]), g.left)
פלטOutput
[6, 0] 270 160.0

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

אתגרChallenge 1

יריב שמנבאA predicting opponent

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

יריב חכם לא עוקב אחרי הכדור, אלא אחרי המקום שבו הכדור יגיע לקו המחבט. כתבו predict_y(x, y, vx, vy, target_x, height) שמחזירה את ה-y שבו הכדור יחצה את target_x, כולל הקפצות מהתקרה והרצפה (0 ו-height). אם הכדור מתרחק, מחזירים את מרכז המסך.

A smart opponent doesn't follow the ball, but where the ball will arrive at its paddle line. Write predict_y(x, y, vx, vy, target_x, height) returning the y where the ball crosses target_x, including bounces off the ceiling and floor (0 and height). If the ball moves away, return the screen centre.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 predict_y(x, y, vx, vy, target_x, height):
    if vx == 0:
        return height / 2
    t = (target_x - x) / vx
    if t < 0:
        return height / 2
    p = (y + vy * t) % (2 * height)
    return round(2 * height - p if p > height else p, 2)

print(predict_y(240, 160, 5, 0, 454, 320), predict_y(240, 160, 5, 3, 454, 320), predict_y(240, 160, -5, 3, 454, 320))
פלטOutput
160.0 288.4 160.0

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

אתגרChallenge 2

שובל חלקיקיםA particle trail

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

כתבו מחלקה Trail(max_len=12) שזוכרת את המיקומים האחרונים של הכדור: add(x, y) מוסיפה ושומרת רק max_len אחרונים (השתמשו ב-collections.deque), ו-points() מחזירה רשימת (x, y, alpha, radius) מהישן לחדש: alpha עולה ליניארית מ-255 // max_len עד 255, ו-radius מ-1 עד 6 (מעוגל).

Write a Trail(max_len=12) class remembering the ball's last positions: add(x, y) adds and keeps only the last max_len (use collections.deque), and points() returns (x, y, alpha, radius) from oldest to newest: alpha rises linearly from 255 // max_len to 255, and radius from 1 to 6 (rounded).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from collections import deque

class Trail:
    def __init__(self, max_len=12):
        self.max_len = max_len
        self.pos = deque(maxlen=max_len)

    def add(self, x, y):
        self.pos.append((x, y))

    def points(self):
        n = len(self.pos)
        out = []
        for i, (x, y) in enumerate(self.pos):
            step = self.max_len - n + i + 1
            out.append((x, y, 255 * step // self.max_len, round(1 + 5 * (step - 1) / max(1, self.max_len - 1))))
        return out

t = Trail(4)
for x in range(0, 60, 10):
    t.add(x, 100)
print(t.points())
פלטOutput
[(20, 100, 63, 1), (30, 100, 127, 3), (40, 100, 191, 4), (50, 100, 255, 6)]

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

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