All files Board.ts

71.28% Statements 139/195
53.84% Branches 28/52
85.18% Functions 23/27
71.19% Lines 131/184

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      1x 1x 1x 1x 1x           1x                               57166x 57166x 57166x 57166x 57166x 57166x 400162x       57166x               17201x 17201x 17201x 17201x 120407x 120407x 120407x 120407x   17201x               11135x 11135x 77945x 77945x 545615x   77945x   11135x 546740x 273214x   273526x   273214x 273214x 704324x 704324x 704324x 24415x   679909x 679909x 144304x   535605x       11135x 11135x                                                                                                           483x 483x 3381x 3381x 23667x   3381x   483x 483x 10923x       5336x   5587x 5587x   5587x 5587x 14246x 14246x 14246x 585x   13661x 13661x 3221x   10440x     483x 483x       11135x 11135x     11135x       17201x                                         114352x               10x       120x     120x 120x     120x     120x 120x                 60x 60x 60x 60x 120x 240x 240x 240x       60x               40x 40x       11x 11x 22x 22x 66x     11x 22x 22x 66x     11x       22270x       22270x     22270x     16904x     5366x         17201x 17201x                       17201x   4397x   4188x   4515x   4101x         17201x             17201x 17201x 120407x 120407x 842849x   120407x   17201x       965459x       5587x                                                 5553x 5553x 38871x 38871x 272097x   38871x   5553x              
/**
 * @author Timo lehnertz
 */
import { BoardPosition } from "./BoardPosition";
import { Heading, HeadingHelper } from "./Heading";
import { Path, PathPart } from "./Path";
import { ShiftPosition } from "./ShiftPosition";
import { PathTile } from "./PathTile";
import { Treasure } from "./Treasure";
 
/**
 * Immutable Board class representing the gameboard.
 */
export class Board {
  private tiles: PathTile[][];
  public readonly looseTile: PathTile;
  public readonly shiftPosition: ShiftPosition;
  public readonly width: number;
  public readonly height: number;
 
  /**
   * @param tiles Must a quadratic array
   * @param looseTile the tile that is currently free
   */
  public constructor(
    tiles: PathTile[][],
    looseTile: PathTile,
    shiftPosition: ShiftPosition
  ) {
    this.tiles = tiles;
    this.looseTile = looseTile;
    this.shiftPosition = shiftPosition;
    this.width = tiles.length;
    this.height = tiles[0].length;
    for (const row of tiles) {
      Iif (row.length !== this.height) {
        throw new Error("Tiles of have invalid shape");
      }
    }
    Iif (!Board.isSizeValid(this.width) || !Board.isSizeValid(this.height)) {
      throw new Error(
        "The provided size is invalid! Size must be >= 7 and cant be prime"
      );
    }
  }
 
  public insertLooseTile() {
    let currentPosition = this.getFirstMovedTilePosition(this.shiftPosition);
    const newTiles = this.copyTiles();
    let lastTile = this.looseTile;
    while (currentPosition.isInBounds(this.width, this.height)) {
      const tmp = newTiles[currentPosition.x][currentPosition.y];
      newTiles[currentPosition.x][currentPosition.y] = lastTile;
      lastTile = tmp;
      currentPosition = currentPosition.add(this.shiftPosition.shiftVector);
    }
    return new Board(
      newTiles,
      lastTile,
      this.invertShiftPosition(this.shiftPosition)
    );
  }
 
  public generateDistances(from: BoardPosition): number[][] {
    const distances: number[][] = [];
    for (let x = 0; x < this.width; x++) {
      const column: number[] = [];
      for (let y = 0; y < this.height; y++) {
        column[y] = Number.MAX_SAFE_INTEGER;
      }
      distances[x] = column;
    }
    const checkDistance = (position: BoardPosition, distance: number) => {
      if (distances[position.x][position.y] > distance) {
        distances[position.x][position.y] = distance;
      } else {
        return;
      }
      const tile = this.getTile(position);
      for (const openHeading of tile.openSides.headings) {
        const direction = new HeadingHelper(openHeading).vec2;
        const nextPos = position.add(direction);
        if (!nextPos.isInBounds(this.width, this.height)) {
          continue;
        }
        const nextTile = this.getTile(nextPos);
        if (!nextTile.openSides.isOpposingOpen(openHeading)) {
          continue;
        }
        checkDistance(nextPos, distance + 1);
      }
    };
    // build distance grid
    checkDistance(from, 0);
    return distances;
  }
 
