I wanna use the minimax algorithm in tic tac toe. But I dont know how I could change my code. Right now the computer is choosing a random x on the board and checking if its available. I have read about it and seen some people do it but they have very similar code. I have a different one. I dont understand how to call the minimax on each available spot and the bestScore and bestMove stuff. this is my code now: check the snippet
const cellElement = document.querySelectorAll('[data-cell]')
const winner = document.getElementById("winner")
const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
let nextTurn = true
let win = true
function createCells() {
cellElement.forEach(cell => {
cell.addEventListener("click", cellButton, { once: true })
});
}
createCells()
function cellButton(e) {
const cell = e.target
playerTurn(cell)
checkWin()
computerTurn(cell)
checkWin()
//check for draw
}
function playerTurn(cell) {
if (nextTurn == false) {
if (cell.innerHTML !== "✖") {
cell.innerHTML = "O"
nextTurn = true
} else {
alert("Choose another cell")
}
}
}
function computerTurn(cell) {
let i = Math.floor(Math.random() * cellElement.length);
if (nextTurn) {
if (cellElement[i].innerHTML !== "✖" && cellElement[i].innerHTML !== "O") {
cellElement[i].innerHTML = "✖";
checkWin()
nextTurn = false
}
return computerTurn();
}
}
computerTurn()
function checkWin() {
if (win) {
for (let winCondition of winningConditions) {
if (winCondition.every(i => cellElement[i].innerHTML == "O")) {
winner.innerHTML = "O WON!!!"
win = false
} else if (winCondition.every(i => cellElement[i].innerHTML == "✖")) {
winner.innerHTML = "X WON!!!"
win = false
}
}
}
}
body{
background-color: #55E9BC;
display: flex;
justify-content: center;
}
.board{
position: relative;
width: 300px;
height: 300px;
top: 70%;
display: grid;
grid-template-columns: repeat(3, auto);
}
.cell{
background-color:#11D3BC;
color: #FFFCCA;
width: 100px;
height: 100px;
margin: 1px;
font-size: 80px;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
#winner{
position: absolute;
top: 250px;
font-weight: bold;
color: #3ab871;
font-size: 40px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
<p id="winner"></p>
<div class="board">
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
</div>