//put list of pieces in a random order
Collections.shuffle(allPiecesFromOneSide);
int amountOfPieces = allPiecesFromOneSide.size();
int piecesChecked = 0;
boolean advancingMove = false;
Piece reservePiece = new Piece(), lastHope = new Piece();
int reserveX=0, reserveY=0, lastHopeX=0, lastHopeY=0;
Piece p;
ArrayList<ArrayList<Integer>> moves;
ArrayList<Integer> xList, yList, moveCheckOrder;
int moveAmount;
int moveLoc;
boolean moveDone = false;
//until advancing move is found or no pieces left to check
while (!advancingMove && piecesChecked<amountOfPieces) {
//get a piece
p = allPiecesFromOneSide.get(piecesChecked);
//get all possible moves that piece can do
moves = move.possiblePieceMoves(p, false);
xList = moves.get(0); //x coordinates
yList = moves.get(1); //y coordinates
moveAmount = xList.size(); //amount of moves
moveLoc = 0; //move index in list
//create order to check moves
moveCheckOrder = new ArrayList<Integer>();
for (int i=0; i<moveAmount; i++) {
moveCheckOrder.add(i);
}
//randomize order in which moves are checked
Collections.shuffle(moveCheckOrder);
int counter = 0;
if (moveAmount>0) { //if there's moves at all
//save first move as a reserve/last chance move
lastHope = p;
int firstMove = moveCheckOrder.get(0);
lastHopeX=xList.get(firstMove);
lastHopeY=yList.get(firstMove);
//while advancing move not found and still moves left
while (!advancingMove && counter<moveAmount) {
moveLoc = moveCheckOrder.get(counter); //get next move
//check if move is safe (enemy can't attack during next move)
if (isSquareSafe(xList.get(moveLoc), yList.get(moveLoc), player)) {
//best move is to advance/go forward: white -vertical, black +vertical
if(player.getSide()==0) { //if white side
//if advancing move
if(xList.get(moveLoc)<p.getRow()) {
advancingMove=true;
}
}
else { //black side
//if advancing move
if(xList.get(moveLoc)>p.getRow()) {
advancingMove=true;
}
}
//if not found a safe piece which can move forward
//put piece in reserve because at least it's safe
if(!advancingMove) {
reservePiece=p;
reserveX=xList.get(moveLoc);
reserveY=yList.get(moveLoc);
}
}
counter++;
}
if (advancingMove) { //advancing move found
move.doMove(player, board.coordinatesToNotation(p.getRow(),
p.getCol()), board.coordinatesToNotation(xList.get(moveLoc),
yList.get(moveLoc)));
moveDone=true;
}
}
piecesChecked++;