xxxxxxxxxx
65
function copyBoard(board) {
let newBoard = createBoard();
for (let i = 0; i < COLS; i++) {
for (let j = 0; j < ROWS; j++) {
newBoard[i][j] = board[i][j];
}
}
return newBoard;
}
function findBestMove(board, player) {
let bestScore = -Infinity;
let bestMoves = [];
for (let n = 0; n < COLS; n++) {
const newBoard = copyBoard(board);
if (makeMove(newBoard, n, player)) {
let score = 0;
if (checkWin(newBoard, player)) {
score = Infinity;
} else if (checkWin(newBoard, player == PLAYER.red ? PLAYER.yellow : PLAYER.red)) {
score = -Infinity;
} else {
score = -search(newBoard, player == PLAYER.red ? PLAYER.yellow : PLAYER.red)
}
if (score > bestScore) {
bestMoves = [n];
bestScore = score;
} else if (score == bestScore) {
bestMoves.push(n);
}
}
}
return random(bestMoves);
}
function search(board, player, depth=4) {
let bestScore = -Infinity;
for (let n = 0; n < COLS; n++) {
const newBoard = copyBoard(board);
if (makeMove(newBoard, n, player)) {
let score = 0;
if (checkWin(newBoard, player)) {
score = Infinity;
} else if (checkWin(newBoard, player == PLAYER.red ? PLAYER.yellow : PLAYER.red)) {
score = -Infinity;
} else if (depth > 0) {
score = -search(newBoard, player == PLAYER.red ? PLAYER.yellow : PLAYER.red, depth-1)
} else {
score = evaluate(newBoard, player);
}
if (score > bestScore) {
bestScore = score;
}
}
}
return bestScore;
}
function evaluate(board, player) {
return 0;
}