Skip to content

Instantly share code, notes, and snippets.

@amir-arad
Created July 22, 2022 18:53
Show Gist options
  • Select an option

  • Save amir-arad/08ea6c7b1c1e59d5b6776bedca404df2 to your computer and use it in GitHub Desktop.

Select an option

Save amir-arad/08ea6c7b1c1e59d5b6776bedca404df2 to your computer and use it in GitHub Desktop.

Revisions

  1. amir-arad revised this gist Jul 22, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion README.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    I'm adding a save/load feature to my WIP game and thought someone here might find this small module useful
    I'm adding a save/load feature to my WIP game and thought someone might find this small module useful

    example usage:
    ```typescript
  2. amir-arad created this gist Jul 22, 2022.
    13 changes: 13 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    I'm adding a save/load feature to my WIP game and thought someone here might find this small module useful

    example usage:
    ```typescript
    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
    20 changes: 20 additions & 0 deletions schema-serialization.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    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;
    }