נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • שני מחבטים כ-RectTwo paddles as Rects
  • קו אמצע מקווקו בלולאהA dashed centre line in a loop
  • מיקום עשרוני bx, by לתנועה חלקהA float position bx, by for smooth motion
  • ה-Rect מקבל round לציורThe Rect gets round for drawing
  • פגיעה במרכז = ישר, בקצה = חדA centre hit = straight, an edge hit = sharp
  • offset בין -1 ל-1offset from -1 to 1
  • עוקב אחרי הכדורFollows the ball
  • מהירות מוגבלת = אפשר לנצחLimited speed = beatable
  • dt = שניות מאז הפריים הקודםdt = seconds since the last frame

מונחיםTerms

  • מחבטpaddle: המלבן שהשחקן מזיז כדי להחזיר את הכדור.The rectangle a player moves to return the ball.
  • זווית יציאהrebound angle: הכיוון שבו הכדור עוזב את המחבט. פגיעה בקצה שולחת בזווית חדה יותר, וזה נותן לשחקן שליטה.The direction the ball leaves the paddle. Hitting near the edge sends it at a sharper angle, giving the player control.
  • יריב ממוחשבAI opponent: שחקן שהמחשב מזיז לפי כלל פשוט, כמו "לעקוב אחרי הכדור", עם מהירות מוגבלת כדי שאפשר יהיה לנצח.A player the computer moves by a simple rule, like "follow the ball", with limited speed so it can be beaten.
  • זמן פריים (dt)delta time (dt): הזמן שעבר מהפריים הקודם. כופלים בו מהירויות כדי שהמשחק ירוץ באותו קצב בכל מחשב.The time since the last frame. Multiply speeds by it so the game runs at the same pace on every computer.
  • שקיפות (alpha)alpha (transparency): רכיב רביעי בצבע: 0 שקוף לגמרי, 255 אטום. צריך Surface עם pygame.SRCALPHA.A fourth colour component: 0 fully transparent, 255 opaque. Needs a Surface with pygame.SRCALPHA.

Cheatsheet

מגרשCourt
import pygame

W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
left = pygame.Rect(16, H // 2 - 35, 10, 70)
right = pygame.Rect(W - 26, H // 2 - 35, 10, 70)
כדורBall
import pygame

rect = pygame.Rect(0, 0, 12, 12)
for _ in range(10):
    rect.x += 0.5
print("rect only:", rect.x)
זוויתAngle
def rebound(ball_y, paddle_y, paddle_h, vx, max_vy=5):
    offset = (ball_y - paddle_y) / (paddle_h / 2)
    offset = max(-1.0, min(1.0, offset))
    return round(-vx * 1.05, 2), round(offset * max_vy, 2)

for hit in [160, 175, 194, 126]:
    print(hit, "->", rebound(hit, 160, 70, 5))
יריבOpponent
def ai_move(paddle_y, ball_y, speed, dead=4):
    if paddle_y < ball_y - dead:
        return paddle_y + min(speed, ball_y - paddle_y)
    if paddle_y > ball_y + dead:
        return paddle_y - min(speed, paddle_y - ball_y)
    return paddle_y
dtdt
def run(fps, seconds=2, speed=300):
    x, dt = 0.0, 1 / fps
    for _ in range(int(fps * seconds)):
        x += speed * dt
    return round(x)

print("60 FPS:", run(60), " 30 FPS:", run(30), " 144 FPS:", run(144))
משחקGame
import pygame

W, H = 480, 320
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 48)
glow = pygame.Surface((W, H), pygame.SRCALPHA)

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorמספרים קבועים מפוזרים בקוד במקום קבוע אחד.Magic numbers scattered in the code instead of one constant.AssertionError: the window grew to 640 but the paddle is still at 454: ...: כותבים W - 26, ואז שינוי גודל לא שובר את המשחק.AssertionError: the window grew to 640 but the paddle is still at 454: ...: write W - 26, and resizing won't break the game.
AssertionErrorמוסיפים מהירות קטנה ישר ל-Rect.Adding a small speed straight to a Rect.AssertionError: after 60 frames ball.x is 0: ...: כל הוספה של 0.4 נחתכת ל-0. שומרים מיקום עשרוני נפרד.AssertionError: after 60 frames ball.x is 0: ...: each 0.4 is truncated to 0. Keep a separate float position.
AssertionErrorהכדור נתקע בתוך המחבט ומתהפך שוב ושוב.The ball gets stuck inside the paddle and flips again and again.AssertionError: vx flipped 4 times ...: מחזירים רק אם הכדור נע לכיוון המחבט (vx < 0 למחבט השמאלי), כמו בקוד המשחק.AssertionError: vx flipped 4 times ...: bounce only if the ball moves toward the paddle (vx < 0 for the left one), as in the game code.
AssertionErrorיריב בלי הגבלת מהירות שאי אפשר לנצח.An opponent without a speed limit that can't be beaten.AssertionError: the AI teleports to every ball: ...: מגבילים מהירות (min(speed, ...)) כדי שיהיה סיכוי לנצח.AssertionError: the AI teleports to every ball: ...: cap the speed (min(speed, ...)) so there's a chance to win.
AssertionErrorצבע עם שקיפות על Surface רגיל.A transparent colour on a plain Surface.AssertionError: alpha is 255: ...: Surface רגיל מתעלם מהשקיפות. יוצרים pygame.Surface(size, pygame.SRCALPHA).AssertionError: alpha is 255: ...: a plain Surface ignores alpha. Create pygame.Surface(size, pygame.SRCALPHA).
AssertionErrorניקוד לצד הלא נכון.Scoring for the wrong side.AssertionError: כדור שיצא מימין = נקודה לשחקן השמאלי. בודקים את התנאי עם דוגמה ביד.AssertionError: a ball out on the right = a point for the left player. Check the condition with an example by hand.

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