为什么我的tic-tac-toe的minimax在reactjs中返回undefined



我想用react hook为井字游戏制作一个AI,但我被卡住了,因为我的AI返回未定义的代码

const defaultScore = {
0: 0, 1: 0, 2: 0,
3: 0, 4: 0, 5: 0,
6: 0, 7: 0, 8: 0,
}
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 compareWin = (a, b, c) => {
return (c !== 0 && b === c && a === b)
}
const tryWin = (board: Object) => {//check if the game is in an end state
let win = null
winArray.forEach(v => {
if (compareWin(board[v[0]], board[v[1]], board[v[2]])) {
win = board[v[0]]
} else if (!Object.values(board).includes(0)) {
win = 'draw'
}
})
return win
}
const AI = 'O'
const human = 'X'

在不改变真实状态的情况下复制和编辑板的功能

const copyBoard = (original: Object, index?: any, newValue?: String) => {//
const copiedBoard = { ...original }
index = Number(index) // so it isn't a string
if (index != null && newValue != null) {
copiedBoard[index] = newValue
}
return copiedBoard
}   

最小最大算法

const miniMax = (board: Object, depth: number, isMax: Boolean) => {
if (tryWin(board) != null) {
const scoreOutcome = {
[AI]: 10,
[human]: -10,
'draw': 0
}
return scoreOutcome[tryWin(board)]
}

const outcome = (isMax) ? -10000 : +10000
if (isMax) {
Object.keys(board).forEach(v => {
if (board[v] === 0) {
const simBoard = copyBoard(board, v, AI)
const newOutcome = miniMax(simBoard, depth + 1, !isMax)
return (typeof (newOutcome) == 'undefined') ? outcome : Math.max(outcome, newOutcome) //it was returning undefined sometimes so to ensure it will always return an integer to confirm that wasn't the problem 
}
})
} else {
Object.keys(board).forEach(v => {
if (board[v] === 0) {
const simBoard = copyBoard(board, v, human)
const newOutcome = miniMax(simBoard, depth + 1, !isMax)
return (typeof (newOutcome) == 'undefined') ? outcome : Math.min(outcome, newOutcome) //this does not return undefined
}
})
}
}
const AImove = () => {
let move
let bestOutcome = -10000
Object.keys(boardState).forEach(v => {
if (boardState[v] === 0) {
const simBoard = copyBoard(boardState, v, AI)
const outcome = miniMax(simBoard, 0, true)
console.log('outcome', outcome) //this returns undefined 
if (outcome >= bestOutcome) {
bestOutcome = outcome
move = v
}
}
})
return move
}
const smartMoves = () => {
const finalPlay = AImove()
console.log('ai', finalPlay)
}

提前感谢你的帮助我已经为此被践踏了好几天了有一个完整代码的沙盒https://8e3gr.csb.app/

它是每个函数的

Object.keys(boardState).forEach(v => {})

将其转换为for。。。在或为。。。

for(const i in boardState){}
for(const i of boardState){}

返回预期结果原因我不太确定,我不想传播不准确的信息,所以如果你知道,请评论

最新更新