Crystal Quest, חלק 2 ופרסוםCrystal Quest, part 2 & publishing
חפצים, אויבים עם AI, קרבות, בוס, שמירה ב-JSON ופרסום לדפדפן עם pygbag.
Items, enemies with AI, combat, a boss, saving to JSON and publishing to the browser with pygbag.
01אויבים עם מצביםEnemies with states
רוח ב-Crystal Quest לא רודפת תמיד: היא מסיירת ליד הבית, עוברת למצב מרדף כשהשחקן מתקרב, ומוותרת וחוזרת הביתה כשהוא מתרחק. זו מכונת מצבים כמו בסצנות, רק בקטן. טריק חשוב: טווח היציאה מהמרדף (90) גדול מטווח הכניסה (60), אחרת רוח בדיוק על הגבול הייתה מתחלפת בכל פריים:
A Crystal Quest ghost doesn't always chase: it patrols near home, switches to a chase state when the player gets close, and gives up and returns home when they move away. It's a state machine like the scenes, just small. An important trick: the exit range (90) is bigger than the entry range (60), otherwise a ghost right on the edge would flip every frame:
def next_state(state, dist_to_player, dist_to_home):
if state == "patrol" and dist_to_player < 60:
return "chase"
if state == "chase" and dist_to_player > 90:
return "return"
if state == "return":
if dist_to_player < 60:
return "chase"
if dist_to_home < 2:
return "patrol"
return state
state = "patrol"
for player_d, home_d in [(120, 0), (55, 10), (75, 40), (95, 50), (100, 20), (100, 1)]:
state = next_state(state, player_d, home_d)
print(f"player {player_d:>3} away -> {state}")player 120 away -> patrol player 55 away -> chase player 75 away -> chase player 95 away -> return player 100 away -> return player 100 away -> patrol
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו כלב שמירה: מסתובב בחצר, נובח ורץ כשמישהו מתקרב לגדר, וכשהאורח הלך רחוק הוא חוזר למלונה.
It's like a guard dog: wanders the yard, barks and runs when someone nears the fence, and when the visitor is far away it goes back to its kennel.
טווח כניסה ויציאה זהים, והרוח "מהבהבת".
Equal entry and exit ranges, so the ghost "flickers".
state, changes = "patrol", 0
for d in [59, 61, 59, 61, 59, 61]:
new = "chase" if d < 60 else "patrol"
changes += new != state
state = new
assert changes <= 1, f"{changes} state changes in 6 frames: make the exit range bigger than the entry range"Traceback (most recent call last):
File "/Users/you/python-course/ghost_ai.py", line 6, in <module>
assert changes <= 1, f"{changes} state changes in 6 frames: make the exit range bigger than the entry range"
^^^^^^^^^^^^
AssertionError: 6 state changes in 6 frames: make the exit range bigger than the entry rangeAssertionError: 6 state changes in 6 frames: ...: על הגבול כל רעד קטן מחליף מצב. נכנסים ב-60 ויוצאים רק ב-90.AssertionError: 6 state changes in 6 frames: ...: on the edge every tiny wobble switches state. Enter at 60 and leave only at 90.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מצב הרוח משתנה לפי המרחק מהשחקן.
The ghost's state changes by the distance to the player.
state = "patrol"
for d in [100, 50, 70, 95, 40]:
if state == "patrol" and d < 60:
state = "chase"
elif state == "chase" and d > 90:
state = "patrol"
print(d, state)100 patrol 50 chase 70 chase 95 patrol 40 chase
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02שמירה וטעינהSaving and loading
קובץ שמירה הוא JSON רגיל, כמו בשיעור הקבצים. שני כללים הופכים אותו לבטוח: כותבים קודם לקובץ זמני ורק אז מחליפים (Path.replace), כך שקריסה באמצע לא משאירה קובץ חצי כתוב; וטעינה תמיד מוכנה לקובץ חסר או פגום, ואז מתחילה משחק חדש במקום לקרוס:
A save file is plain JSON, as in the files lesson. Two rules make it safe: write to a temp file first and only then replace (Path.replace), so a crash midway never leaves a half-written file; and loading is always ready for a missing or broken file, starting a new game instead of crashing:
import json
from pathlib import Path
NEW_GAME = {"room": "hall", "pos": [2, 9], "bag": {}, "hp": 3}
def save(state, path):
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2), encoding="utf-8")
tmp.replace(path)
def load(path):
try:
state = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return dict(NEW_GAME), "new game"
except json.JSONDecodeError:
return dict(NEW_GAME), "save was damaged, new game"
return {**NEW_GAME, **state}, "loaded"
slot = Path("slot1.json")
print(load(slot))
save({"room": "cave", "pos": [4, 2], "bag": {"crystal": 2}}, slot)
print(load(slot))
slot.write_text("{\"room\": \"ca", encoding="utf-8")
print(load(slot)[1])({'room': 'hall', 'pos': [2, 9], 'bag': {}, 'hp': 3}, 'new game')
({'room': 'cave', 'pos': [4, 2], 'bag': {'crystal': 2}, 'hp': 3}, 'loaded')
save was damaged, new gameצפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
שמירה דרך קובץ זמני היא כמו להעתיק מחברת לדף חדש ורק בסוף לזרוק את הישן: אם משהו קורה באמצע, הישן עדיין שלם.
Saving via a temp file is like copying a notebook onto a fresh page and only then throwing out the old one: if something happens midway, the old one is still whole.
שומרים אובייקט שלא ניתן להמרה ל-JSON.
Saving an object JSON can't convert.
import json
state = {"bag": {"crystal", "key"}}
json.dumps(state)Traceback (most recent call last):
File "/Users/you/python-course/save.py", line 3, in <module>
json.dumps(state)
~~~~~~~~~~^^^^^^^
File "/usr/local/lib/python3.13/json/__init__.py", line 235, in dumps
return _default_encoder.encode(obj)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^
File "/usr/local/lib/python3.13/json/encoder.py", line 202, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python3.13/json/encoder.py", line 263, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python3.13/json/encoder.py", line 182, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
f'is not JSON serializable')
TypeError: Object of type set is not JSON serializableTypeError: Object of type set is not JSON serializable: JSON מכיר רשימות ומילונים, לא set או Vector2. ממירים: sorted(bag) או [v.x, v.y].TypeError: Object of type set is not JSON serializable: JSON knows lists and dicts, not set or Vector2. Convert: sorted(bag) or [v.x, v.y].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03חלקיקיםParticles
הרגע שבו אוספים קריסטל צריך להרגיש טוב, וחלקיקים הם הדרך הזולה ביותר: כמה עשרות נקודות שעפות לכיוונים אקראיים, מאטות בחיכוך ונעלמות. כל חלקיק הוא רשימה קטנה [pos, vel, life]. הנה פיצוץ אחד, מצויר ברגע אחד באמצע חייו:
The moment you collect a crystal should feel good, and particles are the cheapest way: a few dozen points flying in random directions, slowing with friction and vanishing. Each particle is a small list [pos, vel, life]. Here's one burst, drawn at a moment halfway through its life:
import math
import random
import pygame
random.seed(3)
pygame.init()
screen = pygame.display.set_mode((240, 160))
particles = []
for _ in range(80):
angle, speed = random.uniform(0, math.tau), random.uniform(0.5, 3)
particles.append([pygame.Vector2(120, 80), pygame.Vector2(math.cos(angle), math.sin(angle)) * speed, random.randint(20, 50)])
alive = []
for frame in range(25):
for p in particles[:]:
p[0] += p[1]
p[1] *= 0.95
p[2] -= 1
if p[2] <= 0:
particles.remove(p)
alive.append(len(particles))
screen.fill((16, 14, 30))
for pos, vel, life in particles:
pygame.draw.circle(screen, (80 + life * 3, 200, 255), pos, 1 + life // 15)
pygame.draw.polygon(screen, (120, 230, 255), [(120, 72), (128, 80), (120, 88), (112, 80)])
print("alive every 5 frames:", alive[::5])
pygame.quit()alive every 5 frames: [80, 80, 80, 80, 77]
חלקיקים הם כמו זיקוקים: כל ניצוץ פשוט לגמרי, נע ודועך, אבל מאות ביחד יוצרים רגע של חגיגה.
Particles are like fireworks: each spark is utterly simple, moving and fading, but hundreds together make a moment of celebration.
מוסיפים חלקיקים ולא מוחקים אף פעם.
Adding particles and never deleting them.
particles = []
for frame in range(600):
particles += [[0, 0, 30] for _ in range(20)]
for p in particles:
p[2] -= 1
assert len(particles) < 1000, f"{len(particles)} particles and counting: remove each one when its life reaches 0"Traceback (most recent call last):
File "/Users/you/python-course/particles.py", line 6, in <module>
assert len(particles) < 1000, f"{len(particles)} particles and counting: remove each one when its life reaches 0"
^^^^^^^^^^^^^^^^^^^^^
AssertionError: 12000 particles and counting: remove each one when its life reaches 0AssertionError: 12000 particles and counting: ...: המשחק יאט עד שייתקע. מוחקים חלקיק כשהחיים שלו מגיעים ל-0.AssertionError: 12000 particles and counting: ...: the game slows until it freezes. Delete a particle when its life reaches 0.04קבצי משחק ונתיביםGame files and paths
משחק אמיתי טוען תמונות וצלילים מתיקיית assets. המלכודת: open("assets/hero.png") מחפש יחסית לתיקייה שממנה הורץ הפקודה, לא לתיקייה של הקוד, ולכן עובד אצלכם ונשבר אצל חברים. בונים נתיבים מ-Path(__file__).parent, ומכינים תחליף צבעוני לכל קובץ שחסר, כדי שהמשחק ייפתח גם אם שכחתם להעתיק תמונה:
A real game loads images and sounds from an assets folder. The trap: open("assets/hero.png") looks relative to the folder the command was run from, not the code's folder, so it works for you and breaks for friends. Build paths from Path(__file__).parent, and prepare a coloured placeholder for any missing file, so the game opens even if you forgot to copy an image:
from pathlib import Path
import pygame
ASSETS = Path(__file__).parent / "assets"
_cache = {}
def image(name, size=(16, 16)):
if name not in _cache:
path = ASSETS / name
if path.exists():
_cache[name] = pygame.image.load(path)
else:
placeholder = pygame.Surface(size)
placeholder.fill((255, 0, 255))
_cache[name] = placeholder
print(f"missing {path.relative_to(Path(__file__).parent)}, using a placeholder")
return _cache[name]
pygame.init()
hero = image("hero.png")
again = image("hero.png")
print(hero.get_size(), hero is again)
pygame.quit()missing assets/hero.png, using a placeholder (16, 16) True
נתיב יחסי לתיקיית ההרצה הוא כמו להגיד "המפתח במגירה השנייה" בלי להגיד באיזה בית. __file__ הוא הכתובת המלאה.
A path relative to where you ran from is like saying "the key is in the second drawer" without saying which house. __file__ is the full address.
מריצים את המשחק מתיקייה אחרת, והתמונה לא נמצאת.
Running the game from another folder, so the image isn't found.
cd ..
python3 python-course/game.py$ cd ..
$ python3 python-course/game.py
Traceback (most recent call last):
File "/Users/you/python-course/game.py", line 1, in <module>
open("assets/hero.txt").read()
~~~~^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'assets/hero.txt'FileNotFoundError: [Errno 2] No such file or directory: 'assets/hero.txt': הקובץ קיים, אבל הנתיב יחסי לתיקייה שבה אתם עומדים. משתמשים ב-Path(__file__).parent / "assets" / "hero.txt".FileNotFoundError: [Errno 2] No such file or directory: 'assets/hero.txt': the file exists, but the path is relative to the folder you're standing in. Use Path(__file__).parent / "assets" / "hero.txt".05פרסום המשחקPublishing the game
כדי שחברים ישחקו, יש שתי דרכים. בדפדפן: pygbag הופך את המשחק לאתר. הוא דורש שינוי קטן: הלולאה הראשית בתוך async def main(), עם await asyncio.sleep(0) בכל פריים כדי לתת לדפדפן לנשום. הקוד הזה רץ גם במחשב רגיל, ולכן אין שתי גרסאות:
For friends to play, there are two ways. In the browser: pygbag turns the game into a website. It needs one small change: the main loop goes inside async def main(), with await asyncio.sleep(0) every frame to let the browser breathe. This code also runs on a normal computer, so there are no two versions:
import asyncio
import pygame
async def main():
pygame.init()
screen = pygame.display.set_mode((240, 120))
clock = pygame.time.Clock()
frames = 0
for frame in range(90):
screen.fill((16, 14, 30))
pygame.draw.circle(screen, (120, 230, 255), (20 + frame * 2, 60), 10)
pygame.display.flip()
clock.tick(60)
frames += 1
await asyncio.sleep(0)
print("ran", frames, "frames; the browser got a turn after each one")
pygame.quit()
asyncio.run(main())ran 90 frames; the browser got a turn after each one
ואז בטרמינל, מתוך תיקיית המשחק (הקובץ הראשי חייב להיקרא main.py). pygbag בונה תיקייה build/web שאפשר לדחוס ל-zip ולהעלות ל-itch.io, ו-PyInstaller בונה קובץ הרצה בתיקייה dist:
Then in the terminal, from the game's folder (the main file must be called main.py). pygbag builds a build/web folder you can zip and upload to itch.io, and PyInstaller builds an executable in the dist folder:
python3 -m pip install pygbag pyinstaller
python3 -m pygbag .
python3 -m PyInstaller --onefile --windowed --add-data "assets:assets" main.pyב-Windows מפרידים ב---add-data בנקודה-פסיק או בנקודתיים לפי הגרסה; בגרסאות חדשות של PyInstaller נקודתיים עובדות בכל מערכת. בדקו תמיד את הקובץ שנבנה על מחשב שאין בו פייתון.
On Windows, --add-data used a semicolon in old versions; new PyInstaller versions accept a colon everywhere. Always test the built file on a computer without Python.
פרסום הוא כמו להעביר מתכון לחבר: אצלכם הכול במקום, אבל צריך לכתוב בדיוק איזה מצרכים לקנות ואיפה הם, אחרת אצלו זה לא יעבוד.
Publishing is like handing a recipe to a friend: in your kitchen everything's in place, but you must write exactly which ingredients to buy and where they are, or it won't work for them.
לולאה אסינכרונית בלי await, והפונקציה לא רצה בכלל.
An async loop without await, so the function never runs at all.
import asyncio
async def main():
return "played"
result = main()
assert result == "played", f"got {type(result).__name__}: run it with asyncio.run(main())"Traceback (most recent call last):
File "/Users/you/python-course/main.py", line 7, in <module>
assert result == "played", f"got {type(result).__name__}: run it with asyncio.run(main())"
^^^^^^^^^^^^^^^^^^
AssertionError: got coroutine: run it with asyncio.run(main())
<sys>:0: RuntimeWarning: coroutine 'main' was never awaitedAssertionError: got coroutine: ...: קריאה ל-main() אסינכרונית רק יוצרת אובייקט. מריצים עם asyncio.run(main()).AssertionError: got coroutine: ...: calling an async main() only creates an object. Run it with asyncio.run(main()).06Crystal Quest: הגרסה המלאהCrystal Quest: the full version
החלק השני של Crystal Quest מחבר הכול: רוחות שמסיירות, רודפות וחוזרות (הצבע מראה את המצב), קריסטלים שמתפוצצים לחלקיקים כשאוספים אותם, ופגיעה שמורידה חיים ונותנת שנייה של חסינות עם הבהוב. כאן השחקן הולך במסלול; במחשב שלכם הוסיפו את המלאי, החדרים והשמירה מהשיעור הקודם ומהיום, ופרסמו:
Crystal Quest part two connects it all: ghosts that patrol, chase and return (the colour shows the state), crystals that burst into particles when collected, and a hit that costs health and gives a second of invulnerability with a flash. Here the player walks a route; on your computer, add the inventory, rooms and saving from last lesson and today, and publish:
import math
import random
import pygame
ROOM = [
"####################",
"#..................#",
"#..c.....g.........#",
"#..........##......#",
"#..........##...c..#",
"#..................#",
"#....##............#",
"#....##.....g......#",
"#.........c........#",
"#..................#",
"####################",
]
T = 16
random.seed(7)
pygame.init()
screen = pygame.display.set_mode((20 * T, 11 * T + 22))
font = pygame.font.Font(None, 20)
walls = [pygame.Rect(c * T, r * T, T, T) for r, row in enumerate(ROOM) for c, ch in enumerate(row) if ch == "#"]
crystals = [pygame.Vector2(c * T + 8, r * T + 8) for r, row in enumerate(ROOM) for c, ch in enumerate(row) if ch == "c"]
ghosts = [{"home": pygame.Vector2(c * T + 8, r * T + 8), "pos": pygame.Vector2(c * T + 8, r * T + 8), "state": "patrol", "t": 0.0}
for r, row in enumerate(ROOM) for c, ch in enumerate(row) if ch == "g"]
player = pygame.Vector2(2 * T, 9 * T)
particles, hp, got, hurt_timer = [], 3, 0, 0
route = [pygame.Vector2(p) for p in [(56, 40), (56, 136), (168, 136), (264, 72), (264, 104)]]
for frame in range(700):
if route and player.distance_to(route[0]) < 2:
route.pop(0)
if not route:
break
step = route[0] - player
player += step.normalize() * 1.5
for g in ghosts:
d = g["pos"].distance_to(player)
if g["state"] == "patrol":
g["t"] += 0.03
g["pos"] = g["home"] + pygame.Vector2(math.cos(g["t"]) * 24, math.sin(g["t"] * 2) * 10)
if d < 60:
g["state"] = "chase"
elif g["state"] == "chase":
g["pos"] += (player - g["pos"]).normalize() * 0.9
if d > 90:
g["state"] = "return"
else:
back = g["home"] - g["pos"]
if back.length() < 2:
g["state"] = "patrol"
else:
g["pos"] += back.normalize() * 1.2
if d < 10 and hurt_timer == 0:
hp, hurt_timer = hp - 1, 60
hurt_timer = max(0, hurt_timer - 1)
for c in crystals[:]:
if player.distance_to(c) < 10:
crystals.remove(c)
got += 1
for _ in range(24):
angle, speed = random.uniform(0, math.tau), random.uniform(0.5, 2.5)
particles.append([pygame.Vector2(c), pygame.Vector2(math.cos(angle), math.sin(angle)) * speed, 40])
for p in particles[:]:
p[0] += p[1]
p[1] *= 0.95
p[2] -= 1
if p[2] <= 0:
particles.remove(p)
screen.fill((16, 14, 30))
for w in walls:
pygame.draw.rect(screen, (70, 60, 110), w)
for c in crystals:
pygame.draw.polygon(screen, (120, 230, 255), [(c.x, c.y - 6), (c.x + 6, c.y), (c.x, c.y + 6), (c.x - 6, c.y)])
for pos, _, life in particles:
shade = 120 + life * 3
pygame.draw.circle(screen, (shade // 2, shade, 255), pos, 2)
for g in ghosts:
color = {"patrol": (150, 150, 200), "chase": (255, 90, 120), "return": (200, 160, 90)}[g["state"]]
pygame.draw.circle(screen, color, g["pos"], 7)
if hurt_timer % 10 < 5:
pygame.draw.rect(screen, (250, 250, 250), (player.x - 6, player.y - 6, 12, 12), border_radius=3)
states = " ".join(g["state"] for g in ghosts)
screen.blit(font.render(f"HP {hp} Crystals {got}/3 Ghosts: {states}", True, (230, 230, 240)), (6, 11 * T + 4))
pygame.display.flip()
print("hp:", hp, "crystals:", got, "ghosts:", [g["state"] for g in ghosts], "particles alive:", len(particles))
pygame.quit()hp: 2 crystals: 3 ghosts: ['patrol', 'chase'] particles alive: 24
משחק גמור הוא לא רעיון גדול אחד אלא מאה רעיונות קטנים שעובדים יחד. כל מה שבניתם בחלק הזה הוא אחד מהם.
A finished game isn't one big idea but a hundred small ones working together. Everything you built in this part is one of them.
מנרמלים וקטור אפס כשהרוח כבר על השחקן.
Normalising a zero vector when the ghost is already on the player.
import pygame
ghost, player = pygame.Vector2(50, 50), pygame.Vector2(50, 50)
ghost += (player - ghost).normalize() * 0.9Traceback (most recent call last):
File "/Users/you/python-course/crystal_quest.py", line 3, in <module>
ghost += (player - ghost).normalize() * 0.9
~~~~~~~~~~~~~~~~~~~~~~~~~~^^
ValueError: Can't normalize Vector of length zeroValueError: Can't normalize Vector of length zero: בודקים שהמרחק גדול מאפס לפני הנרמול, או משתמשים ב-move_towards.ValueError: Can't normalize Vector of length zero: check the distance is above zero before normalising, or use move_towards.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.