נבנה על ידי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.

01פרויקט בכמה קבציםA multi-file project

Crystal Quest הוא הפרויקט הגדול של החלק הזה, ומשחק בגודל כזה לא נכנס בקובץ אחד בנוחות. מפצלים למודולים כמו בפרויקט מדף: settings.py לקבועים (גודל אריח, מהירות), scenes.py למסכים, ו-main.py שמייבא ומריץ. כל קובץ קצר ואפשר להבין אותו לבד:

Crystal Quest is this part's big project, and a game that size doesn't fit comfortably in one file. Split it into modules as in the Shelf project: settings.py for constants (tile size, speed), scenes.py for screens, and main.py that imports and runs. Each file is short and understandable on its own:

Terminal
ls
python3 main.py
פלטOutput
$ ls
main.py
scenes.py
settings.py
$ python3 main.py
Crystal Quest 320 x 192
Title -> Play -> Win
אנלוגיה מהחייםReal-life analogy

פיצול לקבצים הוא כמו ארגזים במעבר דירה עם תוויות: "מטבח", "ספרים". הכול עדיין שלכם, אבל יודעים איפה לחפש.

Splitting into files is like labelled moving boxes: "kitchen", "books". It's all still yours, but you know where to look.

טעות נפוצהCommon mistake

ייבוא מעגלי: scenes מייבא את main, ו-main מייבא את scenes.

A circular import: scenes imports main, and main imports scenes.

Terminal
python3 main.py
מה הטרמינל עונהWhat the terminal says
Traceback (most recent call last):
  File "/Users/you/python-course/main.py", line 1, in <module>
    from scenes import Title
  File "/Users/you/python-course/scenes.py", line 1, in <module>
    from main import Game
  File "/Users/you/python-course/main.py", line 1, in <module>
    from scenes import Title
ImportError: cannot import name 'Title' from 'scenes' (consider renaming '/Users/you/python-course/scenes.py' if it has the same name as a library you intended to import)
בעברית פשוטה: In plain words: ImportError: cannot import name 'Title' from 'scenes': main מייבא את scenes, scenes מייבא את main, ו-main מנסה שוב לקחת את Title מ-scenes שעוד לא סיים להיטען. סצנות לא צריכות לייבא את Game: מעבירים את המשחק כפרמטר (Scene(game)).ImportError: cannot import name 'Title' from 'scenes': main imports scenes, scenes imports main, and main tries again to take Title from scenes, which hasn't finished loading. Scenes don't need to import Game: pass the game in as a parameter (Scene(game)).

02סצנותScenes

עד עכשיו כל משחק השתמש ב-state = "play" ושרשרת if. בפרויקט גדול זה נהיה סבוך, אז כל מסך הופך לסצנה: מחלקה עם update ו-draw. הלולאה הראשית רק קוראת ל-game.scene.update() ו-draw(), וסצנה שרוצה לעבור קוראת ל-game.change(...). כך מוסיפים מסך חדש בלי לגעת בשום if קיים:

Until now every game used state = "play" and an if chain. In a big project that gets tangled, so each screen becomes a scene: a class with update and draw. The main loop just calls game.scene.update() and draw(), and a scene that wants to switch calls game.change(...). That way you add a new screen without touching any existing if:

scenes.py
class Scene:
    def __init__(self, game):
        self.game = game

    def update(self, key):
        pass

    def draw(self):
        return type(self).__name__


class Title(Scene):
    def update(self, key):
        if key == "enter":
            self.game.change(Play(self.game))


class Play(Scene):
    def update(self, key):
        if key == "esc":
            self.game.change(Pause(self.game, self))


class Pause(Scene):
    def __init__(self, game, below):
        super().__init__(game)
        self.below = below

    def update(self, key):
        if key == "esc":
            self.game.change(self.below)

    def draw(self):
        return self.below.draw() + " + Pause"


class Game:
    def __init__(self):
        self.scene = Title(self)

    def change(self, scene):
        self.scene = scene


game = Game()
for key in [None, "enter", "x", "esc", "x", "esc"]:
    game.scene.update(key)
    print(f"{str(key):<5} -> {game.scene.draw()}")
פלטOutput
None  -> Title
enter -> Play
x     -> Play
esc   -> Play + Pause
x     -> Play + Pause
esc   -> Play
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

סצנות הן כמו ערוצים בטלוויזיה: השלט (הלולאה) תמיד אותו שלט, ורק הערוץ שמוצג מתחלף.

Scenes are like TV channels: the remote (the loop) is always the same, only the channel on screen changes.

