חלק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.
הנקודות החשובותKey points
settings.py: קבועיםsettings.py: constantsscenes.py: מסכיםscenes.py: screens- סצנה = מחלקה עם update ו-drawA scene = a class with update and draw
game.change(new_scene)game.change(new_scene)- מבט על: אין כבידהTop-down: no gravity
- אלכסון מהיר מדי? מנרמליםDiagonal too fast? Normalise
- כל חדר = מפת אריחים במילוןEach room = a tilemap in a dict
- דלת מובילה לחדר אחר ולנקודת כניסהA door leads to another room and an entry point
- מלאי = מילון ספירותAn inventory = a dict of counts
מונחיםTerms
- סצנהscene: מסך אחד במשחק (תפריט, משחק, סיום) עם update ו-draw משלו. המשחק מחזיק סצנה נוכחית ומחליף אותה.One screen of a game (menu, play, ending) with its own update and draw. The game holds a current scene and swaps it.
- מודול משחקgame module: קובץ אחד שאחראי על חלק אחד: הגדרות, דמויות, סצנות. main.py רק מחבר ביניהם.One file responsible for one part: settings, characters, scenes. main.py just connects them.
- מלאיinventory: מבנה נתונים (בדרך כלל מילון) שסופר מה השחקן אוסף: מפתחות, קריסטלים, שיקויים.A data structure (usually a dict) counting what the player collects: keys, crystals, potions.
- מבט עלtop-down: משחק שבו המצלמה מסתכלת מלמעלה. אין כבידה, וזזים בארבעה (או שמונה) כיוונים.A game where the camera looks from above. No gravity, and you move in four (or eight) directions.
- דיאלוגdialogue: רצף שורות שדמות אומרת, לפעמים עם בחירות. נוח לשמור כנתונים ולא כקוד.A sequence of lines a character says, sometimes with choices. Best kept as data, not code.
Cheatsheet
סצנותScenes
class Scene:
def __init__(self, game):
self.game = game
def update(self, key):
pass
תנועהMovement
import pygame
SPEED = 2
for keys in [{"right"}, {"right", "down"}, {"left", "up"}, {"left", "right"}]:
d = pygame.Vector2(("right" in keys) - ("left" in keys), ("down" in keys) - ("up" in keys))
raw = d * SPEED
fixed = d.normalize() * SPEED if d.length() else dחדריםRooms
ROOMS = {"hall": ["#####", "#...D", "#####"], "cave": ["#####", "D...#", "##E##"], "crypt": ["##D##", "#...#", "#####"]}
DOORS = {
("hall", "D"): ("cave", (1, 1)),
("cave", "D"): ("hall", (3, 1)),
("cave", "E"): ("crypt", (2, 1)),
("crypt", "D"): ("cave", (2, 1)),
}מלאיInventory
SAGE = [
({"crystal": 3}, "You found them all. The tower awaits."),
({"key": 1}, "A key! The east door will open for you."),
({}, "Bring me three crystals, traveller."),
]
def talk(lines, inventory):משחקGame
import pygame
ROOMS = {
"hall": [
"####################",
"#..................#",
"#..c.......k.......#",שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
AssertionError | סצנת השהיה שיוצרת משחק חדש במקום לחזור לקיים.A pause scene that creates a new game instead of returning to the existing one. | AssertionError: score reset to 0: ...: שומרים את הסצנה שהושהתה (self.below) וחוזרים אליה.AssertionError: score reset to 0: ...: keep the paused scene (self.below) and return to it. |
ValueError | מנרמלים וקטור אפס כשלא לוחצים על כלום.Normalising a zero vector when nothing is pressed. | ValueError: Can't normalize Vector of length zero: בודקים if d.length(): לפני normalize().ValueError: Can't normalize Vector of length zero: check if d.length(): before normalize(). |
KeyError | דלת שמובילה לחדר שלא קיים.A door leading to a room that doesn't exist. | KeyError: 'caev': שגיאת כתיב בשם החדר. כדאי לבדוק את כל הדלתות פעם אחת בעליית המשחק, כמו בדוגמה למעלה.KeyError: 'caev': a typo in the room name. Check every door once when the game starts, as in the example above. |
KeyError | קוראים ספירה של פריט שעוד לא נאסף.Reading the count of an item not yet collected. | KeyError: 'key': אין עדיין מפתח במילון. משתמשים ב-bag.get("key", 0).KeyError: 'key': there's no key in the dict yet. Use bag.get("key", 0). |
RuntimeError | מוחקים מפריט ממילון בזמן לולאה עליו.Deleting from a dict while looping over it. | RuntimeError: dictionary changed size during iteration: עוברים על עותק (list(items)) או משתמשים ב-items.pop(cell) מחוץ ללולאה, כמו במשחק.RuntimeError: dictionary changed size during iteration: loop over a copy (list(items)) or use items.pop(cell) outside a loop, as in the game. |