【发布时间】:2021-08-14 22:21:10
【问题描述】:
我正在尝试制作一个基本的国际象棋 AI。我有存储白色图形和黑色图形的 ArrayLists 的“Schach”类。当轮到 AI 移动时,我首先添加所有移动,然后在下一步中,我想删除那些让自己受到控制的移动。但出于某种原因,人工智能只是执行它拥有的每一个可能的动作。我什至没有更新主类中的列表,问题在于列表总是引用 AI 类中的列表。
ALSO 我已经尝试过 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 function (works fine no reference here for sure)
}
编辑
使用此设置,ai 根本不应该执行移动,只需计算它们...
编辑 2 resetLists 函数是主要问题(我猜)
【问题讨论】:
-
您的列表被声明为类成员。你知道后果吗?
-
不...你是什么意思?
-
@TimothyTruckle 你的意思是它们是静态的?我知道,而且应该是这样的。但我不明白这会如何阻止人工智能完成它的工作。基本上我只是想将 Schach 中的静态列表复制到 AI 中的静态列表中,而不会将它们相互连接。
-
“我知道,应该是这样的。” -- 你的认识是错误的。特别是对于变量,只有在有充分理由的情况下才应使用
static关键字。
标签: java reference artificial-intelligence