טעות נפוצהCommon mistake

סצנת השהיה שיוצרת משחק חדש במקום לחזור לקיים.

A pause scene that creates a new game instead of returning to the existing one.

scenes.py
class Play:
    def __init__(self):
        self.score = 0

play = Play()
play.score = 40
after_pause = Play()
assert after_pause.score == 40, f"score reset to {after_pause.score}: keep the paused scene and go back to it, don't build a new one"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/scenes.py", line 8, in <module>
    assert after_pause.score == 40, f"score reset to {after_pause.score}: keep the paused scene and go back to it, don't build a new one"
           ^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: score reset to 0: keep the paused scene and go back to it, don't build a new one
בעברית פשוטה: In plain words: AssertionError: score reset to 0: ...: שומרים את הסצנה שהושהתה (self.below) וחוזרים אליה.AssertionError: score reset to 0: ...: keep the paused scene (self.below) and return to it.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03תנועה במבט עלTop-down movement

במשחק מבט על אין כבידה: החיצים מזיזים בארבעה כיוונים, ושני חיצים יחד בתנועה אלכסונית. מלכודת קלאסית: באלכסון זזים גם 2 ב-x וגם 2 ב-y, כלומר בערך 2.83 פיקסלים, מהר יותר מבקו ישר. הפתרון הוא לנרמל את וקטור הכיוון. pygame.Vector2 עושה את זה בשבילנו:

In a top-down game there's no gravity: arrows move in four directions, and two arrows together give diagonal movement. A classic trap: diagonally you move 2 on x and 2 on y, about 2.83 pixels, faster than in a straight line. The fix is to normalise the direction vector. pygame.Vector2 does it for us:

topdown.py
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
    print(f"{sorted(keys)!s:<18} raw {raw.length():.2f}  fixed {fixed.length():.2f}")
פלטOutput
['right']          raw 2.00  fixed 2.00
['down', 'right']  raw 2.83  fixed 2.00
['left', 'up']     raw 2.83  fixed 2.00
['left', 'right']  raw 0.00  fixed 0.00
אנלוגיה מהחייםReal-life analogy

זה כמו לחצות מגרש באלכסון: אם כל צעד הוא "צעד ימינה ועוד צעד קדימה", אתם רצים מהר יותר מכולם בלי להתאמץ.

It's like crossing a field diagonally: if every step is "a step right plus a step forward", you outrun everyone without trying.

טעות נפוצהCommon mistake

מנרמלים וקטור אפס כשלא לוחצים על כלום.

Normalising a zero vector when nothing is pressed.

topdown.py
import pygame
d = pygame.Vector2(0, 0)
d = d.normalize()
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/topdown.py", line 3, in <module>
    d = d.normalize()
ValueError: Can't normalize Vector of length zero
בעברית פשוטה: In plain words: 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().

04חדרים ודלתותRooms and doors

העולם של Crystal Quest בנוי מחדרים. כל חדר הוא מפת אריחים (כמו בפלטפורמר) שמור במילון לפי שם, ודלת היא רשומה שאומרת לאן היא מובילה ואיפה מופיעים בצד השני. כשנוגעים בדלת, טוענים את החדר החדש ומציבים את השחקן. כאן בודקים שכל דלת מובילה לחדר קיים, וגם שאפשר לחזור:

Crystal Quest's world is made of rooms. Each room is a tilemap (as in the platformer) stored in a dict by name, and a door is a record saying where it leads and where you appear on the other side. On touching a door, load the new room and place the player. Here we check that every door leads to an existing room, and that you can come back:

rooms.py
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)),
}

for (room, mark), (target, spawn) in DOORS.items():
    row, col = spawn[1], spawn[0]
    ok = target in ROOMS and ROOMS[target][row][col] == "."
    print(f"{room:>5} {mark} -> {target:<5} at {spawn}: {'ok' if ok else 'BROKEN'}")

links = {(a, b) for (a, _), (b, _) in DOORS.items()}
print("one-way doors:", [f"{a}->{b}" for a, b in links if (b, a) not in links])
פלטOutput
 hall D -> cave  at (1, 1): ok
 cave D -> hall  at (3, 1): ok
 cave E -> crypt at (2, 1): ok
crypt D -> cave  at (2, 1): ok
one-way doors: []
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

חדרים ודלתות הם כמו תחנות רכבת: כל תחנה עומדת בפני עצמה, ומסילה (דלת) אומרת לאן ממשיכים ולאיזה רציף מגיעים.

Rooms and doors are like train stations: each stands alone, and a track (door) says where you go and which platform you arrive at.

