JSFiddle - React, Tailwind, and code Playground
HTML
<table id="ta1"></table>
JavaScript
let array1 = [0, 0, 0, 0, 0, 0, 0, 0, 0];
let player1 = -1;
let move1 = -1;
function hasWon(array, player) {
for (let i = 0; i < 3; i++) {
let c1 = 0;
let c2 = 0;
for (let j = 0; j < 3; j++) {
const idx = i * 3 + j;
if (array[idx] == player)
c1++;
if (array[j * 3 + i] == player)
c2++;
}
if (c1 == 3 || c2 == 3) {
return true;
}
}
let c1 = 0;
let c2 = 0;
for (let i = 0; i < 3; i++) {
const idx1 = i * 3 + i;
const idx2 = i * 3 + (2 - i);
if (array[idx1] == player)
c1++;
if (array[idx2] == player)
c2++;
}
if (c1 == 3 || c2 == 3) {
return true;
}
return false;
}
function minimax(array, player) {
if (hasWon(array, player)) {
return 1;
}
let score = -2;
let move = -1;
for (let i = 0; i < array.length; i++) {
if (array[i] == 0) {
array[i] = player;
let score2 = -minimax(array, -player);
array[i] = 0;
if (score2 > score) {
score = score2;
move = i;
move1 = i;
}
}
}
if (move == -1)
return 0;
return score;
}
function makeMove() {
let score = minimax(array1, player1);
if (move1 != -1) {
array1[move1] = player1;
player1 = -player1;
move1 = -1;
makeTable();
}
}
function clickl(index) {
if (array1[index] == 0) {
array1[index] = player1;
player1 = -player1;
makeTable();
makeMove();
}
}
function makeTable() {
document.getElementById('ta1').innerHTML = '';
for (let i = 0; i < 3; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < 3; j++) {
const idx = i * 3 + j;
let td = document.createElement('td');
let bt = document.createElement('button');
bt.style.width = '50px';
bt.style.height = '25px';
bt.style.border = '1px...