所以我在next js中写了这段代码。由于某种原因,它不能正常工作。我几乎尝试了所有方法,但仍然不能正常工作。我甚至尝试使用alpha beta修剪,但它仍然不能正常工作。它所做的就是按顺序返回值。就像如果位置0,1,2,3,4可用,bot将播放0,然后1和2等等。帮我修复它。
"use client";
import React, { useState, useEffect } from "react";
import "./GameMenu.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faRefresh } from "@fortawesome/free-solid-svg-icons/faRefresh";
import WonScreen from "./WonScreen";
import { Tooltip } from "react-tooltip";
const GameMenu = () => {
type board = {
[key: number]: string;
};
const defaultBoard: board = {
0: "",
1: "",
2: "",
3: "",
4: "",
5: "",
6: "",
7: "",
8: "",
};
const [turn, setTurn] = useState<"human" | "bot">("human");
const [won, setWon] = useState(false);
const [boardData, setBoardData] = useState<board>(defaultBoard);
const ai = "O";
const human = "X";
const [tries, setTries] = useState(0);
const winCondition = [
[0, 1, 2],
[0, 4, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[3, 4, 5],
[2, 4, 6],
[6, 7, 8],
];
let scores = {
X: 10,
O: -10,
tie: 0,
};
const updateBoardData = (idx: keyof board) => {
if (won || boardData[idx] !== "") return;
setTurn("bot");
setTries(tries + 1);
setBoardData({ ...boardData, [idx]: "X" });
};
useEffect(() => {
if (tries < 9 && turn === "bot") {
findBestMove();
}
}, [boardData, tries, turn]);
const checkWinner = (board: board) => {
let winner = null;
winCondition.forEach((bd) => {
const [a, b, c] = bd;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
winner = board[a];
}
for (let i = 0; i < 3; i++) {
if (board[i] !== "" && board[i + 3] !== "" && board[i + 6] !== "") {
winner = "tie";
}
}
});
return winner;
};
useEffect(() => {
let win = checkWinner(boardData);
if (win == "X" || win == "O") {
setWon(true);
}
}, [boardData]);
const restart = () => {
setBoardData(defaultBoard);
setWon(false);
setTries(0);
setTurn("human");
};
const minimax = (board: board, isMaximizing: boolean): number => {
const result = checkWinner(board);
if (result !== null) {
return scores[result];
}
let bestScore = isMaximizing ? -Infinity : Infinity;
for (let i = 0; i < Object.keys(board).length; i++) {
if (board[i] === "") {
board[i] = isMaximizing ? ai : human;
const score = minimax(board, !isMaximizing);
console.log(score);
board[i] = ""; // Reset the board for the next iteration
if (isMaximizing) {
bestScore = Math.max(score, bestScore);
} else {
bestScore = Math.min(score, bestScore);
}
}
}
return bestScore;
};
const findBestMove = () => {
let bestMove = -Infinity;
let move;
const board = { ...boardData };
for (let i = 0; i < Object.keys(board).length; i++) {
if (board[i] === "") {
board[i] = ai;
const score = minimax(board, false);
board[i] = "";
if (score > bestMove) {
bestMove = score;
move = i;
}
}
}
const updatedBoard = { ...boardData, [move]: ai };
setTurn("human");
setBoardData(updatedBoard);
setTries(tries + 1);
};
字符串
结果不准确
1条答案
按热度按时间62o28rlo1#
Minimax算法是用来玩电脑游戏的,也许你应该试着最小化那个叫做best move的变量的值,然后你就能得到正确的答案,也许你要求人类先走一步,这也很可能是问题所在。