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
use crate::game::{Game, Playout, SingleWinner, Singleplayer};
use crate::policies::{
    MultiplayerPolicy, MultiplayerPolicyBuilder, SingleplayerPolicy, SingleplayerPolicyBuilder,
};
use crate::settings;

use async_trait::async_trait;
use rand::seq::SliceRandom;
use std::collections::HashMap;

/// Random policy
///
/// Takes a random move at each step.
pub struct RandomPolicy {}

#[async_trait]
impl<G: Game> MultiplayerPolicy<G> for RandomPolicy {
    async fn play(self: &mut RandomPolicy, board: &G) -> G::Move {
        let moves = board.possible_moves();
        moves.choose(&mut rand::thread_rng()).copied().unwrap()
    }
}

#[async_trait]
impl<G: Singleplayer + Clone> SingleplayerPolicy<G> for RandomPolicy {
    async fn solve(self: &mut RandomPolicy, board: &G) -> Vec<G::Move> {
        let b = board.clone();
        let (_, h, _) = b.playout_history(0).await;
        h.iter().map(|(_, b)| *b).collect()
    }
}

/// Random policy builder.
#[derive(Default)]
pub struct Random {}

use std::fmt;
impl fmt::Display for Random {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Random")
    }
}

impl<G: Game> MultiplayerPolicyBuilder<G> for Random {
    type P = RandomPolicy;

    fn create(&self, _: G::Player) -> Self::P {
        RandomPolicy {}
    }
}

impl<G: Singleplayer + Clone> SingleplayerPolicyBuilder<G> for Random {
    type P = RandomPolicy;

    fn create(&self) -> Self::P {
        RandomPolicy {}
    }
}

/// Flat Monte Carlo policy
pub struct FlatMonteCarloPolicy<G: Game> {
    color: G::Player,
    playouts: usize,
}

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

        let n_playouts_per_move = self.playouts / moves.len();

        let mut best_move = None;
        let mut best_score = 0;

        for m in moves.into_iter() {
            let mut b_after_move = board.clone();
            b_after_move.play(&m).await;
            let mut success = 0;
            for _ in 0..n_playouts_per_move {
                if b_after_move.playout_board(self.color).await.0.winner() == Some(self.color) {
                    success += 1;
                }
            }

            if success >= best_score {
                best_score = success;
                best_move = Some(m);
            }
        }

        best_move.unwrap()
    }
}

/// Flat Monte Carlo policy builder
type FlatMonteCarlo = settings::FlatMonteCarlo;

impl fmt::Display for FlatMonteCarlo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "FlatMonteCarlo")
    }
}

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

    fn create(&self, color: G::Player) -> Self::P {
        FlatMonteCarloPolicy {
            color,
            playouts: self.playouts,
        }
    }
}

/// Flat Monte Carlo with UCB policy
pub struct FlatUCBMonteCarloPolicy<G: Game> {
    color: G::Player,
    playouts: usize,
    ucb_weight: f32,
}

#[async_trait]
impl<G: Game + SingleWinner + Clone> MultiplayerPolicy<G> for FlatUCBMonteCarloPolicy<G> {
    async fn play(self: &mut FlatUCBMonteCarloPolicy<G>, board: &G) -> G::Move {
        let moves = board.possible_moves();
        let n_moves = moves.len();

        let mut move_success: HashMap<&G::Move, i32> = HashMap::new();
        let mut move_count: HashMap<&G::Move, i32> = HashMap::new();
        let mut move_board: HashMap<&G::Move, G> = HashMap::new();

        for m in moves.iter() {
            let mut b_after_move = board.clone();
            b_after_move.play(&m).await;
            if b_after_move.playout_board(self.color).await.0.winner() == Some(self.color) {
                move_success.insert(m, 1);
            } else {
                move_success.insert(m, 0);
            }
            move_count.insert(m, 1);
            move_board.insert(m, b_after_move);
        }

        for i in 0..(self.playouts - n_moves) {
            let mut max_ucb = 0f32;
            let mut max_move = None;

            for m in moves.iter() {
                let count = *move_count.get(&m).unwrap() as f32;
                let succ = *move_success.get(&m).unwrap() as f32;
                let mean = succ / count;
                let ucb = mean + self.ucb_weight * (((n_moves + i) as f32).ln() / count).sqrt();

                if ucb >= max_ucb {
                    max_move = Some(m);
                    max_ucb = ucb;
                }
            }

            if let Some(max_move) = max_move {
                *move_count.get_mut(&max_move).unwrap() += 1;
                if move_board
                    .get(&max_move)
                    .unwrap()
                    .playout_board(self.color)
                    .await
                    .0
                    .winner()
                    == Some(self.color)
                {
                    *move_success.get_mut(&max_move).unwrap() += 1;
                }
            }
        }

        let mut max_count = 0;
        let mut max_move = None;

        for m in moves.iter() {
            let count = *move_count.get(&m).unwrap();

            if count >= max_count {
                max_move = Some(m);
                max_count = count;
            }
        }
        max_move.copied().unwrap()
    }
}

/// Flat Monte Carlo with UCB policy builder

type FlatUCBMonteCarlo = settings::FlatUCBMonteCarlo;

impl fmt::Display for FlatUCBMonteCarlo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "FlatUCBMonteCarlo")
    }
}

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

    fn create(&self, color: G::Player) -> Self::P {
        FlatUCBMonteCarloPolicy {
            color,
            playouts: self.playouts,
            ucb_weight: self.ucb_weight,
        }
    }
}