⚠️ Beta State

PyBevy is in an early and experimental stage. The API is incomplete, subject to breaking changes without notice, and you should expect bugs. Many features are still under development.

ECS Guide

A guided introduction to PyBevy's Entity Component System pattern.

Introduction

The Entity Component System (ECS) is the core architecture of PyBevy and the Bevy engine it's built on. This example walks through all the fundamental concepts: components, resources, systems, queries, and commands.

from pybevy.prelude import *

Components

Components are data attached to entities. Define them as Python classes with the @component decorator.

@component
class Player(Component):
    pass
 
 
@component
class Score(Component):
    value: int = 0
 
 
@component
class PlayerName(Component):
    name: str = "Unknown"

Resources

Resources are global singleton data, accessible by any system. Define them with @resource.

@resource
class GameState(Resource):
    def __init__(self):
        self.total_players = 0

Startup System

Spawn player entities with components attached. Commands lets you create entities and insert components.

def add_players(commands: Commands, state: ResMut[GameState]) -> None:
    commands.spawn(Player(), PlayerName(name="Alice"), Score(value=0))
    commands.spawn(Player(), PlayerName(name="Bob"), Score(value=0))
    state.total_players = 2
    print(f"Spawned {state.total_players} players")

Query System

Use Query to iterate over entities that have specific components. This system prints each player's score.

def score_system(query: Query[tuple[PlayerName, Score]]) -> None:
    for name, score in query:
        print(f"{name.name}: {score.value} points")

Running the App

@entrypoint
def main(app: App) -> App:
    return (
        app
        .add_plugins(MinimalPlugins)
        .insert_resource(GameState())
        .add_systems(Startup, add_players)
        .add_systems(Update, score_system)
    )
 
if __name__ == "__main__":
    main().run()

Running this example

Use PyBevy's hot reload feature to run and develop this example. If you don't have PyBevy installed, check out the Quick Start guide.

$pybevy watch ecs_guide.py

The code will reload automatically when you make changes to the file.


From Python to Rust

Notice how the core concepts in the code—Commands, Assets, App, and Systems—are identical to the original Bevy example?

This is the power of pybevy! It lets you learn Bevy's powerful, data-driven architecture in friendly Python.

When your project grows and you're ready for maximum, native performance, you'll already know the concepts to start writing systems in Bevy Engine with Rust.