Created
July 22, 2022 18:53
-
-
Save amir-arad/08ea6c7b1c1e59d5b6776bedca404df2 to your computer and use it in GitHub Desktop.
Revisions
-
amir-arad revised this gist
Jul 22, 2022 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 might find this small module useful example usage: ```typescript -
amir-arad created this gist
Jul 22, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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; }