sync module

State Synchronization

Pure functions for serializing world state and computing deltas.

The delta sync cycle works as follows:

  1. serialize_world() captures the current world as a plain dict.

  2. compute_delta() diffs two snapshots, producing a change list.

  3. apply_delta() patches a snapshot with a change list.

The key invariant is:

apply_delta(old, compute_delta(old, new)) == new
network.sync.apply_delta(state: dict, changes: list) → dict

Apply a change list to a serialized state, returning a new dict.

Does not mutate the input; returns a deep copy with changes applied.

Parameters:
  • state (dict) – The base state to patch.

  • changes (list[dict]) – Change list from compute_delta().

Returns:

A new state dict with changes applied.

Return type:

dict

network.sync.compute_delta(old_state: dict, new_state: dict) → list

Compute a list of changes between two serialized world states.

Uses key-level diffing on tiles, entities, lore, and turn sections. Each change dict has keys op, path, and (for add/update) value.

Parameters:
Returns:

A list of change dicts, each with op ("add"/"update"/"remove"), path (e.g. "tiles/0,1"), and optionally value.

Return type:

list[dict]

network.sync.serialize_entity(entity) → dict

Serialize a single GameEntity.

Includes position if set on the entity.

Parameters:

entity (GameEntity) – The entity to serialize.

Returns:

A dict representation with an optional position key.

Return type:

dict

network.sync.serialize_world(world) → dict

Serialize a World to a dict for network transmission.

Reuses existing TileData.to_dict() and GameEntity.to_dict().

Parameters:

world (World) – The world object to serialize.

Returns:

A dict containing tiles, entities, lore, and turn keys.

Return type:

dict