bhlangonijr / chesslib

chess library for legal move generation, FEN/PGN parsing and more
Apache License 2.0
223 stars 78 forks source link

Add more checks for FEN validity when reading FEN #52

Closed dlbbld closed 3 years ago

dlbbld commented 3 years ago

I suggest to add more tests when reading the FEN. At the very least you should not allow a position where the opponent king of the player having the move is in check! I think as such you could improve the API further. Please see examples below, I hope you get the idea:

final Board board = new Board();

// side field contains invalid char - accepted - not ok
board.loadFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR x KQkq - 0 1");

// castling field contains invalid char - accepted - not ok
board.loadFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w xQkq - 0 1");

// position field contains non complete rank - accepted - not ok
board.loadFromFen("rnbqkbnr/pppppppp/7/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");

// position field contains non possible value (opponent king in check) - accepted - not ok
board.loadFromFen("4k3/8/8/8/8/8/4R3/4K3 w - - 0 1");

// castling field contains non possible value for position - accepted - not ok
board.loadFromFen("4k3/8/8/8/8/8/8/4KR2 w K - 0 1");

// en passant field contains non possible value for position - accepted - not ok
board.loadFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq e3 0 1");

// halfmove counter contains non possible value (too big in regard to fullmove counter) - accepted - not ok
board.loadFromFen("4k3/8/8/8/8/8/8/4KR2 w - - 500 50");
dlbbld commented 3 years ago

Is there any check on this? When I supply an incorrect FEN, I prefer the system to complain, instead of doing something unexpected.

For example, when I mistype the side field, the system assumes that Black has the move. It would be much better to throw an exception, informing that the FEN is wrong. For example:

final Board board = new Board();
// invalid side field
board.loadFromFen("r1bqk1nr/pppp1ppp/2n5/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQK2R x KQkq - 0 4");
// board assumes black has the move
System.out.println(board.getSideToMove()); // BLACK
bhlangonijr commented 3 years ago

I am looking into this one. Will fix in the next release.

dlbbld commented 3 years ago

Closing the issue as it became stale.