基于信念状态的Pacman AI(A*算法)索引越界问题排查
Pacman信念状态AI的IndexOutOfBoundsException异常排查与解决
异常信息
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at logic.AI.updatePath(AI.java:164) at logic.AI.findNextMove(AI.java:130) at logic.PacManLauncher.animate(PacManLauncher.java:176) at logic.PacManLauncher.main(PacManLauncher.java:41)
核心原因
异常触发在AI.java第164行的String direction = actions.get(j);,本质是动作列表与对应信念状态列表长度不匹配:
- 代码逻辑假设
Plans中每个actions列表的长度,和对应的Result里的beliefStates列表长度完全一致,但实际运行时出现了result.size() > actions.size()的情况,导致循环索引j超出动作列表的边界。 Plans类的addPlan方法未对传入的Result和动作列表做长度校验,无法保证数据一致性。updatePath方法的内层循环直接用同一索引j访问两个列表,未做边界检查。
解决方案
1. 强制Plans数据一致性
修改Plans的addPlan方法,添加校验逻辑,确保动作列表与信念状态数量严格匹配:
public void addPlan(Result beliefBeliefState, List<String> action) { if (beliefBeliefState.size() != action.size()) { throw new IllegalArgumentException("动作列表长度必须与信念状态数量一致"); } this.results.add(beliefBeliefState); this.actions.add(action); }
2. 增加循环边界保护
在updatePath的内层循环中,先检查索引合法性,避免越界:
for (int j = 0; j < result.size(); j++) { BeliefState child = result.getBeliefState(j); // 检查索引是否在动作列表的合法范围内 if (j >= actions.size()) { System.err.println("警告:动作列表与信念状态数量不匹配,跳过索引" + j); continue; } String direction = actions.get(j); // 后续逻辑保持不变 List<String> tempPath = new ArrayList<>(path); tempPath.add(direction); System.out.println("Temp path: " + tempPath); Heuristic heuristic = new SimpleHeuristic(); double costToGo = heuristic.calculate(child); double evaluation = evaluateResult(child); totalEvaluation += evaluation; if (!visited.contains(child)) { fringe.add(new Node(child, costToGo)); pathToCurrent.add(new PathNode(tempPath, costToGo)); } }
3. 检查信念状态扩展逻辑
排查beliefState.extendsBeliefState()方法的实现,确保生成Plans时,每个Result的信念状态列表和对应动作列表的元素数量严格一一对应,从根源避免数据不匹配问题。
内容的提问来源于stack exchange,提问作者gringos91
相关产品推荐
相关产品推荐

