(tic-tac-toe): Added button to restart game.

This commit is contained in:
Alessandro Petitcollin 2025-12-07 01:31:29 +01:00
parent 9653b0cbe6
commit fb1b69a0ae
2 changed files with 35 additions and 7 deletions

View file

@ -10,4 +10,7 @@
<div class="bg-blue-500 h-32 flex items-center justify-center text-white text-xl font-bold hover:bg-red-700 ttt-grid-cell"> </div>
<div class="bg-blue-500 h-32 flex items-center justify-center text-white text-xl font-bold hover:bg-red-700 ttt-grid-cell"> </div>
</div>
</div>
<button id="ttt-restart-btn" class="mt-8 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Restart Game
</button>
</div>

View file

@ -75,6 +75,12 @@ class TTC {
return 'ongoing';
}
public reset(): void {
this.board = [null,null,null,null,null,null,null,null,null];
this.currentPlayer = 'X';
this.isGameOver = false;
};
// Attempts to place the current player's mark on the specified cell.
// @param idx - The index of the board (0-8) to place the mark.
// @returns The resulting game state, or `invalidMove` if the move is illegal.
@ -119,13 +125,24 @@ async function handleTTT(): Promise<RouteHandlerReturn>
return {
html: tttPage,
postInsert: async (app) => {
let cells = app?.querySelectorAll<HTMLDivElement>(".ttt-grid-cell");
if (!app) {
return;
}
const cells = app.querySelectorAll<HTMLDivElement>(".ttt-grid-cell");
const restartBtn = app.querySelector<HTMLButtonElement>("#ttt-restart-btn");
const updateUI = () => {
const board_state = board.getBoard();
board_state.forEach((cell_state, cell_idx) => {
cells[cell_idx].innerText = cell_state !== null ? cell_state : " ";
});
};
console.log(cells);
cells?.forEach(function (c, idx) {
c.addEventListener('click', () =>
{
c.addEventListener('click', () => {
const result = board.makeMove(idx);
switch(result)
{
@ -140,6 +157,7 @@ async function handleTTT(): Promise<RouteHandlerReturn>
case ('winX'): {
showSuccess('X won');
app?.querySelector('.ttt-grid')?.classList.add('pointer-events-none');
break;
}
case ('winO'): {
@ -152,9 +170,16 @@ async function handleTTT(): Promise<RouteHandlerReturn>
const board_state = board.getBoard();
board_state.forEach( function (cell_state, cell_idx) {
cells[cell_idx].innerText = cell_state !== null ? cell_state : " ";
})
})
})
});
updateUI();
});
});
restartBtn?.addEventListener('click', () => {
board.reset();
updateUI();
showInfo('Game Restarted');
});
}
}
}