Add proper game code generation

This commit is contained in:
Oliver Akins 2022-03-07 23:39:22 -06:00
parent 6088128b7d
commit eab458bb6b
No known key found for this signature in database
GPG key ID: 3C2014AF9457AF99

View file

@ -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;
}
};