1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use derive_more::From;
use enum_map::EnumMap;

use super::foundation::Foundation;
use super::stock::Stock;
use super::tableau::Tableau;
use super::waste::Waste;
use super::{foundation, tableau, Zone};
use crate::deal::{Deal, Dealable as _};
use crate::enums::enum_map_ext::EnumMapExt as _;
use crate::piles::{Cards, Pile as _};
use crate::shuffle::Shuffle;

pub mod draw_or_replace;
#[derive(Debug, Clone, PartialEq, Eq, From)]
pub struct Table {
    stock: Stock,
    waste: Waste,
    foundation: EnumMap<foundation::Index, Foundation>,
    tableau: EnumMap<tableau::Index, Tableau>,
}

#[derive(Debug, Clone, Copy)]
pub struct View<'a> {
    pub stock: <Stock as Zone>::View<'a>,
    pub waste: <Waste as Zone>::View<'a>,
    pub foundation: EnumMap<foundation::Index, <Foundation as Zone>::View<'a>>,
    pub tableau: EnumMap<tableau::Index, <Tableau as Zone>::View<'a>>,
}

impl Table {
    pub fn new<S, D>() -> Self
    where
        S: Default + Shuffle,
        D: Default + Deal<Index = tableau::Index>,
    {
        Self::from_shuffle_and_deal(S::default(), D::default())
    }

    pub fn from_shuffle_and_deal<S, D>(shuffle: S, deal: D) -> Self
    where
        S: Shuffle,
        D: Deal<Index = tableau::Index>,
    {
        let deck = Cards::shuffled_deck(shuffle);
        let mut tableau_piles: EnumMap<_, Cards> = EnumMap::default();

        let stock = deck.deal_out(deal, &mut tableau_piles).collect::<Stock>();
        let waste = Waste::default();

        let tableau = tableau_piles.map(|_, pile| {
            let face_down_len = pile.len().saturating_sub(1);

            pile.into_split(face_down_len).into()
        });

        let foundation = EnumMap::default();

        Self {
            stock,
            waste,
            foundation,
            tableau,
        }
    }
}

impl Zone for Table {
    type View<'a> = View<'a>
    where
        Self: 'a;

    fn as_view(&self) -> Self::View<'_> {
        View {
            stock: self.stock.as_view(),
            waste: self.waste.as_view(),
            foundation: self.foundation.map_ref(|_, zone| zone.as_view()),
            tableau: self.tableau.map_ref(|_, zone| zone.as_view()),
        }
    }
}