
com.fathzer.chess.utils.evaluators.AbstractNaiveEvaluator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of chess-utils Show documentation
Show all versions of chess-utils Show documentation
Some helpful piece of code to implement chess engines.
The newest version!
package com.fathzer.chess.utils.evaluators;
import static com.fathzer.chess.utils.Pieces.*;
import com.fathzer.chess.utils.Pieces;
import com.fathzer.chess.utils.adapters.BoardExplorerBuilder;
import com.fathzer.games.MoveGenerator;
import com.fathzer.games.ai.evaluation.Evaluator;
import com.fathzer.games.ai.evaluation.ZeroSumEvaluator;
import com.fathzer.games.util.Stack;
/** A naive incremental evaluator that only uses the standard valuation of pieces.
* @param The type of moves
* @param The type of chess board
*/
public abstract class AbstractNaiveEvaluator> implements ZeroSumEvaluator, Evaluator, BoardExplorerBuilder {
private final Stack scores;
private int toCommit;
/** Default constructor
*/
protected AbstractNaiveEvaluator() {
this.scores = new Stack<>(null);
}
/** Constructor.
* @param score The score to initialize the evaluator
*/
protected AbstractNaiveEvaluator(int score) {
this.scores = new Stack<>(null);
scores.set(score);
}
/** Get the piece captured by the move.
* @param board The board
* @param move The move
* @return a piece type index. See {@link Pieces} to learn which integer corresponds to which piece type.
*/
protected abstract int getCapturedType(B board, M move);
/** Get the promotion made by the move.
* @param board The board
* @param move The move
* @return a piece type index. See {@link Pieces} to learn which integer corresponds to which piece type.
*/
protected abstract int getPromotionType(B board, M move);
@Override
public void init(B board) {
scores.clear();
scores.set(getPieces(board).map(p -> p>0?getPoints(p):-getPoints(-p)).sum());
}
@Override
public int evaluateAsWhite(B board) {
return 100*scores.get();
}
/** Creates a new instance initialized with a score.
* @param score The initial score.
* @return a new evaluator of the same class as this, this the same view point, and initialized with the score.
*/
protected abstract AbstractNaiveEvaluator fork(int score);
@Override
public AbstractNaiveEvaluator fork() {
return fork(scores.get());
}
@Override
public void prepareMove(B board, M move) {
int increment = 0;
final int capturedPiece = getCapturedType(board, move);
if (capturedPiece!=0) {
increment = getPoints(capturedPiece);
}
final int promotion = getPromotionType(board, move);
if (promotion!=0) {
increment = increment + getPoints(promotion)-getPoints(PAWN);
}
if (!board.isWhiteToMove()) {
increment = -increment;
}
toCommit = scores.get()+increment;
}
@Override
public void commitMove() {
scores.next();
scores.set(toCommit);
}
@Override
public void unmakeMove() {
scores.previous();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy