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
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use crate::game::*;
use async_trait::async_trait;
use std::sync::Arc;

/// A game with its history.
#[derive(Clone, Debug)]
pub struct WithHistory<G: Base> {
    prec: Option<Arc<Self>>,
    /// Current game state.
    pub state: G, // TODO: create accessor
    history_len: usize,
}

impl<G: Base + Clone> Base for WithHistory<G> {
    type Move = G::Move;

    fn possible_moves(&self) -> Vec<Self::Move> {
        self.state.possible_moves()
    }
}

#[async_trait]
impl<G: Playable + Clone + Sync + Send> Playable for WithHistory<G> {
    async fn play(&mut self, action: &<Self as Base>::Move) -> f32 {
        let prec = self.prec.take();
        let new_node = WithHistory {
            prec,
            state: self.state.clone(),
            history_len: self.history_len,
        };
        self.prec = Some(Arc::new(new_node));
        self.state.play(action).await
    }
}

impl<G: Game + Clone + Sync + Send> Game for WithHistory<G> {
    type Player = G::Player;

    fn players() -> Vec<Self::Player> {
        G::players()
    }

    fn player_after(player: Self::Player) -> Self::Player {
        G::player_after(player)
    }

    fn turn(&self) -> Self::Player {
        self.state.turn()
    }
}

impl<G: SingleWinner + Clone + Sync + Send> SingleWinner for WithHistory<G> {
    fn winner(&self) -> Option<G::Player> {
        self.state.winner()
    }
}

impl<G: Base + PartialEq> PartialEq for WithHistory<G> {
    fn eq(&self, other: &Self) -> bool {
        self.state.eq(&other.state)
    }
}
impl<G: Base + Eq> Eq for WithHistory<G> {}

impl<G: Base + Hash> Hash for WithHistory<G> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.state.hash(state)
    }
}
/* GAME BUILDER */
/// Builder for a game with history.
#[derive(Clone, Copy)]
pub struct WithHistoryGB<GB>(GB, usize);

impl<GB> WithHistoryGB<GB> {
    /// Creates a game builder with history, given a correspond standard game builder.
    pub fn new(gb: GB, history_len: usize) -> Self {
        Self(gb, history_len)
    }
}

#[async_trait]
impl<GB> GameBuilder for WithHistoryGB<GB>
where
    GB::G: Clone + Sync + Send + 'static,
    GB: GameBuilder + Send + Sync,
{
    type G = WithHistory<GB::G>;

    async fn create(&self, starting: <Self::G as Game>::Player) -> WithHistory<GB::G> {
        let state = self.0.create(starting).await;
        WithHistory {
            prec: None,
            state,
            history_len: self.1,
        }
    }
}

impl<G: Features + Clone + Sync + Send> Features for WithHistory<G> {
    // one dimension larger to store history
    type StateDim = <G::StateDim as Dimension>::Larger;
    type ActionDim = G::ActionDim;

    type Descriptor = (<G::StateDim as Dimension>::Larger, G::Descriptor);

    fn get_features(&self) -> Self::Descriptor {
        let ft = self.state.get_features();

        let state_dimension = {
            let game_state_dimension = G::state_dimension(&ft);
            let mut new_dim = game_state_dimension.insert_axis(Axis(0));
            new_dim[0] = self.history_len;
            new_dim
        };

        (state_dimension, ft)
    }

    fn state_dimension(descr: &Self::Descriptor) -> Self::StateDim {
        descr.0.clone()
    }

    fn action_dimension(descr: &Self::Descriptor) -> Self::ActionDim {
        G::action_dimension(&descr.1)
    }

    fn state_to_feature(&self, pov: Self::Player) -> Array<f32, Self::StateDim> {
        let mut states_ref = vec![];
        (0..self.history_len).fold(self, |current, _| {
            states_ref.push(&current.state);
            let res: &Self = current.prec.as_ref().map(|b| b.as_ref()).unwrap_or(current);
            res
        });
        let features_array: Vec<ndarray::Array<f32, Self::StateDim>> = states_ref
            .iter()
            .rev()
            .map(|g| g.state_to_feature(pov).insert_axis(Axis(0)))
            .collect();
        let features_array_view: Vec<ndarray::ArrayView<f32, Self::StateDim>> =
            features_array.iter().map(|x| x.view()).collect();
        ndarray::stack(Axis(0), &features_array_view)
            .expect("All features should have the same shape.")
    }

    fn moves_to_feature(
        descr: &Self::Descriptor,
        moves: &HashMap<Self::Move, f32>,
    ) -> Array<f32, Self::ActionDim> {
        G::moves_to_feature(&descr.1, moves)
    }

    fn feature_to_moves(&self, features: &Array<f32, Self::ActionDim>) -> HashMap<Self::Move, f32> {
        self.state.feature_to_moves(features)
    }

    fn all_feature_to_moves(
        descr: &Self::Descriptor,
        features: &Array<f32, Self::ActionDim>,
    ) -> HashMap<Self::Move, f32> {
        G::all_feature_to_moves(&descr.1, features)
    }

    fn all_possible_moves(descr: &Self::Descriptor) -> Vec<Self::Move> {
        G::all_possible_moves(&descr.1)
    }
}

/// Interface wrapper for WithHistory.
pub struct IWithHistory<GV>
where
    GV: GameView,
{
    view: GV,
}

use cursive::direction::Direction;
use cursive::event::{Event, EventResult};
use cursive::Printer;
use cursive::Vec2;

impl<GV> IWithHistory<GV>
where
    GV: GameView,
{
    /// Wraps a game view for a with history game.
    pub fn new(view: GV) -> Self {
        Self { view }
    }
}

impl<GV> cursive::view::View for IWithHistory<GV>
where
    GV: GameView,
{
    fn draw(&self, printer: &Printer) {
        self.view.draw(printer)
    }

    fn take_focus(&mut self, d: Direction) -> bool {
        self.view.take_focus(d)
    }

    fn on_event(&mut self, event: Event) -> EventResult {
        self.view.on_event(event)
    }

    fn required_size(&mut self, v: Vec2) -> Vec2 {
        self.view.required_size(v)
    }
}

impl<GV> GameView for IWithHistory<GV>
where
    GV: GameView,
    GV::G: Game + Clone,
{
    type G = WithHistory<GV::G>;

    fn set_state(&mut self, state: Self::G) {
        self.view.set_state(state.state)
    }
}