From 0bedf2aa9f490c430e799b61d9629264e52f7ba8 Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Sat, 3 Feb 2024 15:17:40 -0800 Subject: [PATCH] Implement part of a new Builder using the type state pattern The API for this is much easier to use. --- moves/src/builder.rs | 105 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 moves/src/builder.rs diff --git a/moves/src/builder.rs b/moves/src/builder.rs new file mode 100644 index 0000000..9340497 --- /dev/null +++ b/moves/src/builder.rs @@ -0,0 +1,105 @@ +// Eryn Wells + +use crate::{castle, Move}; +use chessfriend_core::{PlacedPiece, Square}; + +pub trait Style {} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Builder { + style: S, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Null; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Push { + from: Option, + to: Option, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Capture { + push: Push, + capture: Option, +} + +pub struct Castle { + castle: castle::Castle, +} + +impl Style for Null {} +impl Style for Push {} +impl Style for Capture {} +impl Style for Castle {} + +impl Builder { + pub fn new() -> Self { + Self { style: Null } + } + + pub fn piece(piece: &PlacedPiece) -> Builder { + Builder { + style: Push { + from: Some(piece.square()), + to: None, + }, + } + } + + pub fn castling(castle: castle::Castle) -> Builder { + Builder { + style: Castle { castle }, + } + } + + pub fn build(&self) -> Move { + Move(0) + } +} + +impl Builder { + pub fn from(mut self, square: Square) -> Self { + self.style.from = Some(square); + self + } + + pub fn to(mut self, square: Square) -> Self { + self.style.to = Some(square); + self + } + + pub fn capturing(self, square: Square) -> Builder { + Builder { + style: Capture { + push: self.style, + capture: Some(square), + }, + } + } + + pub fn capturing_piece(self, piece: PlacedPiece) -> Builder { + Builder { + style: Capture { + push: self.style, + capture: Some(piece.square()), + }, + } + } +} + +impl Builder { + pub fn build(&self) -> Move { + Move(self.style.into_bits()) + } +} + +impl Castle { + fn into_bits(&self) -> u16 { + match self.castle { + castle::Castle::KingSide => 0b10, + castle::Castle::QueenSide => 0b11, + } + } +}