טעות נפוצהCommon mistake

דלת שמובילה לחדר שלא קיים.

A door leading to a room that doesn't exist.

rooms.py
ROOMS = {"hall": [], "cave": []}
DOORS = {("hall", "D"): ("caev", (1, 1))}
target, spawn = DOORS[("hall", "D")]
room = ROOMS[target]
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/rooms.py", line 4, in <module>
    room = ROOMS[target]
           ~~~~~^^^^^^^^
KeyError: 'caev'
בעברית פשוטה: In plain words: KeyError: 'caev': שגיאת כתיב בשם החדר. כדאי לבדוק את כל הדלתות פעם אחת בעליית המשחק, כמו בדוגמה למעלה.KeyError: 'caev': a typo in the room name. Check every door once when the game starts, as in the example above.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05מלאי ודיאלוגInventory and dialogue

המלאי הוא מילון: {"crystal": 2, "key": 1}. איסוף מגדיל ספירה, ודלת נעולה בודקת שיש מפתח ומורידה אותו. דיאלוג נשמר כנתונים: לכל דמות רשימת שורות, וכל שורה יכולה לדרוש תנאי ("יש לך 3 קריסטלים?"). הדמות אומרת את השורה הראשונה שהתנאי שלה מתקיים:

The inventory is a dict: {"crystal": 2, "key": 1}. Picking up raises a count, and a locked door checks there's a key and uses it up. Dialogue is stored as data: each character has a list of lines, and each line can require a condition ("do you have 3 crystals?"). The character says the first line whose condition holds:

inventory.py
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):
    for need, text in lines:
        if all(inventory.get(item, 0) >= n for item, n in need.items()):
            return text

def open_door(inventory):
    if inventory.get("key", 0) < 1:
        return "Locked."
    inventory["key"] -= 1
    return "The door opens."

bag = {}
print(talk(SAGE, bag))
bag["key"] = bag.get("key", 0) + 1
print(talk(SAGE, bag))
print(open_door(bag), open_door(bag), bag)
bag["crystal"] = 3
print(talk(SAGE, bag))
פלטOutput
Bring me three crystals, traveller.
A key! The east door will open for you.
The door opens. Locked. {'key': 0}
You found them all. The tower awaits.
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

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

Dialogue as data is like a script with stage directions: the actor doesn't improvise, they read the line that fits the moment.

טעות נפוצהCommon mistake

קוראים ספירה של פריט שעוד לא נאסף.

Reading the count of an item not yet collected.

inventory.py
bag = {"crystal": 1}
if bag["key"] > 0:
    print("open")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/inventory.py", line 2, in <module>
    if bag["key"] > 0:
       ~~~^^^^^^^
KeyError: 'key'
בעברית פשוטה: In plain words: KeyError: 'key': אין עדיין מפתח במילון. משתמשים ב-bag.get("key", 0).KeyError: 'key': there's no key in the dict yet. Use bag.get("key", 0).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

המלאי הוא מילון ספירות.

The inventory is a dict of counts.

עוד דוגמה: תיק גב של הרפתקןOne more: an adventurer's backpack
example.py
bag = {}
for item in ["key", "gem", "gem", "potion"]:
    bag[item] = bag.get(item, 0) + 1
print(bag)
if bag.get("key", 0):
    bag["key"] -= 1
    print("door opened", bag)
פלטOutput
{'key': 1, 'gem': 2, 'potion': 1}
door opened {'key': 0, 'gem': 2, 'potion': 1}
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06Crystal Quest: חלק 1Crystal Quest: part 1

החלק הראשון של Crystal Quest: חדר ראשון מתוך מפת אריחים, שחקן שזז במבט על ונעצר בקירות, קריסטלים ומפתח לאיסוף, חכם זקן שמדבר, ודלת שנפתחת עם מפתח. כאן השחקן הולך במסלול קבוע; במחשב שלכם החיצים. בשיעור הבא: אויבים, שמירה, צלילים ופרסום:

Crystal Quest part one: a first room from a tilemap, a player moving top-down and stopping at walls, crystals and a key to collect, an old sage who talks, and a door that opens with a key. Here the player walks a fixed route; on your computer, the arrows. Next lesson: enemies, saving, sound and publishing:

crystal_quest.py
import pygame

