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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use crate::{Game, Matchup, Outcome, PerPlayer, PlayResult, Player, Score};
use itertools::Itertools;
use log::error;
use rayon::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;

/// A tournament in which several players play a game against each other in a series of matchups.
#[derive(Clone, Debug)]
pub struct Tournament<G: Game<P>, const P: usize> {
    game: Arc<G>,
    matchups: Vec<Matchup<G, P>>,
}

/// The collected results from running a tournament.
#[derive(Clone, Debug, PartialEq)]
pub struct TournamentResult<G: Game<P>, const P: usize> {
    results: HashMap<PerPlayer<String, P>, PlayResult<G, P>>,
    score: Score<G::Utility>,
    has_errors: bool,
}

impl<G: Game<P>, const P: usize> Tournament<G, P> {
    /// Construct a new tournament for the given game with the given list of matchups.
    pub fn new(game: Arc<G>, matchups: Vec<Matchup<G, P>>) -> Self {
        Tournament { game, matchups }
    }

    /// Construct a new tournament where the matchups are all
    /// [combinations](https://en.wikipedia.org/wiki/Combination)
    /// [with replacement](https://en.wikipedia.org/wiki/Sampling_(statistics)#Replacement_of_selected_units)
    /// of the given list of players.
    ///
    /// That is, all selections of players where the order does not matter and the same player may
    /// be repeated within a matchup.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    /// use t4t::*;
    ///
    /// let players = vec!["A", "B", "C"]
    ///     .into_iter()
    ///     .map(|name| Arc::new(Player::new(name.to_string(), || Strategy::pure(()))))
    ///     .collect::<Vec<_>>();
    ///
    /// let game: Simultaneous<(), u8, 3> = Simultaneous::trivial();
    ///
    /// let tournament = Tournament::combinations_with_replacement(
    ///     Arc::new(game),
    ///     &players,
    /// );
    ///
    /// assert_eq!(
    ///     tournament
    ///         .matchups()
    ///         .iter()
    ///         .map(|m| m.names())
    ///         .collect::<Vec<_>>(),
    ///     vec![
    ///         PerPlayer::new(["A", "A", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "A", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "A", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "C", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "B", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "B", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "C", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "C", "C"]).map(|s| s.to_string()),
    ///     ],
    /// )
    /// ```
    pub fn combinations_with_replacement(game: Arc<G>, players: &[Arc<Player<G, P>>]) -> Self {
        Tournament::new(
            game,
            players
                .iter()
                .cloned()
                .combinations_with_replacement(P)
                .map(|player_vec| Matchup::new(PerPlayer::new(player_vec.try_into().unwrap())))
                .collect(),
        )
    }

    /// Construct a new tournament where the matchups are all
    /// [combinations](https://en.wikipedia.org/wiki/Combination)
    /// [without replacement](https://en.wikipedia.org/wiki/Sampling_(statistics)#Replacement_of_selected_units)
    /// of the given list of players.
    ///
    /// That is, all selections of players where the order does not matter and all players are
    /// distinct within a matchup.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    /// use t4t::*;
    ///
    /// let players = vec!["A", "B", "C", "D", "E"]
    ///     .into_iter()
    ///     .map(|name| Arc::new(Player::new(name.to_string(), || Strategy::pure(()))))
    ///     .collect::<Vec<_>>();
    ///
    /// let game: Simultaneous<(), u8, 3> = Simultaneous::trivial();
    ///
    /// let tournament = Tournament::combinations_without_replacement(
    ///     Arc::new(game),
    ///     &players,
    /// );
    ///
    /// assert_eq!(
    ///     tournament
    ///         .matchups()
    ///         .iter()
    ///         .map(|m| m.names())
    ///         .collect::<Vec<_>>(),
    ///     vec![
    ///         PerPlayer::new(["A", "B", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "D"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "E"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "C", "D"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "C", "E"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "D", "E"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "C", "D"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "C", "E"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "D", "E"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "D", "E"]).map(|s| s.to_string()),
    ///     ],
    /// )
    /// ```
    pub fn combinations_without_replacement(game: Arc<G>, players: &[Arc<Player<G, P>>]) -> Self {
        Tournament::new(
            game,
            players
                .iter()
                .cloned()
                .combinations(P)
                .map(|player_vec| Matchup::new(PerPlayer::new(player_vec.try_into().unwrap())))
                .collect(),
        )
    }

    /// Construct a new tournament where the matchups are all
    /// [premutations](https://en.wikipedia.org/wiki/Permutation)
    /// [with replacement](https://en.wikipedia.org/wiki/Sampling_(statistics)#Replacement_of_selected_units)
    /// of the given list of players.
    ///
    /// That is, all orderings of all selections of players where the same player may be repeated
    /// within in a matchup.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    /// use t4t::*;
    ///
    /// let players = vec!["A", "B"]
    ///     .into_iter()
    ///     .map(|name| Arc::new(Player::new(name.to_string(), || Strategy::pure(()))))
    ///     .collect::<Vec<_>>();
    ///
    /// let game: Simultaneous<(), u8, 3> = Simultaneous::trivial();
    ///
    /// let tournament = Tournament::permutations_with_replacement(
    ///     Arc::new(game),
    ///     &players,
    /// );
    ///
    /// assert_eq!(
    ///     tournament
    ///         .matchups()
    ///         .iter()
    ///         .map(|m| m.names())
    ///         .collect::<Vec<_>>(),
    ///     vec![
    ///         PerPlayer::new(["A", "A", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "A", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "B", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "A", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "A", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "B", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "B", "B"]).map(|s| s.to_string()),
    ///     ],
    /// )
    /// ```
    pub fn permutations_with_replacement(game: Arc<G>, players: &[Arc<Player<G, P>>]) -> Self {
        Tournament::new(
            game,
            itertools::repeat_n(players.to_vec(), P)
                .multi_cartesian_product()
                .map(|player_vec| Matchup::new(PerPlayer::new(player_vec.try_into().unwrap())))
                .collect(),
        )
    }

