tests: game and tic tac toe
This commit is contained in:
+16
-16
@@ -13,30 +13,18 @@ type TurnResult = {
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
};
|
||||
|
||||
function getBoardRegion(host: IGameContext) {
|
||||
export function getBoardRegion(host: IGameContext) {
|
||||
return host.regions.get('board');
|
||||
}
|
||||
|
||||
function isCellOccupied(host: IGameContext, row: number, col: number): boolean {
|
||||
export function isCellOccupied(host: IGameContext, row: number, col: number): boolean {
|
||||
const board = getBoardRegion(host);
|
||||
return board.value.children.some(
|
||||
(child: { value: { position: number[] } }) => child.value.position[0] === row && child.value.position[1] === col
|
||||
);
|
||||
}
|
||||
|
||||
function checkWinner(host: IGameContext): 'X' | 'O' | 'draw' | null {
|
||||
const parts = Object.values(host.parts.collection.value).map((s: { value: Part }) => s.value);
|
||||
|
||||
const xPositions = parts.filter((_: Part, i: number) => i % 2 === 0).map((p: Part) => p.position);
|
||||
const oPositions = parts.filter((_: Part, i: number) => i % 2 === 1).map((p: Part) => p.position);
|
||||
|
||||
if (hasWinningLine(xPositions)) return 'X';
|
||||
if (hasWinningLine(oPositions)) return 'O';
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasWinningLine(positions: number[][]): boolean {
|
||||
export function hasWinningLine(positions: number[][]): boolean {
|
||||
const lines = [
|
||||
[[0, 0], [0, 1], [0, 2]],
|
||||
[[1, 0], [1, 1], [1, 2]],
|
||||
@@ -55,7 +43,19 @@ function hasWinningLine(positions: number[][]): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function placePiece(host: IGameContext, row: number, col: number, moveCount: number) {
|
||||
export function checkWinner(host: IGameContext): 'X' | 'O' | 'draw' | null {
|
||||
const parts = Object.values(host.parts.collection.value).map((s: { value: Part }) => s.value);
|
||||
|
||||
const xPositions = parts.filter((_: Part, i: number) => i % 2 === 0).map((p: Part) => p.position);
|
||||
const oPositions = parts.filter((_: Part, i: number) => i % 2 === 1).map((p: Part) => p.position);
|
||||
|
||||
if (hasWinningLine(xPositions)) return 'X';
|
||||
if (hasWinningLine(oPositions)) return 'O';
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function placePiece(host: IGameContext, row: number, col: number, moveCount: number) {
|
||||
const board = getBoardRegion(host);
|
||||
const piece: Part = {
|
||||
id: `piece-${moveCount}`,
|
||||
|
||||
Reference in New Issue
Block a user