Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Edit this page

Python Scripting API

Gameplay logic in Pite is authored in Python scripts that inherit from engine node classes in the embedded pite module. Scripts execute directly within the engine process via embedded CPython 3.12, providing high performance with full access to standard Python features.

import pite


class Player(pite.Node2D):
    speed: float = 200.0

    def _ready(self):
        self.position = (100.0, 200.0)

    def _process(self, delta: float):
        if pite.held.right:
            self.position.x += self.speed * delta

Script Architecture and Lifecycle

  • Class Mapping: Each Python script file defines a single node class. Scripts are attached to scene nodes via the scene's [node.script] definition (path and class). Class and module names follow standard Python conventions (snake_case filenames and PascalCase classes).
  • _ready(self): Invoked once when the node enters the active scene tree. Use this for one-time initialization, finding child nodes, and connecting signals.
  • _process(self, delta: float): Invoked every frame during variable-rate rendering updates. The delta parameter provides the elapsed frame duration in seconds (clamped to a maximum of 0.1 to avoid physics tunneling during stalls).
  • _physics_process(self, delta: float): Invoked at a fixed 60 Hz rate (delta = 1/60) for deterministic physics simulation and character movement.
  • Graceful Lifecycle: Missing lifecycle methods (_ready, _process, _physics_process) are safe no-ops and never produce errors.

Calling Superclass _process

If your script overrides _process on a Timer or Button subclass, you must invoke super()._process(delta) to allow the engine to process internal timer accumulation and click polling.


Node References and Navigation

Declarative Descriptors

Declare node references cleanly as class attributes using descriptors:

class GameController(pite.Node2D):
    player = pite.node("../Player")
    hud = pite.child("HUD")

Descriptors resolve on first access and cache the resulting node proxy. If the target node is missing, access raises a KeyError.

Dynamic Traversal via get_node

Traverse the scene hierarchy dynamically using relative or absolute path strings:

self.get_node("../Player").take_damage(1)
  • Paths are relative to the calling node: . (self), .. (parent), ChildName (direct child), or /root/… (absolute path from root).
  • If a target node path does not exist, get_node raises a KeyError.
  • Repeated lookups through get_node are automatically cached by the engine runtime.
  • For dynamic label updates, any node proxy exposes a convenient text property:

    self.get_node("../ScoreLabel").text = f"Score: {self.score}"
    

Custom Properties

Nodes can access project-level custom properties declared under [props] in pite.toml:

# Read custom prop (returns None if unset):
spawn = self.get_custom_property("spawn_group")

# Write custom prop (type-checked against manifest, raises ValueError on mismatch):
self.set_custom_property("spawn_group", "elite_guards")

# Remove custom prop (returns True if it was present):
was_present = self.remove_custom_property("spawn_group")

Schema properties (position, text, etc.) are rejected by get_custom_property/set_custom_property/remove_custom_property with ValueError — use direct typed attributes instead.


Signals

Nodes react to each other with typed signals. Declare them as class variables; access them as members:

class Player(pite.Node2D):
    hit = pite.signal(int)

    def _process(self, delta: float):
        if pite.pressed.space:
            self.hit.emit(1)
  • pite.signal(...) takes payload types, bare or as strings (pite.signal(int, "str")). Both hit = pite.signal(int) and the annotated hit: pite.signal(int) form declare the same signal.
  • Emitting the wrong arity or type fails loudly; emitting an undeclared signal fails loudly. There are no untyped string signals.
  • connect(handler) connects any Python callable (bound methods, lambdas, free functions).
  • Button clicks arrive as a zero-payload pressed signal fired by the engine (press-inside plus release-inside). pressed belongs to the Button type itself — just connect it, no declaration needed:
class HitButton(pite.Button):
    def _ready(self):
        self.pressed.connect(self.on_pressed)

    def on_pressed(self):
        self.get_node("../Player").hit.emit(1)

Error Handling and Live Reload

  • Fault Tolerance: When an unhandled exception occurs in a script callback, Pite logs the complete traceback including node path, source file, and line number. The node preserves its last valid state and the game session continues running without crashing. Repeated failures on the same callback are throttled to keep the console clean and readable.
  • Hot Reloading: Modifying and saving a .py file triggers an immediate hot reload: the module re-executes, class definitions rebind to existing node instances in memory, transforms and physics velocities are preserved, and _ready() is not re-run. If a reloaded script contains syntax or import errors, the previous working version continues executing safely.

Module Imports and Dependency Vendoring

  • Standard Library & Engine API: import pite and all CPython 3.12 standard library modules are always available. Each script's parent directory is prepended to sys.path, allowing sibling modules (e.g. import utils) to resolve directly.
  • Third-Party Dependencies: Third-party packages must be vendored into the project's vendor/ directory using pite vendor add package==version. The CLI pins the package and records its SHA-256 hash in [vendor]. Only pure-Python .whl wheels are supported, and each wheel in vendor/ is automatically added to sys.path in both editor and exported builds.
  • Export Isolation: Standalone game exports deliberately exclude host site-packages to guarantee portable, self-contained builds. Any dependency outside the standard library, pite, project scripts, and vendor/ will not be bundled. Use pite check to audit imports and verify that all external dependencies are properly vendored.
  • Auxiliary Code Files: Sibling Python modules located outside standard script directories should be declared under [export] include in pite.toml to ensure they are packaged during export.