嗨,所以我最近开始用java编程,我给自己设置了一个任务,为我制作的一个tic tac toe游戏制作一个AI,然而minmax算法抛出了一个Stack Overflow错误,我看不到错误或程序中的问题所在。
下面是程序:
public State minmax(boolean max, State currentState)
{
if (currentState.getNull() == 0) {
return currentState;
}
else {
State[] successorStates = currentState.getSuccessorStates(aiPlayer);
ArrayList<Integer> scoresTemp = new ArrayList<>();
for (State state : successorStates) {
scoresTemp.add(evaluate(aiPlayer, minmax(!max, state)));
}
Integer[] scores = (Integer[]) scoresTemp.toArray();
if (max) {
State maxState = successorStates[0];
int maxScore = evaluate(aiPlayer, maxState);
for (int score : scores) {
if (scores[0] > maxScore) {
maxScore = score;
maxState = successorStates[score];
}
}
return maxState;
}
else
{
State minState = successorStates[0];
int minScore = evaluate(aiPlayer, minState);
for (int score : scores) {
if (scores[0] > minScore) {
minScore = score;
}
}
return minState;
}
}
}它返回最好的移动状态。
getNull()返回可以播放的剩余空间大小。
getSuccesorStates( Player )返回该状态的所有后续状态,方法是创建一个新状态,其中包含玩家的旧动作和新动作。
evaluate()返回值-1、0或1,具体取决于该状态下的获胜、平局或失败。None返回0
编辑:
public int getNull()
{
int amount = 0;
for (int x =0; x<9; x++)
{
if (getAllCells()[x]==null)
{
amount++;
}
}
return amount;
}
public State[] getSuccessorStates(Player player)
{
State[] states = new State[getNull()];
Player[][] stateCells = cells.clone();
int[][] nullPositions = getNulls();
for (int x=0; x<getNull(); x++)
{
stateCells[nullPositions[x][0]][nullPositions[x][1]] = player;
states[x] = new State(player, stateCells);
stateCells = cells.clone();
}
return states;
}
Caused by: java.lang.StackOverflowError
at sample.AI.minmax(AI.java:23)
at sample.AI.minmax(AI.java:32)
at sample.AI.minmax(AI.java:32)
.
.
.23:if (currentState.getNull() == 0)
32:scoresTemp.add(evaluate(aiPlayer, minmax(!max, state)));
public Player[] getAllCells()
{
Player[] cellList = new Player[9];
for (int x = 0; x<3; x++)
{
for (int y = 0; y<3; y++)
{
cellList[y*3+x] = cells[x][y];
}
}
return cellList;
}在中调用minmax:
public Ply getPly(State state)
{
State bestState = minmax(true, state);
State[] successorStates = state.getSuccessorStates(aiPlayer);
ArrayList<State> states = new ArrayList<State>();
for (int x=0; x<successorStates.length; x++)
{
states.add(successorStates[x]);
}
int[][] nulls = state.getNulls();
Ply bestPly = new Ply(aiPlayer, nulls[states.indexOf(bestState)][0], nulls[states.indexOf(bestState)][1]);
return bestPly;
}如果有人能帮上忙,谢谢:)
发布于 2016-09-04 05:58:47
你的问题在这里:
scoresTemp.add(evaluate(aiPlayer,minmax(!max,state);
当您调用minmax方法时,您会创建一堆耗尽内存的数据( java允许使用一定数量的计算机内存)。然后,在minmax内部再次调用minmax,让它创建更多的数据,这会无限地发生,直到内存耗尽,Java抛出StackOverflow异常。
https://stackoverflow.com/questions/39309585
复制相似问题