All files Game.ts

90.28% Statements 158/175
71.68% Branches 81/113
89.47% Functions 17/19
89.3% Lines 142/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460      1x 1x 1x 1x   1x 1x 1x 1x 1x                                                                       1x       5563x     5563x             5552x     5552x     5552x 5552x 5552x                                   492x             10x                                       10x 10x                 10x           10x       10x     10x     10x         10x 10x 10x     10x             10x               10x 10x       10x 10x                             10x 10x 70x 70x 490x   70x     10x 10x 10x 10x   10x         10x   120x 480x       120x         10x 20x               10x 20x               10x 20x               10x 20x               10x 20x 40x                 10x         10x   340x   120x   119x   101x     10x 70x 490x 330x           330x 330x       10x           10x   10x 30x 30x 340x 340x 10x   330x               10x 40x 40x     10x 10x           340x 340x 119x 221x 120x   101x                 20x 20x 480x     700x 700x 460x   119x 119x   120x 120x   101x 101x   120x 120x           700x 700x 176x   524x     524x 44x   480x 480x 480x   20x                           10x       10x   10x 10x 40x 40x 240x 240x 240x     40x     10x 10x 40x 40x 40x         40x                 10x       10x 10x 240x   10x       5553x 5553x     5553x       10x          
/**
 * @author Timo lehnertz
 */
import { AllPlayerStates } from "./AllPlayerStates";
import { Board } from "./Board";
import { GameState } from "./GameState";
import { Heading } from "./Heading";
import { Move } from "./Move";
import { PathTile, TileType } from "./PathTile";
import { PlayerState } from "./PlayerState";
import { RandomNumberGenerator } from "./RandomNumberGenerator";
import { ShiftPosition } from "./ShiftPosition";
import { Treasure } from "./Treasure";
 
export interface CardRatios {
  lCards: number;
  streightCards: number;
  tCards: number;
}
 
export interface TreasureCardChances {
  lCardTreasureChance: number;
  streightCardTreasureChance: number;
  tCardTreasureChance: number;
  fixCardTreasureChance: number;
}
 
export interface GameSetup {
  seed: string;
  playerCount: number;
  boardWidth: number;
  boardHeight: number;
  cardsRatio: CardRatios;
  treasureCardChances: TreasureCardChances;
}
 
export type GameTileType = "fix" | "homePoint" | TileType;
export interface PlayerListener {
  yourTurn: (gameState: GameState, move: (move: Move) => boolean) => void;
}
 
export interface WinListener {
  gameEnded: (winnerIndex: number) => void;
}
 
/**
 * Game class representing a game
 */
export class Game {
  // Game state
  private _gameState: GameState;
  // stuff
  private redoHistory: Move[] = [];
 
  private constructor(gameState: GameState) {
    this._gameState = gameState;
  }
 
  /**
   * Game Logic -------------------
   */
  public move(move: Move) {
    Iif (this.redoHistory.length > 0) {
      throw new Error("redo all moves before moving a new move");
    }
    Iif (this._gameState.getWinnerIndex() !== null) {
      throw new Error("cant move after game has ended");
    }
    this._gameState.validateMove(move); // throws on error
    this._gameState = this._gameState.move(move);
    this.redoHistory = [];
  }
 
  public undoLastMove() {
    const result = this._gameState.undoMove();
    this._gameState = result.newGameState;
    this.redoHistory.push(result.undoneMove);
  }
 
  public redoLastMove() {
    const redoMove = this.redoHistory.pop();
    Iif (redoMove === undefined) {
      throw new Error("no move to redo");
    }
    this._gameState = this._gameState.move(redoMove);
  }
 
  public get gameState(): GameState {
    return this._gameState;
  }
 
  /**
   * Setup logic
   */
  public static getDefaultSetup(): GameSetup {
    return {
      playerCount: 4,
      seed: "seed",
      boardHeight: 7,
      boardWidth: 7,
      cardsRatio: {
        lCards: 15 / 34,
        streightCards: 13 / 34,
        tCards: 6 / 34,
      },
      treasureCardChances: {
        lCardTreasureChance: 6 / 15,
        streightCardTreasureChance: 0,
        tCardTreasureChance: 1,
        fixCardTreasureChance: 1,
      },
    };
  }
 
  public static finalizeSetup(setup?: Partial<GameSetup>): GameSetup {
    const defaultSetup = Game.getDefaultSetup();
    const finalSetup = {
      boardHeight: setup?.boardHeight ?? defaultSetup.boardHeight,
      boardWidth: setup?.boardWidth ?? defaultSetup.boardWidth,
      cardsRatio: setup?.cardsRatio ?? defaultSetup.cardsRatio,
      playerCount: setup?.playerCount ?? defaultSetup.playerCount,
      seed: setup?.seed ?? defaultSetup.seed,
      treasureCardChances:
        setup?.treasureCardChances ?? defaultSetup.treasureCardChances,
    };
    Iif (
      !Board.isSizeValid(finalSetup.boardWidth) ||
      !Board.isSizeValid(finalSetup.boardHeight)
    ) {
      throw new Error(`Invalid board size`);
    }
    const maxPlayers = Board.getMaxPlayerCount(
      finalSetup.boardWidth,
      finalSetup.boardHeight
    );
    Iif (finalSetup.playerCount > maxPlayers) {
      throw new Error(`Too many players. Max ${maxPlayers}`);
    }
    Iif (finalSetup.playerCount < 2) {
      throw new Error("Too few players. Min 2");
    }
    return finalSetup;
  }
 
