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

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

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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • מצבים: patrol, chase, returnStates: patrol, chase, return
  • מעבר לפי מרחק לשחקןSwitch by distance to the player
  • מצב המשחק → מילון → JSONGame state → dict → JSON
  • כותבים לקובץ זמני ואז מחליפיםWrite to a temp file, then replace
  • חלקיק = מיקום, מהירות, חייםA particle = position, velocity, life
  • חיכוך: vel *= 0.95Friction: vel *= 0.95
  • נתיב יחסי לקובץ הקוד: Path(__file__).parentPaths relative to the code file: Path(__file__).parent
  • תיקיית assets מסודרתA tidy assets folder
  • pygbag: לולאה async עם await asyncio.sleep(0)pygbag: an async loop with await asyncio.sleep(0)

מונחיםTerms

  • מצב התנהגותbehaviour state: אחד מכמה מצבים שבהם אויב יכול להיות (סיור, מרדף, חזרה). בכל פריים בודקים אם לעבור למצב אחר.One of several modes an enemy can be in (patrol, chase, return). Each frame, check whether to switch to another.
  • קובץ שמירהsave file: קובץ (למשל JSON) שמחזיק את מצב המשחק כדי להמשיך מאותה נקודה. חייב לשרוד קובץ חסר או פגום.A file (such as JSON) holding the game's state so you can continue from the same point. Must survive a missing or broken file.
  • pygbagpygbag: כלי שאורז משחק pygame לאתר שרץ בדפדפן (WebAssembly). דורש לולאה ראשית אסינכרונית.A tool that packages a pygame game into a website running in the browser (WebAssembly). Needs an async main loop.
  • קובץ הרצהexecutable: קובץ שמשתמש מריץ בלחיצה כפולה בלי להתקין פייתון. PyInstaller בונה אחד כזה.A file a user runs with a double click without installing Python. PyInstaller builds one.

Cheatsheet

בינהAI
def next_state(state, dist_to_player, dist_to_home):
    if state == "patrol" and dist_to_player < 60:
        return "chase"
    if state == "chase" and dist_to_player > 90:
        return "return"
    if state == "return":
        if dist_to_player < 60:
שמירהSave
import json
from pathlib import Path

NEW_GAME = {"room": "hall", "pos": [2, 9], "bag": {}, "hp": 3}

def save(state, path):
    tmp = path.with_suffix(".tmp")
חלקיקיםParticles
import math
import random
import pygame

random.seed(3)
pygame.init()
screen = pygame.display.set_mode((240, 160))
נכסיםAssets
from pathlib import Path
import pygame

ASSETS = Path(__file__).parent / "assets"
_cache = {}

def image(name, size=(16, 16)):
פרסוםPublish
import asyncio
import pygame

async def main():
    pygame.init()
    screen = pygame.display.set_mode((240, 120))
    clock = pygame.time.Clock()
משחקGame
import math
import random
import pygame

ROOM = [
    "####################",
    "#..................#",

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorטווח כניסה ויציאה זהים, והרוח "מהבהבת".Equal entry and exit ranges, so the ghost "flickers".AssertionError: 6 state changes in 6 frames: ...: על הגבול כל רעד קטן מחליף מצב. נכנסים ב-60 ויוצאים רק ב-90.AssertionError: 6 state changes in 6 frames: ...: on the edge every tiny wobble switches state. Enter at 60 and leave only at 90.
TypeErrorשומרים אובייקט שלא ניתן להמרה ל-JSON.Saving an object JSON can't convert.TypeError: Object of type set is not JSON serializable: JSON מכיר רשימות ומילונים, לא set או Vector2. ממירים: sorted(bag) או [v.x, v.y].TypeError: Object of type set is not JSON serializable: JSON knows lists and dicts, not set or Vector2. Convert: sorted(bag) or [v.x, v.y].
AssertionErrorמוסיפים חלקיקים ולא מוחקים אף פעם.Adding particles and never deleting them.AssertionError: 12000 particles and counting: ...: המשחק יאט עד שייתקע. מוחקים חלקיק כשהחיים שלו מגיעים ל-0.AssertionError: 12000 particles and counting: ...: the game slows until it freezes. Delete a particle when its life reaches 0.
<sys>לולאה אסינכרונית בלי await, והפונקציה לא רצה בכלל.An async loop without await, so the function never runs at all.AssertionError: got coroutine: ...: קריאה ל-main() אסינכרונית רק יוצרת אובייקט. מריצים עם asyncio.run(main()).AssertionError: got coroutine: ...: calling an async main() only creates an object. Run it with asyncio.run(main()).
ValueErrorמנרמלים וקטור אפס כשהרוח כבר על השחקן.Normalising a zero vector when the ghost is already on the player.ValueError: Can't normalize Vector of length zero: בודקים שהמרחק גדול מאפס לפני הנרמול, או משתמשים ב-move_towards.ValueError: Can't normalize Vector of length zero: check the distance is above zero before normalising, or use move_towards.

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