我正在用 Java 编写简单的塔防游戏。这是查找从 spawn(在构造函数中设置)到最近基址的路径的方法。
public int[] findPath(Field startField) {
ArrayList<TestMonster> monsrs = new ArrayList<TestMonster>();
TestMonster first = new TestMonster(startField.getCenter(), getStartingDirection(startField), new int[0]);
monsters.add(first);
while (true) {
for (TestMonster monsr : monsrs) {
monster.move();
if (getFieldFromCenter(monsr.getPoint()).getState() == 101)
return monsr.getPath();
Field field = getFieldFromCenter(monsr.getPoint());
if (field.isUp())
monsters.add(new TestMonster(monsr.getPoint(), 0, monster.getPath()));
if (field.isRight())
monsters.add(new TestMonster(monsr.getPoint(), 90, monster.getPath()));
if (field.isDown())
monsters.add(new TestMonster(monsr.getPoint(), 180, monster.getPath()));
if (field.isLeft())
monsters.add(new TestMonster(monsr.getPoint(), 270, monster.getPath()));
if (monsrs.isEmpty())
return null;
}
}
}
如果没有路径,它可能会返回怪物移动到基地的下一个方向的数组或 null。它遍历作为 Field 类对象的字段。在每场怪物搜索可能的动作,并为每一个创造新的怪物与设定的方向。新怪物继承也会移动数组以添加它自己的方向,然后将其提供给新怪物等等。我的问题是我的代码中哪里有并发 mod ex 的可能性?我该如何预防呢?
堆栈跟踪:
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at towerdefence.MainPanel.findPath(MainPanel.java:160)
at towerdefence.MainPanel$1.actionPerformed(MainPanel.java:62)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:306)
at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:250)
at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:2971)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2963)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
at java.awt.Component.processEvent(Component.java:6282)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)