All files GameState.ts

65.43% Statements 53/81
42.1% Branches 8/19
70% Functions 14/20
65.43% Lines 53/81

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      1x 1x     1x   1x 1x           1x       74056x             74056x 74056x 74056x             11135x           11135x     11135x     11135x     11135x     11135x       11135x     11135x 11135x 11135x 6037x 282x     11135x                     5583x 5583x                                                     17201x               17201x 17201x       17201x   68804x                 17201x 17201x       5583x 5583x             5583x 5442x   141x       141x       5583x 5583x                   5583x                               5583x                               5583x 5583x 744x   5583x       5583x 5583x 5583x                                   5553x 5553x 24x   5553x                            
/**
 * @author Timo lehnertz
 */
import { AllPlayerStates } from "./AllPlayerStates";
import { Board } from "./Board";
import { BoardPosition } from "./BoardPosition";
import { ShiftPosition } from "./ShiftPosition";
import { Move } from "./Move";
import { PlayerState } from "./PlayerState";
import { Treasure } from "./Treasure";
import { Cyrb64 } from "./Cyrb64";
 
/**
 * GameState class representing the state of a game
 * This class exposes all information about the game that a player could legally know by looking at the board
 */
export class GameState {
  public readonly board: Board;
  public readonly allPlayerStates: AllPlayerStates;
  public readonly historyMoves: Move[];
  private hashCache: Cyrb64 | null = null;
 
  public constructor(
    board: Board,
    allPlayerStates: AllPlayerStates,
    historyMoves: Move[]
  ) {
    this.board = board;
    this.allPlayerStates = allPlayerStates;
    this.historyMoves = historyMoves;
  }
 
  /**
   * @throws Error in case the move is not valid
   */
  public validateMove(move: Move) {
    Iif (
      !this.board.isShiftPositionValid(move.fromShiftPosition) ||
      !this.board.isShiftPositionValid(move.toShiftPosition)
    ) {
      throw new Error("Invalid shift position");
    }
    Iif (!this.board.shiftPosition.equals(move.fromShiftPosition)) {
      throw new Error("Invalid starting shiftPosition");
    }
    const gameStatedAfterSlide = this.setShiftPosition(move.toShiftPosition)
      .rotateLooseTile(move.rotateBeforeShift)
      .insertLooseTile();
    const playerState = gameStatedAfterSlide.allPlayerStates.getPlayerState(
      move.playerIndex
    );
    Iif (playerState === null) {
      throw new Error("Invalid playerIndex");
    }
    Iif (!move.from.equals(playerState.position)) {
      console.log(move.from, playerState.position);
      throw new Error("Invalid starting position");
    }
    Iif (!gameStatedAfterSlide.board.isReachable(move.from, move.to)) {
      throw new Error("Destination is not in reach");
    }
    let expectedTreasure: Treasure | null = null;
    const treasureAtTo = gameStatedAfterSlide.board.getTile(move.to).treasure;
    if (treasureAtTo !== null) {
      if (playerState.currentTreasure?.equals(treasureAtTo)) {
        expectedTreasure = treasureAtTo;
      }
    }
    Iif (!Treasure.compare(expectedTreasure, move.collectedTreasure)) {
      console.log(expectedTreasure, move.collectedTreasure);
      console.log(JSON.stringify(move));
      throw new Error("Invalid collected treasure");
    }
  }
 
  /**
   * @throws Error in case the move is not valid
   */
  public move(move: Move): GameState {
    this.validateMove(move);
    return this.rotateLooseTile(move.rotateBeforeShift)
      .setShiftPosition(move.toShiftPosition)
      .insertLooseTile()
      .movePlayer(move.playerIndex, move.to)
      .collectTreasure(move.playerIndex, move.collectedTreasure)
      .nextPlayer()
      .addMoveToHistory(move);
  }
 
  public undoMove(): { newGameState: GameState; undoneMove: Move } {
    Iif (this.historyMoves.length === 0) {
      throw new Error("no moves to undo");
    }
    const move = this.historyMoves[this.historyMoves.length - 1];
    return {
      newGameState: this.removeLastHistoryMove()
        .prevPlayer()
        .removeLastTreasure(move.playerIndex, move.collectedTreasure)
        .movePlayer(move.playerIndex, move.from)
        .insertLooseTile()
        .setShiftPosition(move.fromShiftPosition)
        .rotateLooseTile(-move.rotateBeforeShift),
      undoneMove: move,
    };
  }
 