  public generateShortestPath(
    from: BoardPosition,
    to: BoardPosition
  ): Path | null {
    Iif (from.equals(to)) {
      return new Path([]);
    }
    const distances = this.generateDistances(to);
    // check if reachable
    Iif (distances[from.x][from.y] === Number.MAX_SAFE_INTEGER) {
      return null;
    }
    const pathParts: PathPart[] = [];
    let currentLocation = from;
    while (!currentLocation.equals(to)) {
      let minDistance = Number.MAX_SAFE_INTEGER;
      let bestHeading: Heading | null = null;
      const currentTile = this.getTile(currentLocation);
      for (const heading of currentTile.openSides.headings) {
        const nextLocation = currentLocation.add(
          new HeadingHelper(heading).vec2
        );
        Iif (!nextLocation.isInBounds(this.width, this.height)) {
          continue;
        }
        const nextTile = this.getTile(nextLocation);
        Iif (!nextTile.openSides.isOpposingOpen(heading)) {
          continue;
        }
        Iif (distances[nextLocation.x][nextLocation.y] < minDistance) {
          minDistance = distances[nextLocation.x][nextLocation.y];
          bestHeading = heading;
        }
      }
      const nextPos = currentLocation.add(
        new HeadingHelper(bestHeading ?? Heading.NORTH).vec2
      );
      Iif (bestHeading === null) {
        throw new Error("Bug");
      }
      pathParts.push({
        from: currentLocation,
        to: nextPos,
        heading: bestHeading,
      });
      currentLocation = nextPos;
    }
    return new Path(pathParts);
  }
 
  public getReachablePositions(from: BoardPosition): BoardPosition[] {
    const checkedLocations: boolean[][] = [];
    for (let x = 0; x < this.width; x++) {
      const column: boolean[] = [];
      for (let y = 0; y < this.height; y++) {
        column[y] = false;
      }
      checkedLocations[x] = column;
    }
    const reachablePositions: BoardPosition[] = [];
    const check = (position: BoardPosition) => {
      if (
        !position.isInBounds(this.width, this.height) ||
        checkedLocations[position.x][position.y]
      ) {
        return;
      }
      reachablePositions.push(position);
      checkedLocations[position.x][position.y] = true;
      // check surrounding
      const tile = this.tiles[position.x][position.y];
      for (const openHeading of tile.openSides.headings) {
        const direction = new HeadingHelper(openHeading).vec2;
        const nextPos = position.add(direction);
        if (!nextPos.isInBounds(this.width, this.height)) {
          continue;
        }
        const nextTile = this.tiles[nextPos.x][nextPos.y];
        if (!nextTile.openSides.isOpposingOpen(openHeading)) {
          continue;
        }
        check(nextPos);
      }
    };
    check(from);
    return reachablePositions;
  }
 
  public isReachable(from: BoardPosition, to: BoardPosition): boolean {
    const distances = this.generateDistances(from);
    Iif (distances[to.x][to.y] === Number.MAX_SAFE_INTEGER) {
      return false;
    }
    return true;
  }
 
  public rotateLooseTile(rotateBeforeShift: number): Board {
    return new Board(
      this.tiles,
      this.looseTile.rotate(rotateBeforeShift),
      this.shiftPosition
    );
  }
 
  public static getValidSizes(maxSize: number): number[] {
    const validSizes: number[] = [];
    for (let i = 0; i <= maxSize; i++) {
      Iif (Board.isSizeValid(i)) {
        validSizes.push(i);
      }
    }
    return validSizes;
  }
 
  /**
   * @param size Width or height
   */
  public static isSizeValid(size: number): boolean {
    return (
      size >= 7 && // must be larger than the min size
      ((size - 1) % 4 === 0 || (size - 1) % 5 === 0 || (size - 1) % 6 === 0) && // must be possible to distribute players home positions equaly
      size % 2 != 0 // has to be uneven to not have shift rows at the edge
    );
  }
 
  public static getMaxPlayerCount(width: number, height: number): number {
    return Board.generatePlayerHomePositions(width, height).length;
  }
 
  public static getHomePositionIncrement(size: number): number {
    Iif (size < 7) {
      throw new Error("Invalid size");
    }
    size -= 1;
    Iif (size % 4 === 0) {
      return 4;
    }
    Iif (size % 5 === 0) {
      return 5;
    }
    if (size % 6 === 0) {
      return 6;
    }
    throw new Error("Invalid size");
  }
 
  public static generatePlayerHomePositions(
    width: number,
    height: number
  ): BoardPosition[] {
    const homePositions: BoardPosition[] = [];
    const xIncrement = Board.getHomePositionIncrement(width);
    const YIncrement = Board.getHomePositionIncrement(height);
    for (let x = 0; x < width; x += xIncrement) {
      for (let y = 0; y < height; y += YIncrement) {
        const pos = new BoardPosition(x, y);
        if (pos.isEdge(width, height)) {
          homePositions.push(pos);
        }
      }
    }
    return homePositions;
  }
 
