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
use crate::game::*;
use crate::policies::{
    MultiplayerPolicy, MultiplayerPolicyBuilder, SingleplayerPolicy, SingleplayerPolicyBuilder,
};

use async_trait::async_trait;
use futures::future::{BoxFuture, FutureExt};
use std::f32;
use std::iter::*;

/// Nested Monte Carlo Search
pub struct NMCSPolicy {
    s: NMCS,
}

impl NMCSPolicy {
    fn nested<'a, G: Singleplayer + Clone>(
        self: &'a NMCSPolicy,
        board: &'a G,
        level: usize,
    ) -> BoxFuture<'a, (f32, Vec<G::Move>)> {
        async move {
            if level == 0 {
                let (_board, mut history, total_reward) = board.playout_history(0).await;
                history.reverse();
                (total_reward, history.into_iter().map(|(_, b)| b).collect())
            } else {
                let mut best_score = 0.0;
                let mut best_sequence = Vec::new();
                let mut state = board.clone();
                let mut played_sequence = Vec::new();

                while !state.is_finished() {
                    for m in state.possible_moves() {
                        let mut new_board = state.clone();
                        new_board.play(&m).await;
                        let (score, history) = self.nested(&new_board, level - 1).await;
                        if score >= best_score {
                            best_sequence = history;
                            best_sequence.push(m);
                            best_score = score;
                        }
                    }
                    let next_action = best_sequence.pop().unwrap();
                    state.play(&next_action).await;
                    played_sequence.push(next_action);
                }
                played_sequence.reverse();
                (best_score, played_sequence)
            }
        }
        .boxed()
    }
}

#[async_trait]
impl<G: Singleplayer + Clone> SingleplayerPolicy<G> for NMCSPolicy {
    async fn solve(self: &mut NMCSPolicy, board: &G) -> Vec<G::Move> {
        let (_, mut sequence) = self.nested(board, self.s.level).await;
        sequence.reverse();
        sequence
    }
}

/// Nested Monte Carlo Search policy builder.
#[derive(Copy, Clone)]
pub struct NMCS {
    level: usize,
}

impl Default for NMCS {
    fn default() -> NMCS {
        NMCS { level: 2 }
    }
}

impl<G: Singleplayer + Clone> SingleplayerPolicyBuilder<G> for NMCS {
    type P = NMCSPolicy;

    fn create(&self) -> Self::P {
        NMCSPolicy { s: *self }
    }
}

/// Multiplayer NMCS
pub struct MultiNMCSPolicy<G: Game> {
    color: G::Player,
    s: MultiNMCS,
}

impl<G: Game + SingleWinner + Clone> MultiNMCSPolicy<G> {
    fn nested<'a>(
        self: &'a MultiNMCSPolicy<G>,
        board: &'a G,
        level: usize,
        depth: f32,
        bound: f32,
    ) -> BoxFuture<'a, f32> {
        async move {
            let mut d = depth;
            let mut s = board.clone();

            while !s.is_finished() {
                let mut s_star = s.clone();
                s_star.random_move().await;
                let mut l_star = if s.turn() == self.color {
                    -1. / d
                } else {
                    1. / d
                };

                if self.s.d_pruning
                    && ((s.turn() == self.color && -l_star < bound)
                        || (s.turn() != self.color && -l_star > bound))
                {
                    return bound;
                }

                if depth > 0. {
                    for m in s.possible_moves() {
                        let mut new_s = s.clone();
                        new_s.play(&m).await;
                        let l = self.nested(&new_s, level - 1, d + 1., l_star).await;
                        if (s.turn() == self.color && l > l_star)
                            || (s.turn() != self.color && l < l_star)
                        {
                            l_star = l;
                            s_star = new_s;
                        }
                        if self.s.cut_on_win && (l != 0.) {
                            break;
                        }
                    }
                }

                s = s_star;
                d += 1.;
            }

            let score = if board.winner() == Some(self.color) {
                1.
            } else if !board.is_finished() {
                0.0
            } else {
                -1.0
            };

            if self.s.discounting {
                score / d
            } else {
                score
            }
        }
        .boxed()
    }
}

#[async_trait]
impl<G: Game + SingleWinner + Clone> MultiplayerPolicy<G> for MultiNMCSPolicy<G> {
    async fn play(self: &mut MultiNMCSPolicy<G>, board: &G) -> G::Move {
        let mut best_move = None;
        let mut max_visited = 0.;

        for m in board.possible_moves() {
            let mut new_board = board.clone();
            new_board.play(&m).await;
            let value = self
                .nested(&new_board, self.s.level, 0., self.s.bound)
                .await;

            if value >= max_visited {
                max_visited = value;
                best_move = Some(m);
            }
        }
        best_move.unwrap()
    }
}

/// Multiplayer NMCS policy builder.
#[derive(Copy, Clone)]
pub struct MultiNMCS {
    discounting: bool,
    d_pruning: bool,
    cut_on_win: bool,
    level: usize,
    bound: f32,
}

impl Default for MultiNMCS {
    fn default() -> MultiNMCS {
        MultiNMCS {
            discounting: true,
            d_pruning: true,
            cut_on_win: true,
            level: 3,
            bound: 1.0,
        }
    }
}

use std::fmt;
impl fmt::Display for MultiNMCS {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "MultiNMCS")?;
        writeln!(f, "|| Discounting: {}", self.discounting)?;
        writeln!(f, "|| D_pruning: {}", self.d_pruning)?;
        writeln!(f, "|| Cut_on_win: {}", self.cut_on_win)?;
        writeln!(f, "|| LEVEL: {}", self.level)?;
        writeln!(f, "|| BOUND: {}", self.bound)
    }
}

impl<G: Game + SingleWinner + Clone> MultiplayerPolicyBuilder<G> for MultiNMCS {
    type P = MultiNMCSPolicy<G>;

    fn create(&self, color: G::Player) -> Self::P {
        MultiNMCSPolicy { color, s: *self }
    }
}