diff --git a/server/src/objects/Game.ts b/server/src/objects/Game.ts index 7d7f9ba..ee09bd0 100644 --- a/server/src/objects/Game.ts +++ b/server/src/objects/Game.ts @@ -1,10 +1,9 @@ import { determineDirection, FuelCard } from "common"; +import { config, games, log } from "@/main"; import { promises as fs } from "fs"; -import { v4 as uuid } from "uuid"; import { Player } from "./Player"; import { Logger } from "tslog"; import { Deck } from "./Deck"; -import { log } from "../main"; import path from "path"; export class Game { @@ -32,7 +31,7 @@ export class Game { // Instantiate the deck this.loadDeck(); - this.id = uuid(); + this.id = Game.generateID(config.game.code_length); this.log = log.getChildLogger({ name: this.id, @@ -73,13 +72,38 @@ export class Game { * --- * * Possible Return Values: - * - `-1` = Away from the Warp Gate + * - `-1` = Away from the Warp Gate (towards the black hole) * - `0` = Not moving - * - `1` = Towards the Warp Gate + * - `1` = Towards the Warp Gate (away from the black hole) */ public movementDirection(player: Player): number { let location = this.board.indexOf(player); this.log.debug(`Calculating movement direction for ${player.name}`); return determineDirection(this.board, location); }; + + /** + * Generates a game code with the given length + * + * @param length The length of the code to generate + */ + public static generateID(length: number): string { + let code: string; + + // Prevent erroneous codes from being generated + if (length <= 0) { + throw new Error("Can't code have a length <= 0"); + }; + + // Generate a new code until we find one that isn't taken already. + do { + code = ``; + + for (var i = 0; i < length; i++) { + code += Math.floor(Math.random() * 9); + }; + } while (games.has(code)); + + return code; + } }; \ No newline at end of file