Skip to content

Commit

Permalink
It is not an ambiguous move when other pieces are pinned.
Browse files Browse the repository at this point in the history
  • Loading branch information
onspli committed Sep 17, 2021
1 parent 058a704 commit 260c0a8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
31 changes: 22 additions & 9 deletions src/FEN.php
Original file line number Diff line number Diff line change
Expand Up @@ -671,15 +671,25 @@ private function get_move_origin(Move $move) : Square

$origin_candidates = array_filter($origin_candidates, $does_origin_candidate_comply_with_move_origin);

if (sizeof($origin_candidates) == 0) {
$origin_candidates_legal = [];
$active_color = $this->get_active_color();
foreach ($origin_candidates as $origin)
{
$new_board = $this->get_new_board($move, $origin);
if (!$new_board->is_check($active_color)) {
$origin_candidates_legal[] = $origin;
}
}

if (sizeof($origin_candidates_legal) == 0) {
throw new RulesException("Invalid move.");
}

if (sizeof($origin_candidates) > 1) {
if (sizeof($origin_candidates_legal) > 1) {
throw new RulesException("Ambiguous move.");
}

return reset($origin_candidates);
return reset($origin_candidates_legal);
}

private function validate_move_target_square(Move $move) : void
Expand All @@ -706,12 +716,17 @@ private function validate_move_target_square(Move $move) : void
private function standard_move(Move &$move) : void
{
$this->validate_move_target_square($move);

$piece = $this->get_active_piece($move->get_piece_type());
$target = $move->get_target(true);
$origin = $this->get_move_origin($move);
$new_board = $this->get_new_board($move, $origin);
$this->set_new_board($new_board);
$move->set_origin($origin);
}

private function get_new_board(Move $move, Square $origin) : Board
{
$new_board = $this->board->copy();
$piece = $this->get_active_piece($move->get_piece_type());
$target = $move->get_target(true);

$new_board->set_square($origin, '');
if ($move->get_promotion()) {
Expand All @@ -726,9 +741,7 @@ private function standard_move(Move &$move) : void
}
}
}

$this->set_new_board($new_board);
$move->set_origin($origin);
return $new_board;
}

private function set_new_board(Board $new_board) : void
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/FENTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,11 @@ public function testMove() : void
$fen->move('Nc6');
$this->assertEquals('r1bqkbnr/pppp1ppp/2n5/4p3/4P3/P7/1PPP1PPP/RNBQKBNR w KQkq - 1 3', $fen->export());

// two pseudolegal moves Ne2, one knight pinned
$fen = new FEN("rn1qk1nr/pp1b1ppp/4p3/1B1p4/1b1P1B2/2N5/PPP2PPP/R2QK1NR w KQkq - 4 7");
$fen->move('Ne2');
$this->assertEquals('rn1qk1nr/pp1b1ppp/4p3/1B1p4/1b1P1B2/2N5/PPP1NPPP/R2QK2R', $fen->get_board());

}

public function testMoveToCheck() : void
Expand Down

0 comments on commit 260c0a8

Please sign in to comment.