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

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

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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. למה טווח היציאה מהמרדף גדול מטווח הכניסה?Why is the chase exit range bigger than the entry range?

2. למה כותבים שמירה לקובץ זמני ואז מחליפים?Why write a save to a temp file and then replace?

3. מה pygbag דורש בלולאה הראשית?What does pygbag need in the main loop?

תרגיליםExercises

תרגילExercise 1

מכונת מצבים לרוחA ghost state machine

כתבו next_state(state, player_d, home_d, see=60, lose=90): מ-"patrol" ל-"chase" כש-player_d < see; מ-"chase" ל-"return" כש-player_d > lose; מ-"return" ל-"chase" כש-player_d < see, אחרת ל-"patrol" כש-home_d < 2. אחרת נשארים.

Write next_state(state, player_d, home_d, see=60, lose=90): from "patrol" to "chase" when player_d < see; from "chase" to "return" when player_d > lose; from "return" to "chase" when player_d < see, otherwise to "patrol" when home_d < 2. Otherwise stay.

איך הפלט אמור להיראות?What should the output look like?
pccrrcr
main.py
רמזHint 1: if לכל מצב.An if per state.
רמזHint 2: שימו לב לסדר ב-return: מרדף קודם.Mind the order in return: chase first.
לפתרוןSolution
תרגילExercise 2

שמירה בטוחהSafe saving

כתבו save(state, path) (דרך קובץ .tmp ו-replace) ו-load(path, default) שמחזירה (state, status): "new" אם אין קובץ, "damaged" אם ה-JSON שבור או שאינו מילון, אחרת "ok" עם מילון שממזג את default עם מה שנטען (מפתחות חסרים מקבלים ערך ברירת מחדל). אל תשנו את default.

Write save(state, path) (via a .tmp file and replace) and load(path, default) returning (state, status): "new" if there's no file, "damaged" if the JSON is broken or isn't a dict, otherwise "ok" with a dict merging default with what was loaded (missing keys get the default). Don't modify default.

איך הפלט אמור להיראות?What should the output look like?
new
({'room': 'cave', 'hp': 1, 'bag': {'key': 1}}, 'ok') False
damaged {'room': 'hall', 'hp': 3}
main.py
רמזHint 1: {**default, **data} יוצר מילון חדש.{**default, **data} creates a new dict.
רמזHint 2: isinstance(data, dict).isinstance(data, dict).
לפתרוןSolution
תרגילExercise 3

מערכת חלקיקיםA particle system

בלי pygame: כתבו מחלקה Particles(friction=0.95) עם רשימה items של [x, y, vx, vy, life]. burst(x, y, n, speed, life, rng) מוסיפה n חלקיקים בזוויות rng.uniform(0, math.tau) ומהירות speed. update() מזיזה כל חלקיק, מכפילה מהירות בחיכוך, מורידה חיים, ומוחקת חלקיקים עם חיים 0. מחזירה את מספר החלקיקים החיים.

Without pygame: write a Particles(friction=0.95) class with an items list of [x, y, vx, vy, life]. burst(x, y, n, speed, life, rng) adds n particles at angles rng.uniform(0, math.tau) with speed speed. update() moves each particle, multiplies velocity by friction, lowers life, and deletes particles at 0 life. It returns the number alive.

איך הפלט אמור להיראות?What should the output look like?
40 40 30 30 0
2.0 1.9
main.py
רמזHint 1: rng הוא random.Random(seed), לתוצאות קבועות.rng is a random.Random(seed), for repeatable results.
רמזHint 2: בנו רשימה חדשה של החיים במקום למחוק תוך כדי לולאה.Build a new list of the living instead of deleting while looping.
לפתרוןSolution
תרגילExercise 4

טוען נכסיםAn asset loader

בלי pygame: כתבו מחלקה Assets(folder) עם get(name): אם הקובץ folder / name קיים, מחזירה את התוכן שלו (טקסט); אחרת מחזירה "<missing:NAME>" ומוסיפה את השם ל-missing (set). התוצאות נשמרות במטמון: קריאה שנייה לא קוראת את הקובץ שוב (ספרו קריאות ב-reads). report() מחזירה רשימה ממוינת של החסרים.

Without pygame: write an Assets(folder) class with get(name): if folder / name exists, return its content (text); otherwise return "<missing:NAME>" and add the name to missing (a set). Results are cached: a second call doesn't read the file again (count reads in reads). report() returns a sorted list of the missing.