    /// Construct a new tournament where the matchups are all
    /// [premutations](https://en.wikipedia.org/wiki/Permutation)
    /// [without replacement](https://en.wikipedia.org/wiki/Sampling_(statistics)#Replacement_of_selected_units)
    /// of the given list of players.
    ///
    /// That is, all orderings of all selections of players where players are distinct within a
    /// matchup.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    /// use t4t::*;
    ///
    /// let players = vec!["A", "B", "C"]
    ///     .into_iter()
    ///     .map(|name| Arc::new(Player::new(name.to_string(), || Strategy::pure(()))))
    ///     .collect::<Vec<_>>();
    ///
    /// let game: Simultaneous<(), u8, 2> = Simultaneous::trivial();
    ///
    /// let tournament = Tournament::permutations_without_replacement(
    ///     Arc::new(game),
    ///     &players,
    /// );
    ///
    /// assert_eq!(
    ///     tournament
    ///         .matchups()
    ///         .iter()
    ///         .map(|m| m.names())
    ///         .collect::<Vec<_>>(),
    ///     vec![
    ///         PerPlayer::new(["A", "B"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "C"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "A"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "B"]).map(|s| s.to_string()),
    ///     ],
    /// )
    /// ```
    pub fn permutations_without_replacement(game: Arc<G>, players: &[Arc<Player<G, P>>]) -> Self {
        Tournament::new(
            game,
            players
                .iter()
                .cloned()
                .permutations(P)
                .map(|player_vec| Matchup::new(PerPlayer::new(player_vec.try_into().unwrap())))
                .collect(),
        )
    }

    /// Construct a new tournament where the matchups are the cartesian product of the given
    /// per-player collection of lists of players, that is, every combination where one player is
    /// drawn from each list.
    ///
    /// This constructor is well-suited to non-symmetric games where different groups of players
    /// are specific to different roles in the game.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    /// use t4t::*;
    ///
    /// let [a, b, c, d, e, f, g] = ["A", "B", "C", "D", "E", "F", "G"]
    ///     .map(|name| Arc::new(Player::new(name.to_string(), || Strategy::pure(()))));
    ///
    /// let game: Simultaneous<(), u8, 3> = Simultaneous::trivial();
    ///
    /// let tournament = Tournament::product(
    ///     Arc::new(game),
    ///     PerPlayer::new([&vec![a, b, c], &vec![d, e], &vec![f, g]])
    /// );
    ///
    /// assert_eq!(
    ///     tournament
    ///         .matchups()
    ///         .iter()
    ///         .map(|m| m.names())
    ///         .collect::<Vec<_>>(),
    ///     vec![
    ///         PerPlayer::new(["A", "D", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "D", "G"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "E", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["A", "E", "G"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "D", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "D", "G"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "E", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["B", "E", "G"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "D", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "D", "G"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "E", "F"]).map(|s| s.to_string()),
    ///         PerPlayer::new(["C", "E", "G"]).map(|s| s.to_string()),
    ///     ],
    /// )
    /// ```
    pub fn product(game: Arc<G>, players_per_slot: PerPlayer<&[Arc<Player<G, P>>], P>) -> Self {
        Tournament::new(
            game,
            players_per_slot
                .map(|slice| slice.to_vec())
                .into_iter()
                .multi_cartesian_product()
                .map(|player_vec| Matchup::new(PerPlayer::new(player_vec.try_into().unwrap())))
                .collect(),
        )
    }

    /// Run the tournament and collect the results.
    pub fn play(&self) -> TournamentResult<G, P> {
        let mut results = HashMap::new();
        let mut score = Score::new();
        let mut has_errors = false;

        let (sender, receiver) = std::sync::mpsc::channel();

        self.matchups
            .par_iter()
            .for_each_with(sender, |s, matchup| {
                let result = self.game.play(matchup);
                let send_result = s.send((matchup.names(), result));
                if let Err(err) = send_result {
                    error!("error sending result: {:?}", err);
                }
            });

        receiver.iter().for_each(|(names, result)| {
            if let Ok(outcome) = &result {
                names.for_each_with_index(|i, name| {
                    score.add(name, outcome.payoff()[i]);
                });
            } else {
                has_errors = true;
            }
            results.insert(names, result);
        });

        TournamentResult {
            results,
            score,
            has_errors,
        }
    }

    /// Get a reference to the game being played in this tournament.
    pub fn game(&self) -> &Arc<G> {
        &self.game
    }

    /// Get all the matchups in this tournament.
    pub fn matchups(&self) -> &Vec<Matchup<G, P>> {
        &self.matchups
    }
}

impl<G: Game<P>, const P: usize> TournamentResult<G, P> {
    /// The individual play result of each matchup.
    pub fn results(&self) -> &HashMap<PerPlayer<String, P>, PlayResult<G, P>> {
        &self.results
    }

    /// The cumulative utility for each player across all matchups.
    ///
    /// Note that failed matchups will result in no added utility for either player in the matchup,
    /// so this value should not be relied on if [`has_errors`](Self::has_errors) is true.
    pub fn score(&self) -> &Score<G::Utility> {
        &self.score
    }

    /// Did any of the matchups end in an error rather than a successful outcome?
    pub fn has_errors(&self) -> bool {
        self.has_errors
    }
}