我正在尝试制作一个基本的国际象棋AI。我有一个名为”Schach”的类,它存储了白棋和黑棋的ArrayList。当轮到AI走棋时,我首先添加所有可能的走法,然后在下一步中我想移除那些会让自己处于将死的走法。但不知为何,AI只是执行了它所有的可能走法。我甚至没有在主类中更新列表,问题在于列表总是对AI类中的列表有引用。
另外 我已经尝试了clone()方法,但它不起作用。有什么建议吗?
public class Ai { public static final Ai ai = new Ai(); private static int maxY = 8; private static int maxX = 7; private static int minY = 1; private static int minX = 0; private static ArrayList<Entity> whiteFigures; private static ArrayList<Entity> blackFigures; private static ArrayList<Move> moves; public void processMoves() { moves = new ArrayList<Move>(); resetLists(); for (Entity e : blackFigures) { moves.addAll(calcMoves(e.getFigure(), blackFigures, whiteFigures)); } System.out.println(moves.size()); //removeCheckMoves(); System.out.println(moves.size()); executeMove(moves.get((int) (Math.random() * moves.size()))); resetLists(); Schach.turn = true; } private void removeCheckMoves() { Figure king = null; for (Entity e : blackFigures) { if (e.getFigure().type == Figure.king) { king = e.getFigure(); break; } } ArrayList<Move> legalMoves = new ArrayList<Move>(); for (Move m : moves) { resetLists(); executeMove(m); if(!isLegal(king)) { legalMoves.add(m); } } moves = legalMoves; } private boolean isLegal(Figure king) { boolean check = false; for (Entity w : whiteFigures) { for (Move move : Utils.calcMoves(w.getFigure(), whiteFigures, blackFigures)) { if (Utils.numToPos(move.to).x == king.x && Utils.numToPos(move.to).y == king.y) { check = true; break; } } if(check) break; } return check; } private void executeMove(Move m) { for (Entity e : blackFigures) { if (e.getFigure().x == Utils.numToPos(m.from).x && e.getFigure().y == Utils.numToPos(m.from).y) { e.getFigure().x = Utils.numToPos(m.to).x; e.getFigure().y = Utils.numToPos(m.to).y; e.gotoSquare(Utils.posToNum(e.getFigure()) - 8); for (Entity w : whiteFigures) { if (w.getFigure().x == e.getFigure().x && w.getFigure().y == e.getFigure().y) { whiteFigures.remove(w); break; } } break; } } } private void resetLists() { whiteFigures = new ArrayList<Entity>(); whiteFigures.clear(); whiteFigures.addAll(Schach.whiteFigures); blackFigures = new ArrayList<Entity>(); blackFigures.clear(); blackFigures.addAll(Schach.blackFigures); }//calcMoves函数(这里肯定没有引用,运行正常)}
编辑
有了这个设置,AI根本不应该执行任何走法,只需计算它们…
编辑2resetLists函数是主要问题(我猜)
回答:
好吧,我自己解决了。如果将来有人需要,这里是我的解决方案 😀
public static ArrayList<Entity> cloneList (ArrayList<Entity> array){ ArrayList<Entity> arr = new ArrayList<Entity>(); for(Entity e : array) { arr.add(cloneEntity(e)); } return arr; } public static Entity cloneEntity(Entity e) { Entity entity = new Entity(e.getPosition(), [etc...]); return entity; }