  public rotateLooseTile(rotateBeforeShift: number): GameState {
    return new GameState(
      this.board.rotateLooseTile(rotateBeforeShift),
      this.allPlayerStates,
      this.historyMoves
    );
  }
 
  public setShiftPosition(shiftPosition: ShiftPosition): GameState {
    const newBoard = this.board.setShiftPosition(shiftPosition);
    return new GameState(newBoard, this.allPlayerStates, this.historyMoves);
  }
 
  public insertLooseTile(): GameState {
    const newAllPlayerStates = this.allPlayerStates.mutateAll(
      (playerState: PlayerState): PlayerState => {
        return playerState.setPosition(
          this.board.shiftPosition.shiftPlayer(
            playerState.position,
            this.board.width,
            this.board.height
          )
        );
      }
    );
    const newBoard = this.board.insertLooseTile();
    return new GameState(newBoard, newAllPlayerStates, this.historyMoves);
  }
 
  private movePlayer(playerIndex: number, to: BoardPosition) {
    const newAllPlayerStates = this.allPlayerStates.movePlayer(playerIndex, to);
    return new GameState(this.board, newAllPlayerStates, this.historyMoves);
  }
 
  private collectTreasure(
    playerIndex: number,
    foundTreasure: Treasure | null
  ): GameState {
    if (foundTreasure === null) {
      return this;
    }
    const newAllPlayerStates = this.allPlayerStates.collectTreasure(
      playerIndex,
      foundTreasure
    );
    return new GameState(this.board, newAllPlayerStates, this.historyMoves);
  }
 
  public getWinnerIndex(): number | null {
    const playerStates = this.allPlayerStates.getPlayerStatesWithAllTreasures();
    for (const player of playerStates) {
      const playerHomePoint = Board.getPlayerHomePosition(
        player.playerIndex,
        this.board.width,
        this.board.height
      );
      Iif (player.playerState.position.equals(playerHomePoint)) {
        return player.playerIndex;
      }
    }
    return null;
  }
 
  private removeLastTreasure(
    playerIndex: number,
    foundTreasure: Treasure | null
  ): GameState {
    Iif (foundTreasure === null) {
      return this;
    }
    const newAllPlayerStates =
      this.allPlayerStates.removeLastTreasure(playerIndex);
    return new GameState(this.board, newAllPlayerStates, this.historyMoves);
  }
 
  private nextPlayer(): GameState {
    return new GameState(
      this.board,
      this.allPlayerStates.nextPlayer(),
      this.historyMoves
    );
  }
 
  private prevPlayer(): GameState {
    return new GameState(
      this.board,
      this.allPlayerStates.prevPlayer(),
      this.historyMoves
    );
  }
 
  private copyHistory(): Move[] {
    const newHistory: Move[] = [];
    for (const historyMove of this.historyMoves) {
      newHistory.push(historyMove);
    }
    return newHistory;
  }
 
  private addMoveToHistory(move: Move): GameState {
    const newHistory = this.copyHistory();
    newHistory.push(move);
    return new GameState(this.board, this.allPlayerStates, newHistory);
  }
 
  private removeLastHistoryMove(): GameState {
    const newHistory = this.copyHistory();
    newHistory.pop();
    return new GameState(this.board, this.allPlayerStates, newHistory);
  }
 
  public equals(other: GameState): boolean {
    // if (!other.hash().equals(this.hash())) {
    //   console.log(this.board.looseTile);
    //   console.log(other.board.looseTile);
    // }
    return other.hash().equals(this.hash());
  }
 
  public static create(instance: GameState): GameState {
    const historyMoves: Move[] = [];
    for (const historyMove of instance.historyMoves) {
      historyMoves.push(Move.create(historyMove));
    }
    return new GameState(
      Board.create(instance.board),
      AllPlayerStates.create(instance.allPlayerStates),
      historyMoves
    );
  }
 
  public hash(): Cyrb64 {
    Iif (this.hashCache === null) {
      this.hashCache = Cyrb64.hashString(JSON.stringify(this), 0);
    }
    return this.hashCache;
  }
}