fuzzyworld

dao-game / files / src / game / game-board.ts

game-board.ts

2.3 KB · history · blame

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