Chess-Coding-Adventure icon indicating copy to clipboard operation
Chess-Coding-Adventure copied to clipboard

When checking EnPassant legality, why do you check if our king is behind our pawn?

Open FismanMaxim opened this issue 2 years ago • 3 comments

When you check the legality of an en passant capture, except for this capture opening a horizontal check, you also have this interesting condition, which I don't understand why it's necessary. As I understand the code, it seems to check that there's no friendly king behind the friendly pawn and looks like a rule "En passant cannot be used to avoid check", although this rule does not exist...

// check if 
enemy pawn is controlling this square (can't use pawn attack bitboard, because pawn has been captured)
	for (int i = 0; i < 2; i++) {
		// Check if square exists diagonal to friendly king from which enemy pawn could be attacking it
		if (numSquaresToEdge[friendlyKingSquare][pawnAttackDirections[friendlyColourIndex][i]] > 0) {
			// move in direction friendly pawns attack to get square from which enemy pawn would attack
			int piece = board.Square[friendlyKingSquare + directionOffsets[pawnAttackDirections[friendlyColourIndex][i]]];
			if (piece == (Piece.Pawn | opponentColour)) // is enemy pawn
			{
				return true;
			}
		}
	}

Why is this condition necessary?

FismanMaxim avatar Jul 04 '23 11:07 FismanMaxim

If there is a friendly king behind the pawn on the same file and the pawn captures en passant, and if there is an open file attacked by the enemy, then the move is illegal since the capture en passant revealed a check (basically a pin). But I've got to agree with you that I don't quite understand what this code does...

k-tten avatar Jul 10 '23 06:07 k-tten

@kelsny Yeah but if a friendly king is behind the pawn (any squares far behind, not just one), then the pawn is pinned vertically and cannot capture at all (lines ~268-270). So I don't think that that is what this code was intended to do...

FismanMaxim avatar Jul 10 '23 07:07 FismanMaxim

@FismanMaxim You could try taking that condition out and running Perft_Divide, comparing incorrect results with an engine like Stockfish. Then you can easily see what illegal moves this condition prevents. If it's the exact same, then the condition does nothing.

k-tten avatar Jul 11 '23 05:07 k-tten