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.
מכונת מצבים לרוחA ghost state machine
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def next_state(state, player_d, home_d, see=60, lose=90):
if state == "patrol" and player_d < see:
return "chase"
if state == "chase" and player_d > lose:
return "return"
if state == "return":
if player_d < see:
return "chase"
if home_d < 2:
return "patrol"
return state
state, trail = "patrol", []
for pd, hd in [(100, 0), (50, 5), (80, 30), (95, 40), (70, 20), (55, 10), (120, 0)]:
state = next_state(state, pd, hd)
trail.append(state[0])
print("".join(trail))pccrrcr
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שמירה בטוחהSafe saving
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
import json
from pathlib import Path
def save(state, path):
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(state), encoding="utf-8")
tmp.replace(path)
def load(path, default):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return dict(default), "new"
except json.JSONDecodeError:
return dict(default), "damaged"
if not isinstance(data, dict):
return dict(default), "damaged"
return {**default, **data}, "ok"
DEFAULT = {"room": "hall", "hp": 3}
p = Path("game.json")
print(load(p, DEFAULT)[1])
save({"hp": 1, "room": "cave", "bag": {"key": 1}}, p)
print(load(p, DEFAULT), p.with_suffix(".tmp").exists())
p.write_text("[1, 2]")
print(load(p, DEFAULT)[1], DEFAULT)new
({'room': 'cave', 'hp': 1, 'bag': {'key': 1}}, 'ok') False
damaged {'room': 'hall', 'hp': 3}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מערכת חלקיקיםA particle system
תזכורת: מה ביקשוReminder: the task
בלי 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.
הפתרון המלא והפלט שלוFull solution and its output
import math
import random
class Particles:
def __init__(self, friction=0.95):
self.friction, self.items = friction, []
def burst(self, x, y, n, speed, life, rng):
for _ in range(n):
a = rng.uniform(0, math.tau)
self.items.append([x, y, math.cos(a) * speed, math.sin(a) * speed, life])
def update(self):
for p in self.items:
p[0] += p[2]
p[1] += p[3]
p[2] *= self.friction
p[3] *= self.friction
p[4] -= 1
self.items = [p for p in self.items if p[4] > 0]
return len(self.items)
ps = Particles()
ps.burst(100, 100, 30, 2, 20, random.Random(1))
ps.burst(50, 50, 10, 1, 5, random.Random(2))
counts = [ps.update() for _ in range(21)]
print(counts[0], counts[3], counts[4], counts[18], counts[19])
ps.burst(0, 0, 1, 2, 3, random.Random(0))
ps.update()
print(round(math.hypot(ps.items[0][0], ps.items[0][1]), 2), round(math.hypot(ps.items[0][2], ps.items[0][3]), 3))40 40 30 30 0 2.0 1.9
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טוען נכסיםAn asset loader
תזכורת: מה ביקשוReminder: the task
בלי 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.
הפתרון המלא והפלט שלוFull solution and its output
from pathlib import Path
class Assets:
def __init__(self, folder):
self.folder = Path(folder)
self.cache, self.missing, self.reads = {}, set(), 0
def get(self, name):
if name not in self.cache:
path = self.folder / name
if path.exists():
self.cache[name] = path.read_text(encoding="utf-8")
self.reads += 1
else:
self.cache[name] = f"<missing:{name}>"
self.missing.add(name)
return self.cache[name]
def report(self):
return sorted(self.missing)
folder = Path("assets")
folder.mkdir(exist_ok=True)
(folder / "level1.txt").write_text("####\n#..#\n####", encoding="utf-8")
a = Assets(folder)
for name in ["level1.txt", "level1.txt", "hero.png", "jump.wav", "hero.png"]:
print(name, "->", a.get(name).splitlines()[0])
print(a.reads, a.report())level1.txt -> #### level1.txt -> #### hero.png -> <missing:hero.png> jump.wav -> <missing:jump.wav> hero.png -> <missing:hero.png> 1 ['hero.png', 'jump.wav']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Crystal Quest: שמירה של משחק שלםCrystal Quest: saving a whole game
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה 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.
הפתרון המלא והפלט שלוFull solution and its output
import json
from dataclasses import dataclass, field
@dataclass
class Quest:
room: str = "hall"
pos: tuple = (2, 9)
hp: int = 3
bag: dict = field(default_factory=dict)
ghosts: list = field(default_factory=list)
opened: set = field(default_factory=set)
def to_dict(self):
return {
"room": self.room, "pos": list(self.pos), "hp": self.hp, "bag": dict(self.bag),
"ghosts": [{"pos": list(g["pos"]), "state": g["state"]} for g in self.ghosts],
"opened": sorted(list(d) for d in self.opened),
}
@classmethod
def from_dict(cls, d):
return cls(
room=d["room"], pos=tuple(d["pos"]), hp=d["hp"], bag=dict(d["bag"]),
ghosts=[{"pos": tuple(g["pos"]), "state": g["state"]} for g in d["ghosts"]],
opened={tuple(x) for x in d["opened"]},
)
q = Quest(room="cave", pos=(4, 2), hp=2, bag={"crystal": 2, "key": 0},
ghosts=[{"pos": (120, 40), "state": "chase"}], opened={("hall", 19, 5)})
text = json.dumps(q.to_dict())
back = Quest.from_dict(json.loads(text))
print(back == q, back.pos, back.opened)
print(text)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]]}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
קו ראייהLine of sight
תזכורת: מה ביקשוReminder: the task
רוח צריכה לרדוף רק אם היא רואה את השחקן. כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def can_see(grid, a, b):
(ac, ar), (bc, br) = a, b
n = max(abs(bc - ac), abs(br - ar))
for i in range(n + 1):
t = i / n if n else 0
c, r = round(ac + (bc - ac) * t), round(ar + (br - ar) * t)
if grid[r][c] == "#":
return False
return True
GRID = ["##########", "#........#", "#...##...#", "#...##...#", "#........#", "##########"]
print(can_see(GRID, (1, 1), (8, 1)), can_see(GRID, (1, 2), (8, 3)), can_see(GRID, (2, 4), (7, 1)), can_see(GRID, (3, 3), (3, 3)))True False False True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טבלת שיאיםA high-score table
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
import json
from pathlib import Path
def add_score(path, name, score, keep=5):
try:
table = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError):
table = []
entry = [name, score]
table = sorted(table + [entry], key=lambda e: -e[1])[:keep]
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(table), encoding="utf-8")
tmp.replace(path)
for place, e in enumerate(table, start=1):
if e is entry:
return place
return None
p = Path("scores.json")
places = [add_score(p, n, s, keep=3) for n, s in [("Noa", 120), ("Ari", 300), ("Dan", 120), ("Lia", 50), ("Tom", 500)]]
print(places, json.loads(p.read_text()))[1, 1, 3, None, 1] [['Tom', 500], ['Ari', 300], ['Noa', 120]]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.