JSFiddle - React, Tailwind, and code Playground
HTML
<table id="ta1"></table>
<div id="message"></div>
JavaScript
let array1 = [0, 0, 0, 0, 0, 0, 0, 0, 0];
let player1 = -1;
let bestMove = -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 keineZuegeMehr(array) {
if (hasWon(array, player1)) {
return true;
}
if (hasWon(array, -player1)) {
return true;
}
for (let i = 0; i < array.length; i++) {
if (array[i] == 0) {
return false;
}
}
return true;
}
function bewerte(array, player) {
if (hasWon(array, player)) {
return -1;
}
if (hasWon(array, -player)) {
return 1;
}
return 0;
}
function minimax(array, player, recursiv) {
if (keineZuegeMehr(array)) {
return bewerte(array, player)
}
let maxScore = -2;
for (let i = 0; i < array.length; i++) {
if (array[i] == 0) {
array[i] = player;
if (hasWon(array, player)) {
array[i] = 0;
return 1;
}
let score = -minimax(array, -player, true);
array[i] = 0;
if (score > maxScore) {
maxScore = score;
if (!recursiv ) {
bestMove = i;
}
}
}
}
return maxScore;
}
function makeMove() {
let score = minimax(array1, player1, false);
if (bestMove != -1) {
...