crabchess 0.1.15

A simple Chess API
Documentation
//! Colored board formatting for the terminal.

use crate::prelude::{Board, Color as PieceColor, File, Piece, Rank, Square, Type};
use std::io::Write;
use termcolor::{Color as TermColor, ColorChoice, ColorSpec, StandardStream, WriteColor};

impl Piece {
    const fn color_unicode(self) -> char {
        match (self.piece_type, self.color) {
            (Type::King, PieceColor::White) => '',
            (Type::Queen, PieceColor::White) => '',
            (Type::Rook, PieceColor::White) => '',
            (Type::Bishop, PieceColor::White) => '',
            (Type::Knight, PieceColor::White) => '',
            (Type::Pawn, PieceColor::White) => '',
            (Type::King, PieceColor::Black) => '',
            (Type::Queen, PieceColor::Black) => '',
            (Type::Rook, PieceColor::Black) => '',
            (Type::Bishop, PieceColor::Black) => '',
            (Type::Knight, PieceColor::Black) => '',
            (Type::Pawn, PieceColor::Black) => '',
        }
    }
}

impl Board {
    /// Print colored board representation to terminal.
    ///
    /// # Errors
    ///
    /// Propagates any error raised by the `termcolor` crate while trying to print to console.
    pub fn color_print(&self) -> anyhow::Result<()> {
        let mut stdout = StandardStream::stdout(ColorChoice::Always);

        for rank in Rank::reversed() {
            stdout.set_color(ColorSpec::new().set_bg(None).set_fg(None))?;
            write!(&mut stdout, "{} ", rank.char())?;

            for file in File::all() {
                let square = Square(file, rank);
                let bg = match square.color() {
                    PieceColor::Black => Some(TermColor::Ansi256(2)),
                    PieceColor::White => Some(TermColor::Ansi256(230)),
                };
                let s = self.get(square).map_or(' ', Piece::color_unicode);
                stdout.set_color(
                    ColorSpec::new()
                        .set_bg(bg)
                        .set_fg(Some(TermColor::Ansi256(232))),
                )?;
                write!(&mut stdout, "{s} ")?;
                stdout.set_color(
                    ColorSpec::new()
                        .set_bg(None)
                        .set_fg(Some(TermColor::Ansi256(232))),
                )?;
            }

            writeln!(&mut stdout)?;
        }

        stdout.set_color(ColorSpec::new().set_bg(None).set_fg(None))?;
        writeln!(&mut stdout, "  a b c d e f g h ")?;

        Ok(())
    }
}