tests: game and tic tac toe

This commit is contained in:
2026-04-02 11:31:57 +08:00
parent 1cb7fa05ec
commit 846badc081
3 changed files with 488 additions and 16 deletions
+16 -16
View File
@@ -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}`,