Skip to content

Save and load ​

saveWorld turns a world into plain data and loadWorld makes it again. Entities, components, timers, sequences, orders, objectives and computers are saved for you.

ts
// in src/rules.ts
import { defineComponent, defineIds, type Rules, loadWorld, saveWorld, type World } from '@v12-engine/engine'

export const UNIT = defineIds('scout')

/** State of the game's own, on a unit: saved with it, nothing to write */
const veteran = defineComponent<{ kills: number; rank: string }>({ id: 'mygame.veteran', default: () => ({ kills: 0, rank: 'recruit' }) })

export const rules: Rules = {
	id: 'my-game',
	name: 'My game',
	units: [{ id: UNIT.scout, name: 'Scout', kind: 'unit', radius: 0.4, sight: 10, stats: { health: 100, moveSpeed: 5 } }],
	components: [veteran],
	saves: {
		// bumped when a save of before would be read wrong: a migration brings it up a version at a time
		version: 2,
		migrate: {
			// 1 → 2: the rank was a number
			2: (save) => {
				for (const entity of save.entities) {
					const state = (entity.components as Record<string, unknown> | undefined)?.['mygame.veteran'] as
						{ kills: number; rank: number | string } | undefined
					if (state && typeof state.rank === 'number') state.rank = state.rank > 2 ? 'veteran' : 'recruit'
				}
			}
		}
	},
	victory: null
}

/** Kept and brought back: the same game, to the bit */
export async function roundTrip(world: World): Promise<World> {
	const save = saveWorld(world)
	const text = JSON.stringify(save) // what goes to disk, a store, or a server
	return loadWorld(JSON.parse(text), { rules: rules })
}

Done: roundTrip(world) gives back the same game, to the bit, and an old version-1 save loads with its ranks fixed.

Add saves to a game on a page ​

Pass saves: true to launch: the pause menu gets save, load and replays. A Store says where they are kept. A server saves the same way.

Reference ​

FieldWhat it does
saves.versionBump it when an old save would be read wrong.
saves.migrateVersion → function that brings a save of the version before up to it. Or one function for all.
saves.onMismatchA save of other rules: load, refuse, or a function that decides.

A save holds the world's state only; the rules are found again from the game you pass to loadWorld. Anything kept outside the world (a module variable, a closure) is lost: keep state in components, world.states, or a system's save and restore. See Saves, mods, data and components.