Skip to content

Instantly share code, notes, and snippets.

@amir-arad
Created Jul 22, 2022
Embed
What would you like to do?
save/load feature for colyseus schema objects

I'm adding a save/load feature to my WIP game and thought someone might find this small module useful

example usage:

const saveGameData = new SaveGame(); // make a custom schema for saved games data
... /* add all state objects from your game manager to saveGameData */
const serialized = await schemaToString(saveGameData);
... /* save to file, read from file etc. */
const loadedGameData: SaveGame = await stringToSchema(SaveGame, serialized );
... /* take game state object from loadedGameData into your game manager */

https://raw.githubusercontent.com/starwards/starwards/1a35eea8aacb80ef704df9bbd246a115f653b042/modules/server/src/serialization/game-state-serialization.ts

import { gzip, unzip } from 'node:zlib';
import { Schema } from '@colyseus/schema';
import { promisify } from 'node:util';
const do_gzip = promisify(gzip);
const do_unzip = promisify(unzip);
export async function schemaToString(fragment: Schema) {
const zipped = await do_gzip(Buffer.from(fragment.encodeAll()));
return zipped.toString('base64');
}
type Constructor<T extends Schema> = new (...args: unknown[]) => T;
export async function stringToSchema<T extends Schema>(ctor: Constructor<T>, serialized: string) {
const unzipped = await do_unzip(Buffer.from(serialized, 'base64'));
const result = new ctor();
result.decode([...unzipped]);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment