Pixel PlatformerPixel Platformer
Tilemap, מצלמה, Coyote Time, Jump Buffer ומצבי אנימציה.
Tilemaps, a camera, coyote time, jump buffering and animation states.
01מפת אריחיםA tilemap
פלטפורמר נבנה ממפת אריחים, בדיוק כמו שלבי Brick Breaker: כל תו במחרוזת הוא אריח בגודל 16×16. # הוא קרקע, c מטבע, e אויב ו-F הדגל בסוף. המפה רחבה בהרבה מהמסך, ובהמשך המצלמה תגלה אותה בהדרגה. כאן מציירים את כל העולם מוקטן כדי לראות אותו בבת אחת:
A platformer is built from a tilemap, just like Brick Breaker's levels: each character is a 16×16 tile. # is ground, c a coin, e an enemy and F the flag at the end. The map is much wider than the screen, and later the camera will reveal it gradually. Here we draw the whole world scaled down to see it at once:
import pygame
LEVEL = [
"..............................................",
"..............................................",
"......................c.c.....................",
".............c.c.....#####..........c.c.c.....",
"............#####..............c..#######.....",
"......c.c.................#########...........",
".....#####......e.....................e.....F.",
"##############################################",
]
T = 16
pygame.init()
world = pygame.Surface((len(LEVEL[0]) * T, len(LEVEL) * T))
world.fill((40, 34, 70))
COLORS = {"#": (150, 100, 70), "c": (255, 210, 60), "e": (230, 80, 110), "F": (90, 220, 120)}
counts = {}
for r, row in enumerate(LEVEL):
for c, ch in enumerate(row):
if ch in COLORS:
pygame.draw.rect(world, COLORS[ch], (c * T, r * T, T, T))
counts[ch] = counts.get(ch, 0) + 1
screen = pygame.display.set_mode((480, 84))
screen.blit(pygame.transform.scale(world, (480, 84)), (0, 0))
print(world.get_size(), counts)
pygame.quit()(736, 128) {'c': 10, '#': 77, 'e': 2, 'F': 1}מפת אריחים היא כמו לגו: כמה סוגי לבנים בגודל אחיד, ומהם בונים כל עולם שרוצים.
A tilemap is like Lego: a few kinds of same-size bricks, and from them you build any world you like.
גישה למשבצת מחוץ למפה.
Reading a tile outside the map.
LEVEL = [
"..............................................",
"..............................................",
"......................c.c.....................",
".............c.c.....#####..........c.c.c.....",
"............#####..............c..#######.....",
"......c.c.................#########...........",
".....#####......e.....................e.....F.",
"##############################################",
]
print(LEVEL[8][0])Traceback (most recent call last):
File "/Users/you/python-course/tilemap.py", line 11, in <module>
print(LEVEL[8][0])
~~~~~^^^
IndexError: list index out of rangeIndexError: list index out of range: יש רק 8 שורות (0 עד 7). כשבודקים אריחים ליד השחקן, מוודאים שהשורה והעמודה בתוך המפה.IndexError: list index out of range: there are only 8 rows (0 to 7). When checking tiles near the player, make sure the row and column are inside the map.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02קפיצה ועמידהJumping and standing
הכבידה מוכרת מ-Flappy. ההבדל: מותר לקפוץ רק כשעומדים על הקרקע, אחרת השחקן היה "עף". הדגל on_ground מתאפס בכל פריים ונדלק רק כשמתנגשים במשהו מלמטה. טריק של משחקים טובים: אם משחררים את מקש הקפיצה מוקדם, חותכים את המהירות כלפי מעלה, וכך יש שליטה בגובה:
Gravity is familiar from Flappy. The difference: jumping is allowed only when standing on the ground, otherwise the player would "fly". The on_ground flag resets every frame and turns on only on a collision from below. A good-game trick: if the jump key is released early, cut the upward speed, giving control over the height:
def jump_height(hold_frames, gravity=0.35, jump=-6.2, cut=0.5):
y, vy, top = 0.0, jump, 0.0
for frame in range(200):
if frame == hold_frames and vy < 0:
vy *= cut
vy += gravity
y += vy
top = min(top, y)
if y >= 0:
break
return round(-top, 1)
for hold in (2, 6, 12, 100):
print(f"held {hold:>3} frames -> {jump_height(hold)} px high")held 2 frames -> 20.8 px high held 6 frames -> 34.9 px high held 12 frames -> 48.1 px high held 100 frames -> 51.9 px high
זה כמו לזרוק כדור למעלה: את הגובה קובעת הזריקה, והכבידה מחליטה מתי הוא חוזר. שחרור מוקדם הוא כמו לזרוק חלש יותר.
It's like throwing a ball up: the throw sets the height, and gravity decides when it returns. Releasing early is like throwing softer.
מאפשרים קפיצה באוויר.
Allowing a jump in mid-air.
vy, y, jumps = 0.0, 0.0, 0
for frame in range(30):
jump_pressed = frame % 5 == 0
if jump_pressed:
vy, jumps = -6.0, jumps + 1
vy += 0.35
y += vy
assert jumps == 1, f"{jumps} jumps without landing: only jump when on_ground is True"Traceback (most recent call last):
File "/Users/you/python-course/jump.py", line 8, in <module>
assert jumps == 1, f"{jumps} jumps without landing: only jump when on_ground is True"
^^^^^^^^^^
AssertionError: 6 jumps without landing: only jump when on_ground is TrueAssertionError: 6 jumps without landing: ...: השחקן עף. בודקים if jump_pressed and on_ground:.AssertionError: 6 jumps without landing: ...: the player flies. Check if jump_pressed and on_ground:.03התנגשות באריחיםColliding with tiles
כמו בלבני Brick Breaker, הסוד הוא הפרדת צירים. מזיזים ב-x ובודקים: אם נכנסנו לאריח, מצמידים את הצד לקיר. אחר כך מזיזים ב-y ובודקים: אם נכנסנו לאריח בזמן נפילה, נוחתים עליו (ו-on_ground נדלק); בזמן עלייה, הראש נתקל בתקרה. הנה פונקציה שעושה בדיוק את זה:
As with Brick Breaker's bricks, the secret is axis separation. Move on x and check: if we entered a tile, snap the side to the wall. Then move on y and check: if we entered a tile while falling, land on it (and on_ground turns on); while rising, the head bumps the ceiling. Here's a function doing exactly that:
import pygame
def move(player, dx, vy, solids):
player.x += dx
for s in solids:
if player.colliderect(s):
player.right = s.left if dx > 0 else player.right
player.left = s.right if dx < 0 else player.left
player.y += round(vy)
on_ground = False
for s in solids:
if player.colliderect(s):
if vy > 0:
player.bottom, vy, on_ground = s.top, 0.0, True
else:
player.top, vy = s.bottom, 0.0
return vy, on_ground
floor = [pygame.Rect(0, 100, 200, 16), pygame.Rect(100, 84, 16, 16)]
p = pygame.Rect(50, 90, 12, 14)
print(move(p, 0, 5, floor), p.bottom)
print(move(p, 60, 0, floor), p.right)(0.0, True) 100 (0, False) 100
התנגשות באריחים היא כמו ללכת בחדר חשוך עם יד מושטת: כשנוגעים בקיר, עוצרים בדיוק לידו, לא בתוכו.
Tile collision is like walking in a dark room with your hand out: touch a wall and you stop right next to it, not inside it.
בודקים את שני הצירים יחד, והשחקן "נתפס" בפינות.
Checking both axes together, so the player "snags" on corners.
moved_together = True
slides_along_floor = not moved_together
assert slides_along_floor, "with x and y moved together you can't tell a wall from a floor, so walking catches on tile seams"Traceback (most recent call last):
File "/Users/you/python-course/tile_collide.py", line 3, in <module>
assert slides_along_floor, "with x and y moved together you can't tell a wall from a floor, so walking catches on tile seams"
^^^^^^^^^^^^^^^^^^
AssertionError: with x and y moved together you can't tell a wall from a floor, so walking catches on tile seamsAssertionError: with x and y moved together ...: כשמזיזים בשני הצירים יחד, אי אפשר לדעת אם פגעתם בקיר או ברצפה. מזיזים ובודקים ציר אחרי ציר.AssertionError: with x and y moved together ...: moving on both axes at once, you can't tell whether you hit a wall or a floor. Move and check one axis at a time.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04מצלמה שעוקבתA following camera
העולם רחב מהמסך, אז צריך מצלמה: מספר שאומר כמה פיקסלים לגלול. הלוגיקה של המשחק נשארת בקואורדינטות של העולם, ורק בציור מחסירים את המצלמה. המצלמה ממקמת את השחקן בשליש השמאלי של המסך (כדי לראות קדימה), ולא יוצאת מגבולות העולם:
The world is wider than the screen, so you need a camera: a number saying how many pixels to scroll. Game logic stays in world coordinates, and only when drawing do you subtract the camera. The camera keeps the player in the left third of the screen (to see ahead), and never goes past the world's edges:
def camera_x(player_x, screen_w, world_w):
return max(0, min(world_w - screen_w, player_x - screen_w // 3))
world_w, screen_w = 736, 480
for x in (20, 200, 400, 700):
cam = camera_x(x, screen_w, world_w)
print(f"player at {x:>3} -> camera {cam:>3} -> drawn at {x - cam}")player at 20 -> camera 0 -> drawn at 20 player at 200 -> camera 40 -> drawn at 160 player at 400 -> camera 240 -> drawn at 160 player at 700 -> camera 256 -> drawn at 444
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מצלמה היא כמו חלון ברכבת: הנוף עצמו לא זז, אתם זזים לאורכו ורואים בכל רגע רק את החלק שמול החלון.
A camera is like a train window: the landscape itself doesn't move, you move along it and see only the part in front of the window.
מחסירים את המצלמה גם בלוגיקה, ולא רק בציור.
Subtracting the camera in the logic too, not just when drawing.
player_x, coin_x, camera = 400, 410, 233
screen_player = player_x - camera
touching = abs(screen_player - coin_x) < 12
assert touching, "the player and the coin are 10px apart in the world, but one was converted to screen space: compare world coordinates"Traceback (most recent call last):
File "/Users/you/python-course/camera.py", line 4, in <module>
assert touching, "the player and the coin are 10px apart in the world, but one was converted to screen space: compare world coordinates"
^^^^^^^^
AssertionError: the player and the coin are 10px apart in the world, but one was converted to screen space: compare world coordinatesAssertionError: the player and the coin are 10px apart ...: התנגשויות ותנועה בקואורדינטות של העולם; המצלמה רק לציור.AssertionError: the player and the coin are 10px apart ...: collisions and movement in world coordinates; the camera only for drawing.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
המצלמה זזה כך שהשחקן נשאר בשליש השמאלי של המסך.
The camera moves so the player stays in the left third of the screen.
screen_w, world_w = 300, 900
for player_x in [50, 300, 850]:
cam = max(0, min(world_w - screen_w, player_x - screen_w // 3))
print(player_x, "-> camera", cam, "-> drawn at", player_x - cam)50 -> camera 0 -> drawn at 50 300 -> camera 200 -> drawn at 100 850 -> camera 600 -> drawn at 250
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05מטבעות ואויביםCoins and enemies
מטבעות הם Rects שנעלמים במגע. אויב מסייר הולך עד שאין קרקע לפניו (בודקים אריח מתחת לנקודה שלפניו) ואז מסתובב. והחוק הקלאסי: נגיעה מהצד פוגעת בשחקן, אבל נחיתה עליו מלמעלה (השחקן נופל, והתחתית שלו מעל אמצע האויב) מחסלת אותו ומקפיצה מעט:
Coins are Rects that vanish on touch. A patrolling enemy walks until there's no ground ahead (check the tile below the point in front of it) and then turns. And the classic rule: touching from the side hurts the player, but landing on it from above (the player falling, their bottom above the enemy's middle) defeats it, with a little bounce:
import pygame
def stomp_or_hurt(player, vy, enemy):
if not player.colliderect(enemy):
return None
if vy > 0 and player.bottom - vy <= enemy.centery:
return "stomp"
return "hurt"
enemy = pygame.Rect(100, 100, 14, 12)
print(stomp_or_hurt(pygame.Rect(102, 88, 12, 14), 4, enemy))
print(stomp_or_hurt(pygame.Rect(92, 100, 12, 14), 0, enemy))
ground = [pygame.Rect(x, 112, 16, 16) for x in range(64, 160, 16)]
x, d = 100, 1
for _ in range(120):
x += d
probe = pygame.Rect(x + d * 8, 116, 2, 2)
if not any(g.colliderect(probe) for g in ground):
d = -d
print("patrol stays between", 64, "and", 160, "->", 64 <= x <= 160)stomp hurt patrol stays between 64 and 160 -> True
אויב מסייר הוא כמו שומר שהולך לאורך חומה: מגיע לפינה, מסתובב, וחוזר, בלי לחשוב יותר מזה.
A patrolling enemy is like a guard walking a wall: reaches the corner, turns, comes back, and thinks no further.
אויב שנופל מהפלטפורמה כי לא בודק קרקע לפניו.
An enemy walking off the platform because it doesn't check the ground ahead.
ground_x = range(64, 160)
x, d = 100, 1
for _ in range(120):
x += d
assert x in ground_x, f"the enemy walked to x={x}, off the platform: check for ground ahead and turn"Traceback (most recent call last):
File "/Users/you/python-course/enemies.py", line 5, in <module>
assert x in ground_x, f"the enemy walked to x={x}, off the platform: check for ground ahead and turn"
^^^^^^^^^^^^^
AssertionError: the enemy walked to x=220, off the platform: check for ground ahead and turnAssertionError: the enemy walked to x=220, off the platform: ...: בודקים אריח מתחת לנקודה שלפני האויב, והופכים כיוון אם אין.AssertionError: the enemy walked to x=220, off the platform: ...: check the tile under the point ahead of the enemy, and turn if there isn't one.06Pixel Platformer: המשחקPixel Platformer: the game
המשחק כולו: עולם ממפת אריחים, שחקן עם כבידה וקפיצה, התנגשות בהפרדת צירים, מצלמה שעוקבת, מטבעות, אויבים מסיירים, ודגל בסוף. כאן השחקן רץ ימינה וקופץ לבד מול בורות, קירות ואויבים; במחשב שלכם החיצים ורווח:
The whole game: a world from a tilemap, a player with gravity and jumping, axis-separated collision, a following camera, coins, patrolling enemies, and a flag at the end. Here the player runs right and jumps by itself at gaps, walls and enemies; on your computer, arrows and space:
import pygame
LEVEL = [
"..............................................",
"..............................................",
"......................c.c.....................",
".............c.c.....#####..........c.c.c.....",
"............#####..............c..#######.....",
"......c.c.................#########...........",
".....#####......e.....................e.....F.",
"##############################################",
]
T, W, H = 16, 480, 160
pygame.init()
screen = pygame.display.set_mode((W, H))
font = pygame.font.Font(None, 22)
solids = [pygame.Rect(c * T, r * T, T, T) for r, row in enumerate(LEVEL) for c, ch in enumerate(row) if ch == "#"]
coins = [pygame.Rect(c * T + 4, r * T + 4, 8, 8) for r, row in enumerate(LEVEL) for c, ch in enumerate(row) if ch == "c"]
enemies = [[pygame.Rect(c * T, r * T + 4, 14, 12), 1] for r, row in enumerate(LEVEL) for c, ch in enumerate(row) if ch == "e"]
flag = next(pygame.Rect(c * T, r * T - 16, 4, 32) for r, row in enumerate(LEVEL) for c, ch in enumerate(row) if ch == "F")
world_w = len(LEVEL[0]) * T
player = pygame.Rect(2 * T, 5 * T, 12, 14)
vy, on_ground, score, camera = 0.0, False, 0, 0
for frame in range(420):
ahead = pygame.Rect(player.right + 2, player.bottom - 2, 4, 4)
gap = not any(s.colliderect(ahead.move(0, 6)) for s in solids)
wall = any(s.colliderect(ahead.move(0, -8)) for s in solids)
if on_ground and (gap or wall or any(e.colliderect(ahead.inflate(40, 20)) for e, _ in enemies)):
vy = -6.2
player.x += 2
for s in solids:
if player.colliderect(s):
player.right = s.left
vy = min(8.0, vy + 0.35)
player.y += round(vy)
on_ground = False
for s in solids:
if player.colliderect(s):
if vy > 0:
player.bottom, vy, on_ground = s.top, 0.0, True
else:
player.top, vy = s.bottom, 0.0
for c in coins[:]:
if player.colliderect(c):
coins.remove(c)
score += 1
for e in enemies:
e[0].x += e[1]
if not any(s.colliderect(e[0].move(e[1] * 8, 4)) for s in solids):
e[1] = -e[1]
camera = max(0, min(world_w - W, player.centerx - W // 3))
screen.fill((40, 34, 70))
for s in solids:
if -T < s.x - camera < W:
pygame.draw.rect(screen, (150, 100, 70), s.move(-camera, 0))
pygame.draw.rect(screen, (110, 200, 90), (s.x - camera, s.y, T, 3))
for c in coins:
pygame.draw.ellipse(screen, (255, 210, 60), c.move(-camera, 0))
for e, _ in enemies:
pygame.draw.rect(screen, (230, 80, 110), e.move(-camera, 0), border_radius=4)
pygame.draw.rect(screen, (240, 240, 240), flag.move(-camera, 0))
pygame.draw.polygon(screen, (90, 220, 120), [(flag.right - camera, flag.top), (flag.right - camera + 14, flag.top + 6), (flag.right - camera, flag.top + 12)])
pygame.draw.rect(screen, (120, 200, 255), player.move(-camera, 0), border_radius=3)
screen.blit(font.render(f"Coins {score}", True, (255, 255, 255)), (6, 4))
pygame.display.flip()
if player.colliderect(flag):
break
print("coins:", score, "reached flag:", player.colliderect(flag), "frames:", frame)
pygame.quit()coins: 3 reached flag: True frames: 336
פלטפורמר הוא אוסף של חוקים קטנים שכל אחד מהם פשוט: כבידה, מגע בקרקע, מצלמה. החוויה נוצרת מהשילוב.
A platformer is a collection of small rules, each simple: gravity, ground contact, a camera. The experience comes from combining them.
שחקן שנופל דרך הקרקע במהירות גבוהה.
A player falling through the ground at high speed.
vy = 0.0
for _ in range(120):
vy += 0.35
assert vy <= 16, f"falling at {vy:.0f}px a frame through 16px tiles: cap the fall speed below the tile size"Traceback (most recent call last):
File "/Users/you/python-course/platformer.py", line 4, in <module>
assert vy <= 16, f"falling at {vy:.0f}px a frame through 16px tiles: cap the fall speed below the tile size"
^^^^^^^^
AssertionError: falling at 42px a frame through 16px tiles: cap the fall speed below the tile sizeAssertionError: falling at 42px a frame through 16px tiles: ...: מנהור! מגבילים מהירות נפילה (כאן 8) כך שתהיה קטנה מגודל אריח.AssertionError: falling at 42px a frame through 16px tiles: ...: tunneling! Cap the fall speed (here 8) below the tile size.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.