💾 Archived View for code.lanterne.chilliet.eu › src › Chess › Board.php captured on 2023-09-28 at 15:32:47.

View Raw

More Information

⬅️ Previous capture (2021-12-17)

-=-=-=-=-=-=-

<?php

declare(strict_types=1);

namespace MCMic\Gemini\Chess;

use MCMic\Gemini;

class Board extends Gemini\UnicodeBoard
{
    /**
     * @var array<string,string>
     */
    protected static $fen2Pieces =
    [
        'K' => '♔',
        'Q' => '♕',
        'R' => '♖',
        'B' => '♗',
        'N' => '♘',
        'P' => '♙',
        'k' => '♚',
        'q' => '♛',
        'r' => '♜',
        'b' => '♝',
        'n' => '♞',
        'p' => '♟',
    ];

    protected bool $whiteToPlay;
    protected string $castling;
    protected string $enpassant;
    protected int $halfmoves;
    protected int $moves;

    public function __construct(string $fen)
    {
        parent::__construct(8, 8);
        [$pos, $active, $this->castling, $this->enpassant, $halfmoves, $moves] = explode(' ', $fen, 6);
        $this->halfmoves = (int)$halfmoves;
        $this->moves = (int)$moves;
        $this->whiteToPlay = ($active === 'w');
        $l = 0;
        $c = 0;
        foreach (str_split($pos) as $p) {
            if ($p === '/') {
                $l++;
                $c = 0;
            } elseif (is_numeric($p)) {
                for ($i = 0; $i < $p; $i++) {
                    $this->setSquare($l, $c, ' ', (($c == $l) || ($c == 8 - $l)));
                    $c++;
                }
            } else {
                $this->setSquare($l, $c, static::$fen2Pieces[$p], (($c == $l) || ($c == 8 - $l)));
                $c++;
            }
        }
    }

    public function getLeftContent(int $l, int $pos): string
    {
        if ($pos === 1) {
            return (8 - $l) . ' ';
        }
        return '  ';
    }

    public function getRightContent(int $l, int $pos): string
    {
        if ($pos === 1) {
            return ' ' . (8 - $l) . "\r\n";
        }
        return "\r\n";
    }

    public function render(): string
    {
        $output = '    A   B   C   D   E   F   G   H' . "\r\n";
        $output .= parent::render();
        $output .= '    A   B   C   D   E   F   G   H' . "\r\n";
        return $output;
    }

    public function renderInformation(bool $details = true): string
    {
        $output = '* ' . ($this->whiteToPlay ? static::$fen2Pieces['N'] . ' White' : static::$fen2Pieces['n'] . ' Black') . ' to play' . "\r\n";
        if ($details) {
            $output .= '* Move ' . $this->moves . "\r\n";
            $output .= '* Halfmoves clock: ' . $this->halfmoves . "\r\n";
            $output .= '* En passant: ' . $this->enpassant . "\r\n";
        }
        $output .= '* Castling: ' . $this->castling . "\r\n";
        $output .= "\r\n";
        return $output;
    }
}