我嘗試在Java中編寫一個用於連接四遊戲的MinMax程序,但該程序也應該適用於其他遊戲。但是,我遇到了一個問題,我幾天無法通過。節點的值設置不正確。我分享我負責生成樹的代碼片段。MinMax - 生成遊戲樹
也許你會注意到我犯了一個錯誤。
如果有人能幫助我,我會很高興。
public Node generateTree(Board board, int depth) {
Node rootNode = new Node(board);
generateSubtree(rootNode, depth);
minMax(rootNode, depth);
return rootNode;
}
private void generateSubtree(Node subRootNode, int depth) {
Board board = subRootNode.getBoard();
if (depth == 0) {
subRootNode.setValue(board.evaluateBoard());
return;
}
for (Move move : board.generateMoves()) {
Board tempBoard = board.makeMove(move);
Node tempNode = new Node(tempBoard);
subRootNode.addChild(tempNode);
generateSubtree(tempNode, depth - 1);
}
}
public void minMax(Node rootNode, int depth) {
maxMove(rootNode, depth);
}
public int maxMove(Node node, int depth) {
if (depth == 0) {
return node.getValue();
}
int bestValue = Integer.MIN_VALUE;
for (Node childNode : node.getChildren()) {
int tempValue = minMove(childNode, depth - 1);
childNode.setValue(tempValue);
if (tempValue > bestValue) {
bestValue = tempValue;
}
}
return bestValue;
}
public int minMove(Node node, int depth) {
if (depth == 0) {
return node.getValue();
}
int bestValue = Integer.MAX_VALUE;
for (Node childNode : node.getChildren()) {
int tempValue = maxMove(childNode, depth - 1);
childNode.setValue(tempValue);
if (tempValue < bestValue) {
bestValue = tempValue;
}
}
return bestValue;
}
局類是板狀態的表示。
移動類執行移動(整數[0-8]爲井字遊戲,[0-6]爲連接四)。
節點類擁有移動和價值移動是多好。並且,擁有所有的孩子。
在我用這個方法這樣的代碼:
Node newNode = minmax.generateTree(board, depth, board.getPlayer());
Move newMove = new TicTacToeMove(board.getPlayer(), newNode.getBestMove().getMove(), depth);
board = board.makeMove(newMove);
當很明顯,鑑於此舉是敗着(或獲獎),我沒有收到這個舉動。
如果您可以包含您輸入內容的示例,您認爲結果應該是什麼以及它是什麼,那將會很好。 – Mark
嗨, **董事會**類是董事會國家的代表。 **移動**類執行移動(tictactoe的整數[0-8],連接四的[0-6])。 **節點**類擁有移動和價值移動是多好。還擁有所有的孩子。 在代碼中,我使用這樣的方法: 'Node newNode = minmax.generateTree(board,depth,board.getPlayer()); 移動newMove = new TicTacToeMove(board.getPlayer(),newNode.getBestMove()。getMove(),depth); board = board.makeMove(newMove);' 而且當其明顯的舉動是一個失敗的舉動(或勝利)時,我沒有收到這個舉動。 – Xing92
什麼是「我沒有收到此舉」。意思?這是一款網絡遊戲嗎?輸贏是不是發送給你?你的意思是它沒有放在電路板上?你的樹沒有獲得新的條目嗎? – Mark