Closed ghost closed 5 months ago
Chess pieces can be looped through by using a foreach loop.
Also the space evaluation of the position may help. See Heuristics
@programarivm Could you please send me (random vs random) code?
Sorry @EarlyEdition that I gave a wrong answer. This is how to obtain the legal moves from the start position.
$board = new Board();
$legal = [];
foreach ($board->getPieces() as $piece) {
if ($sqs = $piece->sqs()) {
$legal[$piece->getSq()] = $sqs;
}
}
print_r($legal);
Array
(
[b1] => Array
(
[0] => a3
[1] => c3
)
[g1] => Array
(
[0] => f3
[1] => h3
)
[a2] => Array
(
[0] => a3
[1] => a4
)
[b2] => Array
(
[0] => b3
[1] => b4
)
[c2] => Array
(
[0] => c3
[1] => c4
)
[d2] => Array
(
[0] => d3
[1] => d4
)
[e2] => Array
(
[0] => e3
[1] => e4
)
[f2] => Array
(
[0] => f3
[1] => f4
)
[g2] => Array
(
[0] => g3
[1] => g4
)
[h2] => Array
(
[0] => h3
[1] => h4
)
[b8] => Array
(
[0] => a6
[1] => c6
)
[g8] => Array
(
[0] => f6
[1] => h6
)
[a7] => Array
(
[0] => a6
[1] => a5
)
[b7] => Array
(
[0] => b6
[1] => b5
)
[c7] => Array
(
[0] => c6
[1] => c5
)
[d7] => Array
(
[0] => d6
[1] => d5
)
[e7] => Array
(
[0] => e6
[1] => e5
)
[f7] => Array
(
[0] => f6
[1] => f5
)
[g7] => Array
(
[0] => g6
[1] => g5
)
[h7] => Array
(
[0] => h6
[1] => h5
)
)
The pieces can also be obtained by color or turn if you like as described next.
$board = new Board();
$legal = [];
foreach ($board->getPieces($board->getTurn()) as $piece) {
if ($sqs = $piece->sqs()) {
$legal[$piece->getSq()] = $sqs;
}
}
print_r($legal);
Array
(
[b1] => Array
(
[0] => a3
[1] => c3
)
[g1] => Array
(
[0] => f3
[1] => h3
)
[a2] => Array
(
[0] => a3
[1] => a4
)
[b2] => Array
(
[0] => b3
[1] => b4
)
[c2] => Array
(
[0] => c3
[1] => c4
)
[d2] => Array
(
[0] => d3
[1] => d4
)
[e2] => Array
(
[0] => e3
[1] => e4
)
[f2] => Array
(
[0] => f3
[1] => f4
)
[g2] => Array
(
[0] => g3
[1] => g4
)
[h2] => Array
(
[0] => h3
[1] => h4
)
)
Hi Jordi, I found this function to make legal moves, but it needs
string $sq
!How can I get all legal moves from a position without
$sq
?