Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

starwards-colyseus

БесплатноБез исполняемых скриптовНе проверен

Colyseus multiplayer patterns for Starwards - @gameField decorators, state sync, JSON Pointer commands, room architecture, and avoiding common Colyseus…

starwardsот starwards★ 44 звезды на GitHub

Об этом скилле

Colyseus Multiplayer Patterns for Starwards

Overview

Starwards uses Colyseus v0.15 for real-time multiplayer state synchronization. Understanding decorators, rooms, and state sync prevents bugs.

Core principle: State is the source of truth. Commands modify state. Clients receive automatic updates.

Architecture

Client (Browser)
  ↓ WebSocket connection
Room (Server)
  ↓ owns
State (Schema)
  ↓ syncs to
Client State (Mirror)

Flow:

  1. Client sends command → Room
  2. Room modifies State
  3. Colyseus patches → Client
  4. Client state updates automatically
  5. UI reacts to state changes

The @gameField Decorator

Purpose: Marks properties for automatic Colyseus synchronization

Location: modules/core/src/game-field.ts

Usage:

import { gameField } from '../game-field';

class Shield extends SystemState {
  // Primitive types
  @gameField('float32') strength = 1000;
  @gameField('float32') power = 1.0;
  @gameField('boolean') broken = false;

  // Nested Schema
  @gameField(ShieldDesign) design = new ShieldDesign();

  // Arrays
  @gameField([Emitter]) emitters = new ArraySchema<Emitter>();

  // Maps
  @gameField({ map: Target }) targets = new MapSchema<Target>();
}

Types:

  • 'float32' - 32-bit float (precision loss vs 64-bit number!)
  • 'float64' - 64-bit float
  • 'int8', 'int16', 'int32' - Signed integers
  • 'uint8', 'uint16', 'uint32' - Unsigned integers
  • 'boolean' - Boolean
  • 'string' - String
  • SchemaClass - Nested Schema
  • [SchemaClass] - Array of Schema
  • {map: SchemaClass} - Map of Schema

Critical @gameField Rules

Rule 1: @gameField Must Be Last Decorator

// CORRECT order
@range([0, 1])           // 1st
@tweakable('number')     // 2nd
@gameField('float32')    // 3rd - LAST
power = 1.0;

// WRONG order
@gameField('float32')    // Can't be first
@range([0, 1])
power = 1.0;

Why: Decorators execute bottom-to-top. @gameField must wrap the final property.

Rule 2: Initialize Collections

// CORRECT
@gameField([Thruster])
thrusters = new ArraySchema<Thruster>();

@gameField({map: Spaceship})
ships = new MapSchema<Spaceship>();

// WRONG
@gameField([Thruster])
thrusters: ArraySchema<Thruster>;  // Not initialized!

Why: Colyseus needs instances, not undefined.

Rule 3: Use Correct Types

// CORRECT
@gameField('float32') speed = 0;      // 32-bit float
@gameField('int16') count = 0;        // 16-bit int

// WRONG
@gameField('number') speed = 0;       // No 'number' type
@gameField('float') speed = 0;        // No 'float' type (use float32/float64)

Why: Colyseus schema types are explicit.

Rule 4: Don't Sync Everything

// Only sync state that clients need
@gameField('float32') health = 100;   // ✅ Clients need this
@gameField('float32') damage = 10;    // ❌ Internal calculation, don't sync

// Derive internally
get damage() {
  return this.weapon.baseDamage * this.effectiveness;
}

Why: Less sync = better performance.

Nested ArraySchema (Two Levels Deep)

An ArraySchema<Child> inside items of another ArraySchema<Parent> syncs correctly — nothing special is needed for depth two, just plain @gameField([Child]) on the mid-level schema. Real example: Armor.armorPlates[i].layers[j].health in modules/core/src/ship/armor.ts.

  • colyseus-events emits leaf events with both indices (e.g. /armor/armorPlates/3/layers/0/health), and EventEmitter2 wildcard listeners (/armor/armorPlates/*/layers/*/health, delimiter '/') match them.
  • Pushing a new nested child after wireEvents auto-wires it.

Pinned by modules/core/test/armor-layers-sync.spec.ts.

Float32 Precision Gotcha

Problem: JavaScript numbers are 64-bit, Colyseus float32 is 32-bit

@gameField('float32') speed = 123.456789;
console.log(speed);  // 123.46 (precision lost!)

Solution: Use toBeCloseTo() in tests

// WRONG
expect(ship.speed).toBe(123.456789);

// CORRECT
expect(ship.speed).toBeCloseTo(123.46, 1);

State vs Non-State

State (synced):

class ShipState extends Schema {
  @gameField('float32') health = 100;   // Synced
  @gameField(Reactor) reactor!: Reactor;  // Synced
}

Non-State (server only):

class ShipManager {
  updateRate = 60;                      // Not synced
  lastUpdate = Date.now();              // Not synced

  update(dt: number) {
    this.state.health -= 10 * dt;       // Modify state → syncs
  }
}

Rule: Only Schema classes with @gameField sync. Plain properties don't sync.

Commands: Client → Server

Two patterns:

1. JSON Pointer (Dynamic)

Client:

room.send({
  type: '/Spaceship/ship-1/reactor/power',
  value: 0.8
});

Server (auto-handled in ShipRoom):

// No code needed - JSON Pointer auto-applies to state

Use when: Simple property updates, GM interface, debugging

Полный SKILL.md на GitHub

Установить starwards-colyseus в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл starwards-colyseus?

Colyseus multiplayer patterns for Starwards - @gameField decorators, state sync, JSON Pointer commands, room architecture, and avoiding common Colyseus pitfalls; state is source of truth, server authoritative

Как установить скилл starwards-colyseus?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл starwards-colyseus запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить starwards-colyseus с