Skip to content

Engine

The Engine<TState> base class is the state coordinator at the heart of every game.

Usage

typescript
import { Engine } from "quantum-forge/engine";

interface GameState {
  player: { x: number; y: number; health: number };
  enemies: Enemy[];
  score: number;
}

class MyEngine extends Engine<GameState> {
  constructor(logger?: any) {
    const initialState: GameState = {
      player: { x: 400, y: 300, health: 100 },
      enemies: [],
      score: 0,
    };
    super(initialState, { logger });
  }

  getHelpers() {
    return {
      movePlayer: (dx: number, dy: number) => {
        const state = this.getState();
        state.player.x += dx;
        state.player.y += dy;
        this.setState({ ...state });
      },

      spawnEnemy: (x: number, y: number) => {
        const state = this.getState();
        state.enemies.push({ x, y, health: 50 });
        this.setState({ ...state });
      },

      addScore: (points: number) => {
        const state = this.getState();
        state.score += points;
        this.setState({ ...state });
      },
    };
  }

  reset() {
    this.setState({
      player: { x: 400, y: 300, health: 100 },
      enemies: [],
      score: 0,
    });
  }
}

API

MethodDescription
getState()Returns the current game state
setState(state)Replaces the game state
getHelpers()Returns an object of state-mutating functions (override in subclass)
reset()Reset to initial state (override in subclass)

Quantum Registry

Games pass a quantum registry to the engine and expose quantum operations through helpers:

typescript
class PongEngine extends Engine<PongState> {
  private registry: QuantumRegistry;

  constructor(logger?: any) {
    super(initialState, { logger });
    this.registry = new QuantumRegistry(logger);
  }

  getHelpers() {
    return {
      enterQuantumZone: (ballId: string) => {
        this.registry.entangleSplit(ballId, `${ballId}-ghost`);
        const state = this.getState();
        // Add ghost ball to state...
        this.setState({ ...state });
      },

      scoreBall: (ballId: string) => {
        const exists = this.registry.measureExistence(ballId);
        const state = this.getState();
        if (exists === 1) state.score++;
        this.setState({ ...state });
      },
    };
  }
}

Powered by Quantum Forge