p-chess/chess

A PHP chess library that is used for chess move generation/validation, piece placement/movement, and check/checkmate/stalemate detection

0.5.0 2023-12-28 09:29 UTC

This package is auto-updated.

Last update: 2024-11-15 18:46:47 UTC


README

Chess is a PHP chess library that is used for chess move generation/validation, piece placement/movement, and check/checkmate/stalemate detection - basically everything but the AI.

NOTE: this started as a port of chess.js for php, forked from ryanhs/chess.php

Latest Stable Version MIT License

Installation

use composer with composer require p-chess/chess or put in your composer.json

"require": {
    "p-chess/chess": "^1.0"
}

Example Code

The code below plays a complete game of chess ... randomly.

<?php

require 'vendor/autoload.php';
use \PChess\Chess\Chess;
use \PChess\Chess\Output\UnicodeOutput;

$chess = new Chess();
while (!$chess->gameOver()) {
    $moves = $chess->moves();
    $move = $moves[random_int(0, count($moves) - 1)];
    $chess->move($move);
}

echo (new UnicodeOutput())->render($chess) . PHP_EOL;
   +---+---+---+---+---+---+---+---+
 8 |   | ♜ | ♘ |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 7 | ♞ |   |   |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 6 |   |   |   |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 5 |   |   |   |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 4 |   |   |   |   |   | ♚ | ♟ |   | 
   +---+---+---+---+---+---+---+---+
 3 | ♜ |   |   |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 2 |   |   |   |   |   |   |   |   | 
   +---+---+---+---+---+---+---+---+
 1 | ♔ |   |   |   | ♞ |   |   |   | 
   +---+---+---+---+---+---+---+---+
     a   b   c   d   e   f   g   h

Supported output formats

ASCII

Pieces are displayed with corresponding codes (e.g. "p" for pawn, "q" for queen, etc.).

<?php
// use...
$chess = new Chess();
echo (new AsciiOutput())->render($chess);

Unicode

Pieces are displayed like in the example above.

<?php
// use...
$chess = new Chess();
echo (new UnicodeOutput())->render($chess);

PNG Image

Pieces are displayed inside a png image.

<?php
// use...
$chess = new Chess();
$imagine = new \Imagine\Gd\Imagine();   // or \Imagine\Imagick\Imagine()
$output = new ImageOutput($imagine, '/your/path/to/images', 480);
header('Content-Type: image/png');  
echo $output->render($chess);

See dedicated documentation for a detailed instructions.

HTML

Pieces are displayed inside an HTML table.

See dedicated documentation for a detailed instructions.

Performance

There is still a lot to do in this topic.
akondas/php-grandmaster is a good place to start experiment ;)

Chess::move()

Other documentation

All classes are documented in the docs directory.