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

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

Crystal Quest, חלק 1Crystal Quest, part 1

משחק הרפתקאות: עולם מאריחים, גיבור מונפש, מצלמה, דיאלוגים ושערים.

An adventure game: a tile world, an animated hero, a camera, dialogue and gates.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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 does each screen become a class (scene)?

2. מה קורה בלי נרמול כשלוחצים ימינה ולמטה?What happens without normalising when pressing right and down?

3. איך מונעים KeyError כשבודקים פריט במלאי?How do you avoid a KeyError when checking an inventory item?

תרגיליםExercises

תרגילExercise 1

מנהל סצנותA scene manager

כתבו מחלקה Game עם scene (שם המסך, מתחיל ב-"title") ו-history (רשימה). change(name) מעבירה מסך ושומרת את הקודם בהיסטוריה. back() חוזרת למסך הקודם (אם אין, נשארת). update(key): מ-title עם "enter" ל-play; מ-play עם "esc" ל-pause; מ-pause עם "esc" חוזרים (back).

Write a Game class with scene (the screen's name, starting at "title") and history (a list). change(name) switches screen and pushes the previous one onto the history. back() returns to the previous screen (if none, stays). update(key): from title with "enter" to play; from play with "esc" to pause; from pause with "esc" go back.

איך הפלט אמור להיראות?What should the output look like?
['title', 'play', 'pause', 'play', 'pause', 'play'] ['title']
main.py
רמזHint 1: מילון מעברים: {("title", "enter"): "play", ...}.A transitions dict: {("title", "enter"): "play", ...}.
רמזHint 2: history.pop().history.pop().
לפתרוןSolution
תרגילExercise 2

כיוון מנורמלA normalised direction

בלי pygame: כתבו direction(keys, speed) שמקבלת set של מקשים (up/down/left/right) ומחזירה (dx, dy) באורך speed (מעוגל ל-2 ספרות), או (0, 0) אם אין תנועה. מקשים מנוגדים מבטלים זה את זה.

Without pygame: write direction(keys, speed) taking a set of keys (up/down/left/right) and returning (dx, dy) of length speed (rounded to 2 decimals), or (0, 0) with no movement. Opposite keys cancel out.

איך הפלט אמור להיראות?What should the output look like?
(2.0, 0.0) (1.41, 1.41) (0, 0) (0.0, -3.0)
main.py
רמזHint 1: x = ("right" in keys) - ("left" in keys).x = ("right" in keys) - ("left" in keys).
רמזHint 2: length = math.hypot(x, y).length = math.hypot(x, y).
לפתרוןSolution
תרגילExercise 3

מפת חדריםA room map

כתבו check_world(rooms, doors) כש-rooms מילון שם → רשימת מחרוזות ו-doors מילון (room, mark) → (target, (col, row)). מחזירה רשימת בעיות ממוינת: "missing room X" אם target לא קיים, "blocked spawn X (c, r)" אם המשבצת אינה ., ו-"unreachable X" לכל חדר (חוץ מהראשון ב-rooms) שאי אפשר להגיע אליו מהחדר הראשון דרך דלתות.

Write check_world(rooms, doors) where rooms is a dict name → list of strings and doors a dict (room, mark) → (target, (col, row)). Return a sorted list of problems: "missing room X" if a target doesn't exist, "blocked spawn X (c, r)" if the cell isn't ., and "unreachable X" for each room (other than the first in rooms) you can't reach from the first room via doors.

איך הפלט אמור להיראות?What should the output look like?
['blocked spawn crypt (0, 1)', 'missing room tower', 'unreachable vault']
main.py
רמזHint 1: הנגישות היא BFS/DFS על גרף החדרים.Reachability is a BFS/DFS on the room graph.
רמזHint 2: החדר הראשון: next(iter(rooms)).The first room: next(iter(rooms)).
לפתרוןSolution
תרגילExercise 4

דיאלוג עם תנאיםConditional dialogue

כתבו talk(lines, bag, flags) כש-lines רשימת מילונים עם text, ואופציונלית need (מילון פריטים ומינימום), flag (דגל שחייב להיות ב-flags) ו-set (דגל להוסיף ל-flags אחרי שאמרו את השורה). מחזירה את הטקסט של השורה הראשונה שכל התנאים שלה מתקיימים (ומוסיפה את set אם יש), או "..." אם אין.

Write talk(lines, bag, flags) where lines is a list of dicts with text, and optionally need (a dict of items and minimums), flag (a flag that must be in flags) and set (a flag to add to flags after the line is said). Return the text of the first line whose conditions all hold (adding set if present), or "..." if none.

איך הפלט אמור להיראות?What should the output look like?
['Find three crystals.', 'Still looking?', 'You did it!'] ['done', 'quest'] ...
main.py
רמזHint 1: line.get("need", {}).line.get("need", {}).
רמזHint 2: flags הוא set: flags.add(...).flags is a set: flags.add(...).
לפתרוןSolution
תרגילExercise 5

Crystal Quest: עולםCrystal Quest: the world

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

כתבו מחלקה World(rooms, doors, start_room, start_cell) בלי pygame, עם room, pos (עמודה, שורה), bag (מילון), message. step(direction) ("up"/"down"/"left"/"right") מזיזה משבצת אחת אם אינה #. על c או k אוספים (crystal/key) והמשבצת הופכת ל-.. על L (דלת נעולה): נכנסים רק עם מפתח, והוא נצרך והמשבצת הופכת ל-.; אחרת message = "Locked" ונשארים. על משבצת שיש לה רשומה ב-doors עוברים חדר. שימו לב: אל תשנו את המחרוזות המקוריות, עבדו על עותק של רשימות.

Write a World(rooms, doors, start_room, start_cell) class without pygame, with room, pos (column, row), bag (a dict), message. step(direction) ("up"/"down"/"left"/"right") moves one cell if it isn't #. On c or k collect (crystal/key) and the cell becomes .. On L (a locked door): enter only with a key, which is used up and the cell becomes .; otherwise message = "Locked" and stay. On a cell with an entry in doors, switch rooms. Note: don't change the original strings; work on a copy of lists.

איך הפלט אמור להיראות?What should the output look like?
cave (3, 1) {'key': 0, 'crystal': 1} #....L
world.py
רמזHint 1: עותק: {name: [list(row) for row in rows] for name, rows in rooms.items()}.A copy: {name: [list(row) for row in rows] for name, rows in rooms.items()}.
רמזHint 2: doors: (room, (c, r)) → (target, (c, r)).doors: (room, (c, r)) → (target, (c, r)).
לפתרוןSolution

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

אתגרChallenge 1

מסלול קצר לקריסטלThe shortest path to a crystal

כתבו path_to(grid, start, goal_char) שמחזירה רשימת כיוונים ("up" וכו') של המסלול הקצר ביותר מ-start (עמודה, שורה) למשבצת הקרובה ביותר עם goal_char, בלי לעבור דרך #. אם אין, None. השתמשו ב-BFS ושמרו לכל משבצת מאיפה הגעתם. סדר בדיקת שכנים: up, down, left, right.

Write path_to(grid, start, goal_char) returning a list of directions ("up" etc.) for the shortest path from start (column, row) to the nearest cell holding goal_char, never through #. If none, None. Use BFS and keep, for each cell, where you came from. Neighbour order: up, down, left, right.

איך הפלט אמור להיראות?What should the output look like?
['down', 'down', 'right', 'right', 'right', 'up']
None
main.py
רמזHint 1: came = {start: None} ומילון כיוונים.came = {start: None} and a directions dict.
רמזHint 2: בסוף הולכים אחורה מהמטרה ומהפכים.At the end, walk back from the goal and reverse.
לפתרוןSolution
אתגרChallenge 2

מצב שמור כמחרוזתState as a save code

משחקים ישנים נתנו "קוד" להמשך. כתבו encode(room_index, pos, bag) שמחזירה מחרוזת של 6 תווים הקסדצימליים: חדר (תו אחד), עמודה ושורה (תו לכל אחד), קריסטלים ומפתחות (תו לכל אחד), וספרת ביקורת אחרונה = סכום חמשת הערכים מודולו 16. decode(code) מחזירה (room_index, (c, r), {"crystal": n, "key": m}), או זורקת ValueError("bad code") אם ספרת הביקורת לא מתאימה או שהקוד אינו באורך 6.

Old games gave a "password" to continue. Write encode(room_index, pos, bag) returning a 6-character hex string: room (one char), column and row (one each), crystals and keys (one each), and a final check digit = the sum of the five values modulo 16. decode(code) returns (room_index, (c, r), {"crystal": n, "key": m}), or raises ValueError("bad code") if the check digit doesn't match or the code isn't 6 long.

איך הפלט אמור להיראות?What should the output look like?
259314 (2, (5, 9), {'crystal': 3, 'key': 1})
rejected: bad code
main.py
רמזHint 1: format(n, "x") נותן תו הקס; int(ch, 16) מחזיר.format(n, "x") gives a hex char; int(ch, 16) goes back.
רמזHint 2: כל ערך בין 0 ל-15.Every value is 0 to 15.
לפתרוןSolution

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