Skip to content

Commit

Permalink
Add check for invalid pawn placement in validateFen (#412)
Browse files Browse the repository at this point in the history
  • Loading branch information
Manukyanq authored May 28, 2023
1 parent cf9cef2 commit 583f9ba
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions __tests__/validate_fen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ test.each([
fen: 'kk6/8/8/8/8/8/8/7K w - - 0 1',
ok: false,
},
{
// white pawn on 8th row
fen: '3P4/1k2K3/8/8/8/8/8/8 w - - 0 1',
ok: false,
},
{
// black pawn on 1st row
fen: '8/8/8/8/8/8/1k3K2/3p4 w - - 0 1',
ok: false,
},
{
fen: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNRw KQkq - 0 1',
ok: false,
Expand Down
12 changes: 12 additions & 0 deletions src/chess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,13 +379,15 @@ export function validateFen(fen: string) {
}
}

// 9th criterion: is en-passant square legal?
if (
(tokens[3][1] == '3' && tokens[1] == 'w') ||
(tokens[3][1] == '6' && tokens[1] == 'b')
) {
return { ok: false, error: 'Invalid FEN: illegal en-passant square' }
}

// 10th criterion: does chess position contain exact two kings?
const kings = [
{ color: 'white', regex: /K/g },
{ color: 'black', regex: /k/g },
Expand All @@ -401,6 +403,16 @@ export function validateFen(fen: string) {
}
}

// 11th criterion: are any pawns on the first or eighth rows?
if (
Array.from(rows[0] + rows[7]).some((char) => char.toUpperCase() === 'P')
) {
return {
ok: false,
error: 'Invalid FEN: some pawns are on the edge rows',
}
}

return { ok: true }
}

Expand Down

0 comments on commit 583f9ba

Please sign in to comment.