Crystal Quest, חלק 1Crystal Quest, part 1
משחק הרפתקאות: עולם מאריחים, גיבור מונפש, מצלמה, דיאלוגים ושערים.
An adventure game: a tile world, an animated hero, a camera, dialogue and gates.
מנהל סצנותA scene manager
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה 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.
הפתרון המלא והפלט שלוFull solution and its output
class Game:
MOVES = {("title", "enter"): "play", ("play", "esc"): "pause"}
def __init__(self):
self.scene, self.history = "title", []
def change(self, name):
self.history.append(self.scene)
self.scene = name
def back(self):
if self.history:
self.scene = self.history.pop()
def update(self, key):
if (self.scene, key) == ("pause", "esc"):
self.back()
elif (self.scene, key) in self.MOVES:
self.change(self.MOVES[(self.scene, key)])
g = Game()
seen = []
for key in ["x", "enter", "esc", "esc", "esc", "esc"]:
g.update(key)
seen.append(g.scene)
print(seen, g.history)['title', 'play', 'pause', 'play', 'pause', 'play'] ['title']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
כיוון מנורמלA normalised direction
תזכורת: מה ביקשוReminder: the task
בלי 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.
הפתרון המלא והפלט שלוFull solution and its output
import math
def direction(keys, speed):
x = ("right" in keys) - ("left" in keys)
y = ("down" in keys) - ("up" in keys)
length = math.hypot(x, y)
if not length:
return (0, 0)
return (round(x / length * speed, 2), round(y / length * speed, 2))
print(direction({"right"}, 2), direction({"right", "down"}, 2), direction({"up", "down"}, 2), direction({"left", "up", "right"}, 3))(2.0, 0.0) (1.41, 1.41) (0, 0) (0.0, -3.0)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מפת חדריםA room map
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def check_world(rooms, doors):
problems = []
for (room, mark), (target, (c, r)) in doors.items():
if target not in rooms:
problems.append(f"missing room {target}")
elif rooms[target][r][c] != ".":
problems.append(f"blocked spawn {target} ({c}, {r})")
start = next(iter(rooms))
seen, stack = {start}, [start]
while stack:
room = stack.pop()
for (src, _), (target, _) in doors.items():
if src == room and target in rooms and target not in seen:
seen.add(target)
stack.append(target)
problems += [f"unreachable {name}" for name in rooms if name not in seen]
return sorted(problems)
ROOMS = {"hall": ["#####", "#...D", "#####"], "cave": ["#####", "D...#", "##E##"], "crypt": ["##D##", "#...#", "#####"], "vault": ["#..#"]}
DOORS = {("hall", "D"): ("cave", (1, 1)), ("cave", "D"): ("hall", (3, 1)), ("cave", "E"): ("crypt", (0, 1)), ("crypt", "D"): ("tower", (2, 1))}
print(check_world(ROOMS, DOORS))['blocked spawn crypt (0, 1)', 'missing room tower', 'unreachable vault']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
דיאלוג עם תנאיםConditional dialogue
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def talk(lines, bag, flags):
for line in lines:
has_items = all(bag.get(item, 0) >= n for item, n in line.get("need", {}).items())
has_flag = line.get("flag") is None or line["flag"] in flags
if has_items and has_flag:
if "set" in line:
flags.add(line["set"])
return line["text"]
return "..."
SAGE = [
{"flag": "quest", "need": {"crystal": 3}, "text": "You did it!", "set": "done"},
{"flag": "quest", "text": "Still looking?"},
{"text": "Find three crystals.", "set": "quest"},
]
bag, flags = {}, set()
said = [talk(SAGE, bag, flags), talk(SAGE, bag, flags)]
bag["crystal"] = 3
said.append(talk(SAGE, bag, flags))
print(said, sorted(flags), talk([], bag, flags))['Find three crystals.', 'Still looking?', 'You did it!'] ['done', 'quest'] ...
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Crystal Quest: עולםCrystal Quest: the world
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה 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.
הפתרון המלא והפלט שלוFull solution and its output
class World:
STEPS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}
ITEMS = {"c": "crystal", "k": "key"}
def __init__(self, rooms, doors, start_room, start_cell):
self.rooms = {name: [list(row) for row in rows] for name, rows in rooms.items()}
self.doors = doors
self.room, self.pos = start_room, start_cell
self.bag, self.message = {}, ""
def step(self, direction):
dc, dr = self.STEPS[direction]
c, r = self.pos[0] + dc, self.pos[1] + dr
grid = self.rooms[self.room]
tile = grid[r][c]
if tile == "#":
return
if tile == "L":
if self.bag.get("key", 0) < 1:
self.message = "Locked"
return
self.bag["key"] -= 1
grid[r][c] = "."
if tile in self.ITEMS:
item = self.ITEMS[tile]
self.bag[item] = self.bag.get(item, 0) + 1
grid[r][c] = "."
self.message = f"Got a {item}"
self.pos = (c, r)
if (self.room, self.pos) in self.doors:
self.room, self.pos = self.doors[(self.room, self.pos)]
ROOMS = {"hall": ["######", "#.c.k#", "#....L", "######"], "cave": ["#####", "..c.#", "#####"]}
DOORS = {("hall", (5, 2)): ("cave", (1, 1)), ("cave", (0, 1)): ("hall", (4, 2))}
w = World(ROOMS, DOORS, "hall", (1, 2))
for d in ["right", "right", "right", "right", "up", "down", "right", "right", "right"]:
w.step(d)
print(w.room, w.pos, w.bag, ROOMS["hall"][2])cave (3, 1) {'key': 0, 'crystal': 1} #....Lיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מסלול קצר לקריסטלThe shortest path to a crystal
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from collections import deque
STEPS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}
def path_to(grid, start, goal_char):
came = {start: None}
queue = deque([start])
while queue:
c, r = queue.popleft()
if grid[r][c] == goal_char:
moves, cell = [], (c, r)
while came[cell]:
cell, move = came[cell]
moves.append(move)
return moves[::-1]
for name, (dc, dr) in STEPS.items():
nxt = (c + dc, r + dr)
if nxt not in came and grid[nxt[1]][nxt[0]] != "#":
came[nxt] = ((c, r), name)
queue.append(nxt)
return None
GRID = ["#######", "#..#..#", "#..#c.#", "#.....#", "#######"]
print(path_to(GRID, (1, 1), "c"))
print(path_to(GRID, (1, 1), "z"))['down', 'down', 'right', 'right', 'right', 'up'] None
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מצב שמור כמחרוזתState as a save code
תזכורת: מה ביקשוReminder: the task
משחקים ישנים נתנו "קוד" להמשך. כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def encode(room_index, pos, bag):
values = [room_index, pos[0], pos[1], bag.get("crystal", 0), bag.get("key", 0)]
values.append(sum(values) % 16)
return "".join(format(v, "x") for v in values)
def decode(code):
if len(code) != 6:
raise ValueError("bad code")
values = [int(ch, 16) for ch in code]
if sum(values[:5]) % 16 != values[5]:
raise ValueError("bad code")
room, c, r, crystals, keys, _ = values
return room, (c, r), {"crystal": crystals, "key": keys}
code = encode(2, (5, 9), {"crystal": 3, "key": 1})
print(code, decode(code))
try:
decode("2593a1")
except ValueError as e:
print("rejected:", e)259314 (2, (5, 9), {'crystal': 3, 'key': 1})
rejected: bad codeיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.