  public static buildFromSetup(partialSetup?: Partial<GameSetup>): Game {
    // apply defaults
    const setup = Game.finalizeSetup(partialSetup);
    const generator = new RandomNumberGenerator(setup.seed);
    const treasures = Game.generateTreasures(
      Game.getTreasureCount(setup.playerCount)
    );
    const allPlayerStates = Game.generatePlayerStates(
      generator,
      setup.playerCount,
      treasures,
      setup.boardWidth,
      setup.boardHeight
    );
    const board = Game.generateRandomBoard(
      generator,
      treasures,
      setup.boardWidth,
      setup.boardHeight,
      setup.cardsRatio,
      setup.treasureCardChances
    );
    const gameState = new GameState(board, allPlayerStates, []);
    return new Game(gameState);
  }
 
  private static getTreasureCount(playerCount: number): number {
    if (playerCount <= 4) {
      return 24;
    } else E{
      return playerCount * 6;
    }
  }
 
  private static generateRandomBoard(
    generator: RandomNumberGenerator,
    treasures: Treasure[],
    width: number,
    height: number,
    cardsRatios: CardRatios,
    treasureCardChances: TreasureCardChances
  ) {
    // create board tile placeholders
    const tiles: (PathTile | null)[][] = [];
    for (let x = 0; x < width; x++) {
      const column: (PathTile | null)[] = [];
      for (let y = 0; y < height; y++) {
        column[y] = null;
      }
      tiles.push(column);
    }
    // fill corners
    tiles[0][0] = new PathTile(TileType.L, null, 0, null);
    tiles[width - 1][0] = new PathTile(TileType.L, null, 1, null);
    tiles[width - 1][height - 1] = new PathTile(TileType.L, null, 2, null);
    tiles[0][height - 1] = new PathTile(TileType.L, null, 3, null);
    // get generator
    const getRandomTreasure = Game.getRandomTreasureProvider(
      generator,
      treasures,
      treasureCardChances
    );
    const homePoints = Board.generatePlayerHomePositions(width, height);
    function isHome(x: number, y: number): boolean {
      for (const homePoint of homePoints) {
        Iif (homePoint.x === x && homePoint.y === y) {
          return true;
        }
      }
      return false;
    }
    //
    // fill fix edges
    // NORTH
    for (let x = 2; x < width - 2; x += 2) {
      tiles[x][0] = new PathTile(
        TileType.T,
        getRandomTreasure(isHome(x, 0) ? "homePoint" : "fix"),
        2,
        null
      );
    }
    // EAST
    for (let y = 2; y < height - 2; y += 2) {
      tiles[width - 1][y] = new PathTile(
        TileType.T,
        getRandomTreasure(isHome(width - 1, y) ? "homePoint" : "fix"),
        3,
        null
      );
    }
    // SOUTH
    for (let x = 2; x < width - 2; x += 2) {
      tiles[x][height - 1] = new PathTile(
        TileType.T,
        getRandomTreasure(isHome(x, height - 1) ? "homePoint" : "fix"),
        0,
        null
      );
    }
    // WEST
    for (let y = 2; y < height - 2; y += 2) {
      tiles[0][y] = new PathTile(
        TileType.T,
        getRandomTreasure(isHome(0, y) ? "homePoint" : "fix"),
        1,
        null
      );
    }
    // fill fix center
    for (let x = 2; x < width - 2; x += 2) {
      for (let y = 2; y < height - 2; y += 2) {
        tiles[x][y] = new PathTile(
          TileType.T,
          getRandomTreasure(isHome(x, y) ? "homePoint" : "fix"),
          Math.floor(generator.rand() * 4),
          null
        );
      }
    }
    // fill remaining
    const treasureCandidates: ({ x: number; y: number } | "loose-tile")[][] = [
      [], // T cards
      [], // L cards
      [], // Streight cards
    ];
    const tileTypes = [TileType.T, TileType.L, TileType.STREIGHT];
    function idxFromTileType(tileType: TileType): number {
      switch (tileType) {
        case TileType.T:
          return 0;
        case TileType.L:
          return 1;
        case TileType.STREIGHT:
          return 2;
      }
    }
    for (let x = 0; x < width; x++) {
      for (let y = 0; y < height; y++) {
        if (tiles[x][y] === null) {
          const pathTile = new PathTile(
            Game.generateRandomTileType(generator),
            null,
            Math.floor(generator.rand() * 4),
            null
          );
          tiles[x][y] = pathTile;
          treasureCandidates[idxFromTileType(pathTile.tileType)].push({ x, y });
        }
      }
    }
    let looseTile = new PathTile(
      Game.generateRandomTileType(generator),
      null,
      Math.floor(generator.rand() * 4),
      null
    );
    treasureCandidates[idxFromTileType(looseTile.tileType)].push("loose-tile");
    // distribute remaining treasures
    for (let i = 0; i < treasureCandidates.length; i++) {
      const treasureCandidatesOfType = treasureCandidates[i];
      for (const chosenCandidate of treasureCandidatesOfType) {
        const treasure = getRandomTreasure(tileTypes[i]);
        if (chosenCandidate === "loose-tile") {
          looseTile = looseTile.setTreasure(treasure);
        } else {
          tiles[chosenCandidate.x][chosenCandidate.y] =
            tiles[chosenCandidate.x][chosenCandidate.y]?.setTreasure(
              treasure
            ) ?? null;
        }
      }
    }
    // set homePoints
    for (let i = 0; i < homePoints.length; i++) {
      const homePoint = homePoints[i];
      tiles[homePoint.x][homePoint.y] =
        tiles[homePoint.x][homePoint.y]?.setHomeOfPlayerIndex(i) ?? null;
    }
    const startingShiftPosition = new ShiftPosition(Heading.NORTH, 0);
    return new Board(tiles as PathTile[][], looseTile, startingShiftPosition);
  }
 
