Download source/src/training/ticTacToe.js from FormaLau/microduck-reachy-simulator: direct link, hf CLI and curl.
- Browser
- Download file 1.33 kB
-
https://huggingface.co/spaces/FormaLau/microduck-reachy-simulator/resolve/main/source/src/training/ticTacToe.js
- Command line
-
hf download hf://spaces/FormaLau/microduck-reachy-simulator/source/src/training/ticTacToe.js
-
curl -L -o ticTacToe.js https://huggingface.co/spaces/FormaLau/microduck-reachy-simulator/resolve/main/source/src/training/ticTacToe.js
1.33 kB
| export const WINNING_LINES = [ | |
| [0, 1, 2], [3, 4, 5], [6, 7, 8], | |
| [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], | |
| ]; | |
| export function boardResult(cells) { | |
| const line = WINNING_LINES.find(([a, b, c]) => cells[a] && cells[a] === cells[b] && cells[a] === cells[c]); | |
| return line ? { winner: cells[line[0]], line, finished: true } | |
| : { winner: 0, line: [], finished: cells.every(Boolean) }; | |
| } | |
| export function createTicTacToeState() { | |
| const cells = Array(9).fill(0); | |
| let turn = 1; | |
| return { | |
| cells, | |
| get turn() { return turn; }, | |
| get result() { return boardResult(cells); }, | |
| play(team, cell) { | |
| if (boardResult(cells).finished) throw new Error('Tic Tac Toe: the game is already over.'); | |
| if (team !== turn) throw new Error(`Tic Tac Toe: team ${turn} must play next.`); | |
| if (!Number.isInteger(cell) || cell < 1 || cell > 9) throw new Error('Tic Tac Toe: choose a cell from 1 to 9.'); | |
| if (cells[cell - 1]) throw new Error('Tic Tac Toe: this cell is occupied.'); | |
| cells[cell - 1] = team; | |
| turn = 3 - turn; | |
| return boardResult(cells); | |
| }, | |
| finish(winner) { | |
| const result = boardResult(cells); | |
| if (!result.finished || result.winner !== winner) throw new Error('Tic Tac Toe: your result does not match the board.'); | |
| return result; | |
| }, | |
| }; | |
| } | |