'why is my minimax recursion not looping through all possible outcomes
I'm not sure where I'm wrong with my function but it doesn't check every possible out it seems to check a few and I don't know how to fix it here's my code
basic variables
const defaultScore = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0}
const [boardState,setBoardState] = useState(defaultScore)
const winArray = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,6,4]]
const AI = side
const human = (side == 'X') ? 'O' : 'X'
a function to copy the current state of the board without changing the actual state
const copyBoard=(original :Object,index ?:any, newValue?:any)=>{
const copiedBoard = {...original}
index = Number(index)
if(index != null && newValue != null){
copiedBoard[index] = newValue
}
return copiedBoard
}
the function for checking end state
const tryWin=(board :Object)=>{
let win
let check = true
for (const i in winArray){
const v = winArray[i]
if(compareWin(board[v[0]],board[v[1]],board[v[2]])){
check = false
if(board[v[0]] == AI){
win = 10
}else{
win = -10
}
}
}
if(!Object.values(board).includes(0) && check){
win = 0
}
return win
}
the minimax
const miniMax = (board:Object, depth:number, isMax :Boolean ) =>{
if(typeof(tryWin(board)) == 'number'){
return tryWin(board)
}
if(isMax){
for (const v in board){
if(board[v] === 0){
const outcome = -100
let simBoard = copyBoard(board,v,AI)
const newOutcome = miniMax(simBoard,depth+1,!isMax)
return (typeof(newOutcome) == 'undefined') ? outcome : Math.max(outcome,newOutcome) - depth
}
}
}else{
for (const v in board){
if(board[v] === 0){
const outcome = 100
let simBoard = copyBoard(board,v,human)
const newOutcome = miniMax(simBoard,depth+1,!isMax)
return (typeof(newOutcome) == 'undefined') ? outcome : Math.min(outcome,newOutcome) + depth
}
}
}
}
const AImove =()=>{
let move
let bestOutcome = -100
for(const v in boardState){
if(boardState[v] === 0){
let simBoard = copyBoard(boardState,v,AI)
const outcome = miniMax(simBoard,0,true)
console.log('move',v,'outcome',outcome)
if(outcome > bestOutcome){
bestOutcome = outcome
move = Number(v)
}
}
}
return {move:move,outcome:bestOutcome}
}
what am I getting wrong?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
