Skip to content

Commit

Permalink
Refactored isStalemate()
Browse files Browse the repository at this point in the history
  • Loading branch information
programarivm committed Sep 28, 2024
1 parent bf634aa commit 64967d9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
25 changes: 11 additions & 14 deletions src/Variant/Dunsany/Board.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,25 +92,22 @@ public function __construct(array $pieces = null, string $castlingAbility = '-')

public function isStalemate(): bool
{
if (Color::W === $this->turn) {
return $this->isTrapped() && !$this->isCheck() && !$this->doesWin();
}

$legal = [];
$clone = $this->clone();
$clone->turn = Color::W;
foreach ($clone->pieces(Color::W) as $piece) {
$legal = [
...$legal,
...$clone->legal($piece->sq),
];
if (!$this->doesWin()) {
$moveSqs = [];
foreach ($this->pieces($this->turn) as $piece) {
$moveSqs = [
...$moveSqs,
...$piece->moveSqs(),
];
}
return $moveSqs === [];
}

return empty($legal);
return false;
}

public function doesWin(): bool
{
return $this->isMate() xor empty($this->pieces(Color::W));
return $this->isMate() xor $this->pieces(Color::W) === [];
}
}
12 changes: 8 additions & 4 deletions tests/unit/Variant/Dunsany/BoardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public function w_wins()
/**
* @test
*/
public function b_stalemates()
public function Rh8_stalemates()
{
$board = FenToBoardFactory::create(
'r7/3k3P/8/8/8/8/8/8 b - -',
Expand Down Expand Up @@ -196,16 +196,16 @@ public function b_stalemates()
/**
* @test
*/
public function w_stalemates()
public function Kxh7_stalemates()
{
$board = FenToBoardFactory::create(
'7k/7P/8/7P/8/8/8/8 w - -',
new Board()
);

$expected = [
7 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' k ' ],
6 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' P ' ],
7 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ' ],
6 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' k ' ],
5 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' P ' ],
4 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ' ],
3 => [ ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ', ' . ' ],
Expand All @@ -218,6 +218,10 @@ public function w_stalemates()
$this->assertFalse($board->isStalemate());
$this->assertTrue($board->play('w', 'h6'));
$this->assertSame('b', $board->turn);
$this->assertFalse($board->isStalemate());
$this->assertFalse($board->isMate());
$this->assertFalse($board->doesWin());
$this->assertTrue($board->play('b', 'Kxh7'));
$this->assertTrue($board->isStalemate());
$this->assertFalse($board->isMate());
$this->assertFalse($board->doesWin());
Expand Down

0 comments on commit 64967d9

Please sign in to comment.