dao-game / react / files / src / game / game-board.ts
Branch react · default branch · all branches
game-board.ts
| 1 | import { Coord } from "./coord"; |
| 2 | |
| 3 | export class GameBoard { |
| 4 | public board: (string | null)[]; |
| 5 | public readonly size: Coord; |
| 6 | public readonly player1Id: string; |
| 7 | public readonly player2Id: string; |
| 8 | |
| 9 | public constructor(player1Id: string, player2Id: string) { |
| 10 | // default board |
| 11 | const defaultBoard = ([] as (string | null)[]).concat.apply([], [ |
| 12 | [player1Id, null, null, player2Id], |
| 13 | [null, player1Id, player2Id, null], |
| 14 | [null, player2Id, player1Id, null], |
| 15 | [player2Id, null, null, player1Id]]); |
| 16 | const testBoard = ([] as (string | null)[]).concat.apply([], [ |
| 17 | [player1Id, null, player2Id, player2Id], |
| 18 | [player1Id, null, player2Id, null], |
| 19 | [player1Id, null, null, null], |
| 20 | [null, player1Id, null, player2Id]]); |
| 21 | this.board = defaultBoard; |
| 22 | this.size = new Coord(4, 4); |
| 23 | this.player1Id = player1Id; |
| 24 | this.player2Id = player2Id; |
| 25 | } |
| 26 | public move(source: Coord, dest: Coord): void { |
| 27 | const piece = this.getPiece(source); |
| 28 | if (piece === null) |
| 29 | throw `Source ${source} points to an empty space`; |
| 30 | this.setPiece(source, null); |
| 31 | this.setPiece(dest, piece); |
| 32 | } |
| 33 | public getPiece(coord: Coord): string | null { |
| 34 | const index = this.coordToBoardIndex(coord); |
| 35 | if (!Number.isSafeInteger(index) || index < 0 || index >= this.board.length) |
| 36 | throw `Index ${index} is out of bounds`; |
| 37 | const id = this.board[index]; |
| 38 | return id; |
| 39 | } |
| 40 | public getCoords(id: string): Coord[] { |
| 41 | const coords = this.board |
| 42 | .map((pieceId, index) => { |
| 43 | const isTarget = pieceId === id; |
| 44 | return isTarget ? this.boardIndexToCoord(index) : null; |
| 45 | }) |
| 46 | .filter((coord) => coord !== null) |
| 47 | .map(coord => coord!); |
| 48 | return coords; |
| 49 | } |
| 50 | private setPiece(coord: Coord, piece: string | null): void { |
| 51 | const { player1Id, player2Id } = this; |
| 52 | if (piece !== null && piece !== player1Id && piece !== player2Id) |
| 53 | throw `Invalid piece specified: ${piece}`; |
| 54 | const index = this.coordToBoardIndex(coord); |
| 55 | if (!Number.isSafeInteger(index) || index < 0 || index >= this.board.length) |
| 56 | throw `Index ${index} is out of bounds`; |
| 57 | this.board[index] = piece; |
| 58 | } |
| 59 | public coordToBoardIndex(coord: Coord): number { |
| 60 | const { row, col } = coord; |
| 61 | const index = row * this.size.col + col; |
| 62 | return index; |
| 63 | } |
| 64 | public boardIndexToCoord(index: number): Coord { |
| 65 | const col = index % this.size.col; |
| 66 | const row = Math.floor(index / this.size.col); |
| 67 | return new Coord(row, col); |
| 68 | } |
| 69 | } |