From dbe316d8b337eadff5518585dfc163f2724d0810 Mon Sep 17 00:00:00 2001 From: Kjetil Orbekk Date: Fri, 30 Dec 2022 10:27:10 -0500 Subject: Utility method to reconstruct Deal from tricks played --- protocol/src/bridge_engine.rs | 45 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) (limited to 'protocol/src/bridge_engine.rs') diff --git a/protocol/src/bridge_engine.rs b/protocol/src/bridge_engine.rs index 708d9ae..75a51ba 100644 --- a/protocol/src/bridge_engine.rs +++ b/protocol/src/bridge_engine.rs @@ -10,7 +10,7 @@ use rand::{ }; use regex::Regex; use serde::{Deserialize, Serialize}; -use std::cmp::Ordering; +use std::{cmp::Ordering, borrow::Cow}; use std::fmt; use std::str::FromStr; use strum::{EnumCount, IntoEnumIterator}; @@ -682,6 +682,7 @@ impl PlayState { MoveResult::Next(tricks) => { MoveResult::Next(PlayResult::Played(PlayedResult { bidding: self.bidding, + contract: self.contract, tricks, })) } @@ -695,18 +696,51 @@ pub struct PassedOutResult { pub bidding: Bidding, } +impl PassedOutResult { + pub fn deal(&self) -> Cow { + Cow::Borrowed(&self.deal) + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct PlayedResult { pub bidding: Bidding, + pub contract: Contract, pub tricks: Vec, } +impl PlayedResult { + pub fn deal(&self) -> Cow { + let mut deal = Deal::empty(); + let mut leader = self.contract.leader(); + let trump_suit = self.contract.highest_bid.suit; + for trick in &self.tricks { + let mut player = leader; + for card in &trick.cards_played { + player.get_cards_mut(&mut deal).push(*card); + player = player.next(); + } + leader = trick.winner(trump_suit); + } + Cow::Owned(deal) + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum PlayResult { PassedOut(PassedOutResult), Played(PlayedResult), } +impl PlayResult { + pub fn deal(&self) -> Cow { + match self { + PlayResult::PassedOut(r) => r.deal(), + PlayResult::Played(r) => r.deal(), + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum GameState { Bidding(BiddingState), @@ -824,6 +858,15 @@ pub struct Deal { } impl Deal { + pub fn empty() -> Self { + Self { + north: Vec::with_capacity(13), + west: Vec::with_capacity(13), + south: Vec::with_capacity(13), + east: Vec::with_capacity(13), + } + } + pub fn sort(&mut self, suits: &[Suit; 4], ord: RankOrder) { sort_cards(suits, ord, self.north.as_mut_slice()); sort_cards(suits, ord, self.west.as_mut_slice()); -- cgit v1.2.3