Files
3DChess/app/src/main/java/chess/ai/HungryAI.java
Persson-dev 3b38e0da1f Super IA (#5)
Reviewed-on: #5
Co-authored-by: Persson-dev <sim16.prib@gmail.com>
Co-committed-by: Persson-dev <sim16.prib@gmail.com>
2025-04-30 18:28:01 +00:00

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));
}
}