我想用react钩子为tic脚趾创建一个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/
发布于 2022-01-27 00:25:39
它是每个函数的
Object.keys(boardState).forEach(v => {})
将其转换为for...in或for...of
for(const i in boardState){}
for(const i of boardState){}
返回预期的结果,原因是我不太确定,我不想散布不准确的信息,所以如果你知道,请评论
https://stackoverflow.com/questions/70836635
复制相似问题