fuzzyworld

dao-game / peerjs-browser-bug / files / src / game-board.ts

Branch peerjs-browser-bug · default branch · all branches

game-board.ts

2.3 KB · history · blame

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