  private static generateRandomTileType(
    generator: RandomNumberGenerator
  ): TileType {
    const rand = generator.rand() * 3;
    if (rand < 1) {
      return TileType.L;
    } else if (rand < 2) {
      return TileType.T;
    } else {
      return TileType.STREIGHT;
    }
  }
 
  public static getRandomTreasureProvider(
    generator: RandomNumberGenerator,
    treasures: Treasure[],
    treasureCardChances?: TreasureCardChances
  ): (cardType?: GameTileType) => Treasure | null {
    const remainingTreasures: Treasure[] = [];
    for (const treasure of treasures) {
      remainingTreasures.push(treasure);
    }
    function getRandomTreasure(cardType?: GameTileType): Treasure | null {
      let skipChance = 0;
      if (treasureCardChances !== undefined && cardType !== undefined) {
        switch (cardType) {
          case TileType.L:
            skipChance = 1 - treasureCardChances.lCardTreasureChance;
            break;
          case TileType.T:
            skipChance = 1 - treasureCardChances.tCardTreasureChance;
            break;
          case TileType.STREIGHT:
            skipChance = 1 - treasureCardChances.streightCardTreasureChance;
            break;
          case "fix":
            skipChance = 1 - treasureCardChances.fixCardTreasureChance;
            break;
          case "homePoint":
            skipChance = 1;
            break;
        }
      }
      const rand = generator.rand();
      if (rand < skipChance) {
        return null;
      }
      const index = Math.floor(
        Math.min(0.99, rand) * remainingTreasures.length
      );
      if (index >= remainingTreasures.length) {
        return null;
      }
      const randomTreasure = remainingTreasures[index];
      remainingTreasures.splice(index, 1);
      return randomTreasure;
    }
    return getRandomTreasure;
  }
 
  /**
   * @param numberOfPlayers Has to be either 2, 3 or 4
   */
  private static generatePlayerStates(
    generator: RandomNumberGenerator,
    numberOfPlayers: number,
    treasures: Treasure[],
    boardWidth: number,
    boardHeight: number
  ): AllPlayerStates {
    // generate treasures
    const getRandomTreasure = Game.getRandomTreasureProvider(
      generator,
      treasures
    );
    const treasuresPerPlayer = treasures.length / numberOfPlayers;
    // distribute all treasures evenly to all players
    const allPlayersTreasures: Treasure[][] = [];
    for (let i = 0; i < numberOfPlayers; i++) {
      const playerTreasures: Treasure[] = [];
      for (let i = 0; i < treasuresPerPlayer; i++) {
        const treasure = getRandomTreasure();
        if (treasure) {
          playerTreasures.push(treasure);
        }
      }
      allPlayersTreasures.push(playerTreasures);
    }
    // create playerStates
    const playerStates: PlayerState[] = [];
    for (let i = 0; i < allPlayersTreasures.length; i++) {
      const playersTreasures = allPlayersTreasures[i];
      const currentTreasure = playersTreasures.pop() ?? null;
      const playerStartPosition = Board.getPlayerHomePosition(
        i,
        boardWidth,
        boardHeight
      );
      playerStates.push(
        new PlayerState(
          [],
          playersTreasures,
          currentTreasure,
          playerStartPosition
        )
      );
    }
    return new AllPlayerStates(playerStates, 0);
  }
 
  public static generateTreasures(amount: number): Treasure[] {
    const treasures: Treasure[] = [];
    for (let i = 0; i < amount; i++) {
      treasures.push(new Treasure(i));
    }
    return treasures;
  }
 
  public static buildFromString(str: string): Game {
    const obj = JSON.parse(str);
    Iif (!("gameState" in obj)) {
      throw new Error("Invalid game string");
    }
    return new Game(GameState.create(obj.gameState));
  }
 
  public stringify(): string {
    return JSON.stringify({
      gameState: this._gameState,
    });
  }
}