Skip to content

Commit

Permalink
Refactored isKingLeftInCheck() (#726)
Browse files Browse the repository at this point in the history
  • Loading branch information
programarivm authored Jan 27, 2025
1 parent fd95a1f commit 8f61020
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 22 deletions.
35 changes: 13 additions & 22 deletions src/Variant/AbstractPiece.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,32 +315,23 @@ public function isPinned(): ?AbstractPiece
*/
public function isKingLeftInCheck(): bool
{
$isCheck = false;
$turn = $this->board->turn;
$history = $this->board->history;
$castlingAbility = $this->board->castlingAbility;
$sqCount = $this->board->sqCount;
$spaceEval = $this->board->spaceEval;
$pieces = $this->board->pieces();
if ($this->move()) {
$isCheck = $this->board->piece($this->color, Piece::K)?->attacking() != [];
$this->board->turn = $turn;
$this->board->history = $history;
$this->board->castlingAbility = $castlingAbility;
$this->board->sqCount = $sqCount;
$this->board->spaceEval = $spaceEval;
$this->board->rewind();
while ($this->board->valid()) {
$piece = $this->board->current();
$this->board->next();
$this->board->detach($piece);
if ($king = $this->board->piece($this->color, Piece::K)) {
foreach ($king->attacking() as $attacking) {
if ($this->move['to'] !== $attacking->sq &&
!in_array($this->move['to'], $attacking->line($king->sq))
) {
return true;
}
}
foreach ($pieces as $val) {
$this->board->attach($val);
}
if ($pinning = $this->isPinned()) {
if ($this->move['to'] !== $pinning->sq &&
!in_array($this->move['to'], $pinning->line($king->sq))) {
return true;
}
}

return $isCheck;
return false;
}

/**
Expand Down
10 changes: 10 additions & 0 deletions src/Variant/Classical/K.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,14 @@ public function castle(string $rookType): bool

return false;
}

/**
* Returns true if the king is left in check because of moving the piece.
*
* @return bool
*/
public function isKingLeftInCheck(): bool
{
return in_array($this->move['to'], $this->board->spaceEval[$this->oppColor()]);
}
}

0 comments on commit 8f61020

Please sign in to comment.