āā Tic-Tac-Toe
š± Tap a cell to place your mark | š„ 2 Players or š¤ vs CPU
Player ā's turn!
/* === TIC TAC TOE - MINIMAX AI === */
const board = ['','','','','','','','',''];
let currentPlayer = 'X';
const winCombos = [
[0,1,2],[3,4,5],[6,7,8], // rows
[0,3,6],[1,4,7],[2,5,8], // cols
[0,4,8],[2,4,6] // diagonals
];
function checkWinner(b) {
for (let [a,bx,c] of winCombos)
if (b[a] && b[a]===b[bx] && b[a]===b[c]) return b[a];
return b.every(c=>c) ? 'Draw' : null;
}
// Minimax AI - tries all moves recursively
function minimax(b, isMax) {
const w = checkWinner(b);
if (w==='O') return +10;
if (w==='X') return -10;
if (b.every(c=>c)) return 0;
let best = isMax ? -Infinity : Infinity;
for (let i=0; i<9; i++) {
if (!b[i]) {
b[i] = isMax ? 'O' : 'X';
const score = minimax(b, !isMax);
b[i] = '';
best = isMax ? Math.max(best,score) : Math.min(best,score);
}
}
return best;
}
function cpuMove() {
let best = -Infinity, move = -1;
for (let i=0; i<9; i++) {
if (!board[i]) {
board[i] = 'O';
const s = minimax(board, false);
board[i] = '';
if (s > best) { best=s; move=i; }
}
}
board[move] = 'O';
}