chessfriend/board/src/position/diagram_formatter.rs
Eryn Wells 0d8653894a An attempt at making unit structs for Color and piece Shape
My idea was to implement traits on Piece that return sight lines, etc. This has
turned out to be much more complex than I thought it would be. Ultimately, I
don't think it's worth the effort.
2024-01-14 10:23:35 -08:00

73 lines
1.9 KiB
Rust

// Eryn Wells <eryn@erynwells.me>
use crate::{File, Position, Rank, Square};
use std::{fmt, fmt::Write};
pub struct DiagramFormatter<'a, PosC>(&'a Position<PosC>);
impl<'a, PosC> DiagramFormatter<'a, PosC> {
pub fn new(position: &'a Position<PosC>) -> DiagramFormatter<PosC> {
DiagramFormatter(position)
}
}
impl<'a, PosC> fmt::Display for DiagramFormatter<'a, PosC> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut output = String::new();
output.push_str(" +-----------------+\n");
for rank in Rank::ALL.iter().rev() {
write!(output, "{} | ", rank)?;
for file in File::ALL.iter() {
let square = Square::from_file_rank(*file, *rank);
match self.0.piece_on_square(square) {
Some(placed_piece) => write!(output, "{} ", placed_piece.piece())?,
None => output.push_str(". "),
}
}
output.push_str("|\n");
}
output.push_str(" +-----------------+\n");
output.push_str(" a b c d e f g h\n");
write!(f, "{}", output)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::piece::{Color, Piece};
use crate::Position;
#[test]
fn empty() {
let pos = Position::empty();
let diagram = DiagramFormatter(&pos);
println!("{}", diagram);
}
#[test]
fn one_king() {
let mut pos = Position::empty();
pos.place_piece(
Piece::king(Color::Black),
Square::from_algebraic_str("h3").expect("h3"),
)
.expect("Unable to place piece");
let diagram = DiagramFormatter(&pos);
println!("{}", diagram);
}
#[test]
fn starting() {
let pos = Position::starting();
let diagram = DiagramFormatter(&pos);
println!("{}", diagram);
}
}