Skip to content

Commit

Permalink
Refactored Chess\Randomizer
Browse files Browse the repository at this point in the history
  • Loading branch information
programarivm committed May 8, 2024
1 parent dd21ccd commit bfabd88
Showing 1 changed file with 9 additions and 38 deletions.
47 changes: 9 additions & 38 deletions src/Randomizer/Randomizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Chess\Variant\Classical\PGN\AN\Color;
use Chess\Variant\Classical\Board;
use Chess\Variant\Classical\PGN\AN\Piece;
use Chess\Variant\Classical\Rule\CastlingRule;

/**
* Randomizer.
Expand All @@ -19,31 +18,13 @@
*/
class Randomizer
{
const FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

const RANKS = ['1', '2', '3', '4', '5', '6', '7', '8'];

/**
* Chess board.
*
* @var \Chess\Variant\Classical\Board
*/
protected Board $board;

/**
* Castling rule.
*
* @var array
*/
protected array $castlingRule;

/**
* The items to be added.
*
* @var array
*/
protected array $items = [];

/**
* Constructor.
*
Expand All @@ -52,21 +33,17 @@ class Randomizer
*/
public function __construct(string $turn, array $items = [])
{
$this->castlingRule = (new CastlingRule())->getRule();

$this->items = $items;

$this->board = new Board();
do {
$pieces = $this->kings();
$pieces = $this->rand($items, $pieces);
$pieces = $this->rand($items, $this->kings());
$board = new Board($pieces);
} while ($this->isAttackingKing($board));

$this->board = $board->setTurn($turn);
}

/**
* Returns the Chess\Board object.
* Returns the board.
*
* @return \Chess\Variant\Classical\Board
*/
Expand All @@ -82,16 +59,10 @@ public function getBoard(): Board
*/
protected function sq(): string
{
$files = self::FILES;
$ranks = self::RANKS;

shuffle($files);
shuffle($ranks);

$file = $files[0];
$rank = $ranks[0];
$sqs = $this->board->getSqs();
shuffle($sqs);

return $file . $rank;
return $sqs[0];
}

/**
Expand All @@ -109,7 +80,7 @@ protected function areAdjacentSqs(string $w, string $b): bool
}

/**
* Creates a Chess\Board object with two randomly placed kings.
* Creates a board with two randomly placed kings.
*
* @return array
*/
Expand All @@ -129,8 +100,8 @@ protected function kings(): array
);

$pieces = [
new K(Color::W, $wSq, $this->castlingRule),
new K(Color::B, $bSq, $this->castlingRule),
new K(Color::W, $wSq, $this->board->getCastlingRule()),
new K(Color::B, $bSq, $this->board->getCastlingRule()),
];

$this->board = new Board($pieces);
Expand Down

0 comments on commit bfabd88

Please sign in to comment.