refactor: use part map for tictactoe
This commit is contained in:
@@ -24,7 +24,7 @@ export function createInitialState() {
|
||||
{ name: 'x', min: 0, max: BOARD_SIZE - 1 },
|
||||
{ name: 'y', min: 0, max: BOARD_SIZE - 1 },
|
||||
]),
|
||||
parts: [] as TicTacToePart[],
|
||||
parts: {} as Record<string, TicTacToePart>,
|
||||
currentPlayer: 'X' as PlayerType,
|
||||
winner: null as WinnerType,
|
||||
turn: 0,
|
||||
@@ -104,7 +104,7 @@ export function hasWinningLine(positions: number[][]): boolean {
|
||||
}
|
||||
|
||||
export function checkWinner(host: Entity<TicTacToeState>): WinnerType {
|
||||
const parts = host.value.parts;
|
||||
const parts = Object.values(host.value.parts);
|
||||
|
||||
const xPositions = parts.filter((p: TicTacToePart) => p.player === 'X').map((p: TicTacToePart) => p.position);
|
||||
const oPositions = parts.filter((p: TicTacToePart) => p.player === 'O').map((p: TicTacToePart) => p.position);
|
||||
@@ -118,7 +118,7 @@ export function checkWinner(host: Entity<TicTacToeState>): WinnerType {
|
||||
|
||||
export function placePiece(host: Entity<TicTacToeState>, row: number, col: number, player: PlayerType) {
|
||||
const board = host.value.board;
|
||||
const moveNumber = host.value.parts.length + 1;
|
||||
const moveNumber = Object.keys(host.value.parts).length + 1;
|
||||
const piece: TicTacToePart = {
|
||||
id: `piece-${player}-${moveNumber}`,
|
||||
regionId: 'board',
|
||||
@@ -126,7 +126,7 @@ export function placePiece(host: Entity<TicTacToeState>, row: number, col: numbe
|
||||
player,
|
||||
};
|
||||
host.produce(state => {
|
||||
state.parts.push(piece);
|
||||
state.parts[piece.id] = piece;
|
||||
board.childIds.push(piece.id);
|
||||
board.partMap[`${row},${col}`] = piece.id;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user