-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathothello_ai.js
80 lines (63 loc) · 2.35 KB
/
othello_ai.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
////////// OTHELLO GAME AI BEHAVIOR \\\\\\\\\\
function aiTurn() {
let validMoves = [];
// Iterate through the grid to find all valid moves for the AI (player 2).
for (let row = 0; row < 8; row++) {
for (let column = 0; column < 8; column++) {
// If the cell is empty, check if it's a valid move for the AI.
if (discsGrid[row][column] === 0) {
let originalPlayerTurn = playerTurn;
// Temporarily set AI as the current player.
playerTurn = 2;
// If valid, store the move and its potential score (number of discs affected).
if (isValidMove(row, column)) {
let affectedDiscs = getAffectedDiscs(row, column);
validMoves.push({
row: row,
column: column,
affectedDiscs: affectedDiscs,
score: affectedDiscs.length
});
}
// Restore the original player's turn.
playerTurn = originalPlayerTurn;
}
}
}
// If no valid moves are found, switch back to player 1's turn.
if (validMoves.length === 0) {
playerTurn = 1;
isAiTurn = false;
// Check if the game is over or pass the turn.
gameOver();
return;
}
// Find the highest score among all valid moves.
let maxScore = -1;
for (let i = 0; i < validMoves.length; i++) {
if (validMoves[i].score > maxScore) {
maxScore = validMoves[i].score;
}
}
// Collect all moves that have the maximum score.
let bestMoves = [];
for (let i = 0; i < validMoves.length; i++) {
if (validMoves[i].score === maxScore) {
bestMoves.push(validMoves[i]);
}
}
// Randomly select one of the best moves (if multiple).
let randomIndex = Math.floor(Math.random() * bestMoves.length);
let bestMove = bestMoves[randomIndex];
// Place the AI disc and flip the affected discs on the board.
discsGrid[bestMove.row][bestMove.column] = 2;
flipDiscs(bestMove.affectedDiscs);
playerTurn = 1;
aiLastMoveRow = bestMove.row;
aiLastMoveColumn = bestMove.column;
drawDiscs();
drawValidMoves();
updateScore();
checkGameStatus();
isAiTurn = false;
}