Reviewed-on: #5 Co-authored-by: Persson-dev <sim16.prib@gmail.com> Co-committed-by: Persson-dev <sim16.prib@gmail.com>
62 lines
1.5 KiB
Java
62 lines
1.5 KiB
Java
package chess.ai;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Random;
|
|
|
|
import chess.controller.CommandExecutor;
|
|
import chess.controller.commands.MoveCommand;
|
|
import chess.controller.commands.PromoteCommand;
|
|
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
import chess.model.Color;
|
|
import chess.model.Coordinate;
|
|
import chess.model.Move;
|
|
import chess.model.Piece;
|
|
|
|
public class HungryAI extends AI {
|
|
|
|
private final PieceCost pieceCost;
|
|
private final Random random;
|
|
|
|
public HungryAI(CommandExecutor commandExecutor, Color color) {
|
|
super(commandExecutor, color);
|
|
this.pieceCost = new PieceCost(color);
|
|
this.random = new Random();
|
|
}
|
|
|
|
private int getMoveCost(Move move) {
|
|
Piece piece = pieceAt(move.getDeadPieceCoords());
|
|
return - (int) pieceCost.getCost(piece);
|
|
}
|
|
|
|
private List<Move> getBestMoves() {
|
|
List<Move> moves = getAllowedMoves();
|
|
List<Move> bestMoves = new ArrayList<>();
|
|
int bestCost = 0;
|
|
for (Move move : moves) {
|
|
int moveCost = getMoveCost(move);
|
|
if (moveCost == bestCost) {
|
|
bestMoves.add(move);
|
|
} else if (moveCost > bestCost) {
|
|
bestMoves.clear();
|
|
bestMoves.add(move);
|
|
bestCost = moveCost;
|
|
}
|
|
}
|
|
return bestMoves;
|
|
}
|
|
|
|
@Override
|
|
protected void play() {
|
|
List<Move> bestMoves = getBestMoves();
|
|
int randomMove = this.random.nextInt(bestMoves.size());
|
|
this.commandExecutor.executeCommand(new MoveCommand(bestMoves.get(randomMove)));
|
|
}
|
|
|
|
@Override
|
|
protected void promote(Coordinate pawnCoords) {
|
|
sendCommand(new PromoteCommand(PromoteType.Queen));
|
|
}
|
|
|
|
}
|