איך הפלט אמור להיראות?What should the output look like?
level1.txt -> ####
level1.txt -> ####
hero.png -> <missing:hero.png>
jump.wav -> <missing:jump.wav>
hero.png -> <missing:hero.png>
1 ['hero.png', 'jump.wav']
main.py
רמזHint 1: self.cache = {}.self.cache = {}.
רמזHint 2: Path(folder) / name.Path(folder) / name.
לפתרוןSolution
תרגילExercise 5

Crystal Quest: שמירה של משחק שלםCrystal Quest: saving a whole game

פרויקט מלווהCompanion project

כתבו מחלקה Quest עם room, pos (טאפל), hp, bag (מילון), ghosts (רשימת מילונים עם pos טאפל ו-state) ו-opened (set של דלתות שנפתחו, כל אחת טאפל (room, c, r)). to_dict() מחזירה מילון שאפשר לשמור ב-JSON (טאפלים לרשימות, set לרשימה ממוינת של רשימות), ו-Quest.from_dict(d) (classmethod) בונה אובייקט שווה. הגדירו __eq__ שמשווה את כל השדות, כך ש-Quest.from_dict(json.loads(json.dumps(q.to_dict()))) == q.

Write a Quest class with room, pos (a tuple), hp, bag (a dict), ghosts (a list of dicts with a pos tuple and state) and opened (a set of opened doors, each a (room, c, r) tuple). to_dict() returns a dict JSON can store (tuples to lists, the set to a sorted list of lists), and Quest.from_dict(d) (a classmethod) builds an equal object. Define __eq__ comparing every field, so that Quest.from_dict(json.loads(json.dumps(q.to_dict()))) == q.

איך הפלט אמור להיראות?What should the output look like?
True (4, 2) {('hall', 19, 5)}
{"room": "cave", "pos": [4, 2], "hp": 2, "bag": {"crystal": 2, "key": 0}, "ghosts": [{"pos": [120, 40], "state": "chase"}], "opened": [["hall", 19, 5]]}
quest_save.py
רמזHint 1: JSON הופך טאפלים לרשימות, אז ב-from_dict ממירים בחזרה עם tuple(...).JSON turns tuples into lists, so in from_dict convert back with tuple(...).
רמזHint 2: השתמשו ב-@dataclass עם field(default_factory=...) כדי לקבל __eq__ בחינם.Use @dataclass with field(default_factory=...) to get __eq__ for free.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

קו ראייהLine of sight

רוח צריכה לרדוף רק אם היא רואה את השחקן. כתבו can_see(grid, a, b) שבודקת אם הקו בין המשבצות a ו-b (עמודה, שורה) לא עובר דרך #. דגמו n = max(|dx|, |dy|) נקודות לאורך הקו (כולל הקצוות), עגלו כל אחת למשבצת (round), ובדקו שאף אחת אינה קיר.

A ghost should chase only if it can see the player. Write can_see(grid, a, b) checking whether the line between cells a and b (column, row) passes through no #. Sample n = max(|dx|, |dy|) points along the line (including the ends), round each to a cell (round), and check none is a wall.

איך הפלט אמור להיראות?What should the output look like?
True False False True
main.py
רמזHint 1: נקודה i: a + (b - a) * i / n.Point i: a + (b - a) * i / n.
רמזHint 2: אם n == 0, a == b, ורואים.If n == 0, a == b, and it's visible.
לפתרוןSolution
אתגרChallenge 2

טבלת שיאיםA high-score table

כתבו add_score(path, name, score, keep=5) ששומרת טבלת שיאים בקובץ JSON (רשימת [name, score]): טוענת (קובץ חסר או פגום = רשימה ריקה), מוסיפה, ממיינת מהגבוה לנמוך (בתיקו, הוותיק קודם), שומרת רק keep ראשונים (דרך קובץ זמני) ומחזירה את המקום של הניקוד החדש (1 והלאה) או None אם לא נכנס.

Write add_score(path, name, score, keep=5) keeping a high-score table in a JSON file (a list of [name, score]): load it (missing or broken file = an empty list), add, sort high to low (on a tie, the older first), keep only the first keep (via a temp file) and return the new score's place (1 onwards), or None if it didn't make it.

איך הפלט אמור להיראות?What should the output look like?
[1, 1, 3, None, 1] [['Tom', 500], ['Ari', 300], ['Noa', 120]]
main.py
רמזHint 1: sorted יציב, אז key=lambda e: -e[1] שומר את הוותיק קודם.sorted is stable, so key=lambda e: -e[1] keeps the older first.
רמזHint 2: זהו את הרשומה החדשה לפי זהות (is), לא לפי ערך.Identify the new entry by identity (is), not by value.
לפתרוןSolution

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