ROOMS = {
    "hall": [
        "####################",
        "#..................#",
        "#..c.......k.......#",
        "#..................#",
        "#.......####.......#",
        "#.......#..#.......D",
        "#.......#..#.......#",
        "#..................#",
        "#....c.........N...#",
        "#..................#",
        "#..................#",
        "####################",
    ],
}
T = 16
COLORS = {"#": (70, 60, 110), "D": (200, 140, 60), ".": (24, 22, 40)}
pygame.init()
screen = pygame.display.set_mode((20 * T, 12 * T + 24))
font = pygame.font.Font(None, 20)
room = ROOMS["hall"]
walls = [pygame.Rect(c * T, r * T, T, T) for r, row in enumerate(room) for c, ch in enumerate(row) if ch == "#"]
door = next(pygame.Rect(c * T, r * T, T, T) for r, row in enumerate(room) for c, ch in enumerate(row) if ch == "D")
items = {(c, r): ch for r, row in enumerate(room) for c, ch in enumerate(row) if ch in "ck"}
npc = next(pygame.Rect(c * T + 2, r * T + 2, 12, 12) for r, row in enumerate(room) for c, ch in enumerate(row) if ch == "N")
player = pygame.Rect(2 * T + 2, 9 * T + 2, 12, 12)
inventory, message = {"crystal": 0, "key": 0}, "Find the key, then the door"
route = [(5 * T, 8 * T), (3 * T, 2 * T), (11 * T, 2 * T), (15 * T, 7 * T), (18 * T, 5 * T), (19 * T, 5 * T)]


def move(dx, dy):
    for axis, step in (("x", dx), ("y", dy)):
        setattr(player, axis, getattr(player, axis) + step)
        for w in walls:
            if player.colliderect(w):
                if axis == "x":
                    player.right, player.left = (w.left, player.left) if step > 0 else (player.right, w.right)
                else:
                    player.bottom, player.top = (w.top, player.top) if step > 0 else (player.bottom, w.bottom)


for frame in range(900):
    if not route:
        break
    tx, ty = route[0]
    dx = (tx > player.x + 2) - (tx < player.x - 2)
    dy = (ty > player.y + 2) - (ty < player.y - 2)
    if dx == dy == 0:
        route.pop(0)
    move(dx * 2, dy * 2)
    cell = (player.centerx // T, player.centery // T)
    if cell in items:
        kind = {"c": "crystal", "k": "key"}[items.pop(cell)]
        inventory[kind] += 1
        message = f"Picked up a {kind}!"
    if player.inflate(8, 8).colliderect(npc):
        message = "Old sage: the door opens with a key."
    if player.colliderect(door.inflate(4, 0)) and inventory["key"]:
        message = "The door creaks open..."
    screen.fill((10, 10, 18))
    for r, row in enumerate(room):
        for c, ch in enumerate(row):
            pygame.draw.rect(screen, COLORS.get(ch, COLORS["."]), (c * T, r * T, T, T))
    for (c, r), ch in items.items():
        color = (120, 230, 255) if ch == "c" else (255, 215, 80)
        pygame.draw.polygon(screen, color, [(c * T + 8, r * T + 2), (c * T + 14, r * T + 8), (c * T + 8, r * T + 14), (c * T + 2, r * T + 8)])
    pygame.draw.rect(screen, (160, 120, 220), npc, border_radius=6)
    pygame.draw.rect(screen, (250, 250, 250), player, border_radius=3)
    hud = f"Crystals {inventory['crystal']}   Keys {inventory['key']}   {message}"
    screen.blit(font.render(hud, True, (230, 230, 240)), (6, 12 * T + 5))
    pygame.display.flip()
print(inventory, "|", message)
pygame.quit()
פלטOutput
{'crystal': 2, 'key': 1} | The door creaks open...
Crystal Quest: חדר סגול כהה עם קירות, עמוד באמצע, דמות סגולה, השחקן הלבן ליד הדלת הכתומה, ושורת מצב עם מלאי והודעה.
screen.png
אנלוגיה מהחייםReal-life analogy

משחק הרפתקה הוא אוסף של חדרים קטנים ופשוטים. הקסם נוצר מהחיבורים: מפתח כאן פותח דלת שם.

An adventure game is a collection of small, simple rooms. The magic comes from the connections: a key here opens a door there.

טעות נפוצהCommon mistake

מוחקים מפריט ממילון בזמן לולאה עליו.

Deleting from a dict while looping over it.

crystal_quest.py
items = {(1, 1): "c", (2, 2): "k"}
for cell in items:
    if cell == (1, 1):
        del items[cell]
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/crystal_quest.py", line 2, in <module>
    for cell in items:
                ^^^^^
RuntimeError: dictionary changed size during iteration
בעברית פשוטה: In plain words: 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.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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