PHP code example of cmuset / chess-tools

1. Go to this page and download the library: Download cmuset/chess-tools library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cmuset / chess-tools example snippets


use Cmuset\ChessTools\Model\Game;

// Parse a PGN string
$game = Game::fromPGN($pgn);

echo $game->getTag('White');     // 'Kasparov, Garry'
echo $game->getResult()->value;  // '1-0'

// Iterate moves
foreach ($game->getMainLine() as $key => $node) {
    echo $key . ' ' . $node->getMove()->getSAN(); // '1. e4', '1... e5', ...

    foreach ($node->getVariations() as $variation) {
        // Alternative lines branching from this move
    }
}

// Apply moves to a position
use Cmuset\ChessTools\Model\Position;
use Cmuset\ChessTools\Tool\Parser\PGNParser;

$pos = Position::fromFEN(PGNParser::INITIAL_FEN);
$pos->applyMove('e4');
$pos->applyMove('e5');
echo $pos->getFEN(); // 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

// Export
echo $game->getPGN();      // Full PGN with tags, comments, variations
echo $game->getLitePGN();  // Moves only

use Cmuset\ChessTools\Tool\Parser\PGNParser;

$parser = PGNParser::create();
$game   = $parser->parse($pgn);         // Game | Game[]

$game->getPGN();        // full PGN
$game->getLitePGN();    // moves only
$game->getVerbosePgn(); // with resolved source squares and check/mate markers
$position->getFEN();
$move->getSAN();

use Cmuset\ChessTools\Tool\MoveApplier\Exception\MoveApplyingException;

try {
    $pos->applyMove('Nf3');
} catch (MoveApplyingException $e) {
    echo $e->getMoveViolation()->value; // e.g. 'No piece found for the move'
}

$pos->getLegalMoves(); // Move[] — all legal moves for the side to move

use Cmuset\ChessTools\Tool\Validator\PositionValidator;
use Cmuset\ChessTools\Tool\Validator\GameValidator;

$violations = (new PositionValidator())->validate($pos);   // PositionViolationEnum[]
$violation  = (new GameValidator())->validate($game);      // ?GameViolation

use Cmuset\ChessTools\Tool\Resolver\GameResolver;

GameResolver::create()->resolve($game);
// All moves now carry squareFrom, isCapture, isCheck, isCheckmate

$variations = $game->split(); // Variation[] — first is always the main line

$game->merge($variationA, $variationB);