  public static getPlayerHomePosition(
    playerIndex: number,
    width: number,
    height: number
  ): BoardPosition {
    const homePositions = Board.generatePlayerHomePositions(width, height);
    return homePositions[playerIndex];
  }
 
  public generateValidShiftPositions(): ShiftPosition[] {
    const shiftPositions: ShiftPosition[] = [];
    for (const heading of [Heading.NORTH, Heading.SOUTH]) {
      let index = 0;
      for (let x = 1; x < this.width - 1; x += 2) {
        shiftPositions.push(new ShiftPosition(heading, index++));
      }
    }
    for (const heading of [Heading.WEST, Heading.EAST]) {
      let index = 0;
      for (let x = 1; x < this.height - 1; x += 2) {
        shiftPositions.push(new ShiftPosition(heading, index++));
      }
    }
    return shiftPositions;
  }
 
  private static getShiftPositionCount(size: number): number {
    return (size - 1) / 2;
  }
 
  public isShiftPositionValid(shiftPosition: ShiftPosition): boolean {
    Iif (shiftPosition.index < 0 || !Number.isInteger(shiftPosition.index)) {
      return false;
    }
    switch (shiftPosition.heading) {
      case Heading.NORTH:
      case Heading.SOUTH:
        return shiftPosition.index < Board.getShiftPositionCount(this.width);
      case Heading.EAST:
      case Heading.WEST:
        return shiftPosition.index < Board.getShiftPositionCount(this.height);
    }
  }
 
  public invertShiftPosition(shiftPosition: ShiftPosition): ShiftPosition {
    const invertedHeading = new HeadingHelper(shiftPosition.heading).inverted;
    return new ShiftPosition(invertedHeading, shiftPosition.index);
  }
 
  public getLastMovedTilePosition(shiftPosition: ShiftPosition): BoardPosition {
    return this.getFirstMovedTilePosition(
      this.invertShiftPosition(shiftPosition)
    );
  }
 
  public getFirstMovedTilePosition(
    shiftPosition: ShiftPosition
  ): BoardPosition {
    switch (shiftPosition.heading) {
      case Heading.NORTH:
        return new BoardPosition(1 + shiftPosition.index * 2, 0);
      case Heading.EAST:
        return new BoardPosition(this.width - 1, 1 + shiftPosition.index * 2);
      case Heading.SOUTH:
        return new BoardPosition(1 + shiftPosition.index * 2, this.height - 1);
      case Heading.WEST:
        return new BoardPosition(0, 1 + shiftPosition.index * 2);
    }
  }
 
  public setShiftPosition(shiftPosition: ShiftPosition): Board {
    return new Board(this.tiles, this.looseTile, shiftPosition);
  }
 
  /**
   * Because Tile is immutable we dont need to make a deep copy here
   */
  private copyTiles(): PathTile[][] {
    const newTiles: PathTile[][] = [];
    for (const column of this.tiles) {
      const newColumn: PathTile[] = [];
      for (const tile of column) {
        newColumn.push(tile);
      }
      newTiles.push(newColumn);
    }
    return newTiles;
  }
 
  public getTile(position: BoardPosition): PathTile {
    return this.tiles[position.x][position.y];
  }
 
  public getTreasureAt(position: BoardPosition): Treasure | null {
    return this.tiles[position.x][position.y].treasure;
  }
 
  public equals(other: Board): boolean {
    Iif (!this.looseTile.equals(other.looseTile)) {
      console.log("looseTile");
      return false;
    }
    Iif (!this.shiftPosition.equals(other.shiftPosition)) {
      return false;
    }
    Iif (this.width !== other.width || this.height !== other.height) {
      return false;
    }
    for (let x = 0; x < this.width; x++) {
      for (let y = 0; y < this.height; y++) {
        Iif (!this.tiles[x][y].equals(other.tiles[x][y])) {
          return false;
        }
      }
    }
    return true;
  }
 
  static create(instance: Board): Board {
    const tiles: PathTile[][] = [];
    for (const row of instance.tiles) {
      const newRow: PathTile[] = [];
      for (const tile of row) {
        newRow.push(PathTile.create(tile));
      }
      tiles.push(newRow);
    }
    return new Board(
      tiles,
      PathTile.create(instance.looseTile),
      ShiftPosition.create(instance.shiftPosition)
    );
  }
}