gfcore 0.0.6

Go Fish card game engine
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Structural audit of [`GameRecord`] and [`GameCollection`].

use serde::{Deserialize, Serialize};

use super::record::{GameCollection, GameRecord};

/// The result of a structural audit of a single [`GameRecord`].
///
/// Produced by [`GameRecord::audit`] and collected by [`GameCollection::audit_all`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditResult {
    /// The game ID from the audited record.
    pub game_id: String,
    /// `true` iff no violations were found.
    pub is_consistent: bool,
    /// Book counts per player as of the last recorded turn (empty if no turns).
    pub final_books: Vec<usize>,
    /// Human-readable violation descriptions. Empty when `is_consistent`.
    pub violations: Vec<String>,
}

impl GameRecord {
    /// Validates structural invariants of this record.
    ///
    /// Infallible — violations accumulate in [`AuditResult::violations`]
    /// rather than returning an error.
    ///
    /// # Examples
    ///
    /// ```
    /// use gfcore::history::GameRecord;
    ///
    /// let record = GameRecord::new("Standard", vec!["Alice".to_string(), "Bob".to_string()]);
    /// let result = record.audit();
    /// assert!(result.is_consistent);
    /// assert!(result.violations.is_empty());
    /// ```
    #[must_use]
    pub fn audit(&self) -> AuditResult {
        let mut violations: Vec<String> = Vec::new();
        let player_count = self.players.len();

        // Check 1: at least 2 players.
        if player_count < 2 {
            violations.push(format!(
                "player count is {player_count}; must be at least 2"
            ));
        }

        for (i, turn) in self.turns.iter().enumerate() {
            // Check 2: turn player index in range.
            if turn.player >= player_count {
                violations.push(format!(
                    "turn {i}: player index {} out of range (players: {player_count})",
                    turn.player
                ));
            }

            // Check 3: books_after_turn length matches player count.
            if turn.books_after_turn.len() != player_count {
                violations.push(format!(
                    "turn {i}: books_after_turn length {} != player count {player_count}",
                    turn.books_after_turn.len()
                ));
            }

            // Check 4: events must not be empty.
            if turn.events.is_empty() {
                violations.push(format!("turn {i}: events list is empty"));
            }
        }

        // Check 5: book counts non-decreasing per player.
        for (i, turn) in self.turns.iter().enumerate().skip(1) {
            let prev = &self.turns[i - 1].books_after_turn;
            let curr = &turn.books_after_turn;
            if prev.len() == player_count && curr.len() == player_count {
                for p in 0..player_count {
                    if curr[p] < prev[p] {
                        violations.push(format!(
                            "player {p} book count decreased from {} to {} at turn {i}",
                            prev[p], curr[p]
                        ));
                    }
                }
            }
        }

        // Check 6: total books <= 13 (Standard52 deck maximum).
        if let Some(last) = self.turns.last() {
            let total: usize = last.books_after_turn.iter().sum();
            if total > 13 {
                violations.push(format!(
                    "total books {total} exceeds maximum of 13 (Standard52 deck yields at most 13 books)"
                ));
            }
        }

        // Check 7: winner consistent with final book counts.
        if let Some(last) = self.turns.last() {
            let books = &last.books_after_turn;
            if books.len() == player_count && player_count >= 2 {
                let max_books = *books.iter().max().unwrap_or(&0);
                let leaders: Vec<usize> = (0..player_count)
                    .filter(|&p| books[p] == max_books)
                    .collect();
                let unique_leader = leaders.len() == 1;

                match self.winner {
                    Some(w) => {
                        if w >= player_count {
                            violations.push(format!(
                                "winner index {w} is out of range (players: {player_count})"
                            ));
                        } else if !unique_leader {
                            violations.push(format!(
                                "winner declared as player {w} but final books are tied (books: {books:?})"
                            ));
                        } else if leaders[0] != w {
                            violations.push(format!(
                                "winner declared as player {w} but player {} has more books (books: {books:?})",
                                leaders[0]
                            ));
                        }
                    }
                    None => {
                        if unique_leader && max_books > 0 {
                            violations.push(format!(
                                "winner is None but player {} has unique max book count of \
                                 {max_books} (books: {books:?})",
                                leaders[0]
                            ));
                        }
                    }
                }
            }
        }

        let final_books = self
            .turns
            .last()
            .map(|t| t.books_after_turn.clone())
            .unwrap_or_default();

        AuditResult {
            game_id: self.id.clone(),
            is_consistent: violations.is_empty(),
            final_books,
            violations,
        }
    }
}

impl GameCollection {
    /// Audits every game in this collection and returns one [`AuditResult`] per game.
    ///
    /// # Examples
    ///
    /// ```
    /// use gfcore::history::{GameCollection, GameRecord};
    ///
    /// let mut col = GameCollection::new();
    /// col.push(GameRecord::new("Standard", vec!["Alice".to_string(), "Bob".to_string()]));
    /// let results = col.audit_all();
    /// assert_eq!(results.len(), 1);
    /// assert!(results[0].is_consistent);
    /// ```
    pub fn audit_all(&self) -> Vec<AuditResult> {
        self.games.iter().map(GameRecord::audit).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::game::GameEvent;
    use crate::history::record::{GameCollection, TurnRecord};

    fn make_clean_record(player_count: usize, turn_count: usize) -> GameRecord {
        let players: Vec<String> = (0..player_count).map(|i| format!("P{i}")).collect();
        let mut r = GameRecord::new("Standard", players);
        for t in 0..turn_count {
            r.turns.push(TurnRecord {
                player: t % player_count,
                events: vec![GameEvent::Drew {
                    player: t % player_count,
                    matched: false,
                }],
                books_after_turn: vec![0; player_count],
                actions: None,
            });
        }
        r
    }

    #[test]
    fn test_audit_clean_record_is_consistent() {
        let record = make_clean_record(2, 3);
        let result = record.audit();
        assert!(result.is_consistent);
        assert!(result.violations.is_empty());
    }

    #[test]
    fn test_audit_empty_record_no_turns_is_consistent() {
        let record = GameRecord::new("Standard", vec!["Alice".to_string(), "Bob".to_string()]);
        let result = record.audit();
        assert!(result.is_consistent);
        assert!(result.violations.is_empty());
        assert!(result.final_books.is_empty());
    }

    #[test]
    fn test_audit_single_player_is_violation() {
        let record = GameRecord::new("Standard", vec!["Solo".to_string()]);
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("player")));
    }

    #[test]
    fn test_audit_turn_player_out_of_range() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 5,
            events: vec![GameEvent::Drew {
                player: 5,
                matched: false,
            }],
            books_after_turn: vec![0, 0],
            actions: None,
        });
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("turn 0")));
    }

    #[test]
    fn test_audit_books_after_turn_wrong_length() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![0], // should be length 2
            actions: None,
        });
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("turn 0")));
    }

    #[test]
    fn test_audit_empty_events_in_turn() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![],
            books_after_turn: vec![0, 0],
            actions: None,
        });
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("turn 0")));
    }

    #[test]
    fn test_audit_book_counts_decreasing_is_violation() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![2, 0],
            actions: None,
        });
        record.turns.push(TurnRecord {
            player: 1,
            events: vec![GameEvent::Drew {
                player: 1,
                matched: false,
            }],
            books_after_turn: vec![1, 0], // player 0 decreased
            actions: None,
        });
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("decreas")));
    }

    #[test]
    fn test_audit_total_books_exceeds_13() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![10, 5], // 15 > 13
            actions: None,
        });
        let result = record.audit();
        assert!(!result.is_consistent);
        // The violation message includes the actual total (15).
        assert!(result.violations.iter().any(|v| v.contains("15")));
    }

    #[test]
    fn test_audit_winner_some_but_another_has_more_books() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![3, 5],
            actions: None,
        });
        record.winner = Some(0); // player 1 has more books
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("winner")));
    }

    #[test]
    fn test_audit_winner_some_but_tied() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![5, 5],
            actions: None,
        });
        record.winner = Some(0); // tied — no unique winner
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("winner")));
    }

    #[test]
    fn test_audit_winner_none_but_clear_leader() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![5, 3],
            actions: None,
        });
        record.winner = None; // player 0 has unique max — must be declared winner
        let result = record.audit();
        assert!(!result.is_consistent);
        assert!(result.violations.iter().any(|v| v.contains("winner")));
    }

    #[test]
    fn test_audit_winner_correct_unique_max() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![5, 3],
            actions: None,
        });
        record.winner = Some(0);
        let result = record.audit();
        assert!(result.is_consistent, "violations: {:?}", result.violations);
    }

    #[test]
    fn test_audit_winner_none_correct_when_tied() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![4, 4],
            actions: None,
        });
        record.winner = None;
        let result = record.audit();
        assert!(result.is_consistent, "violations: {:?}", result.violations);
    }

    #[test]
    fn test_audit_final_books_populated_from_last_turn() {
        let mut record = make_clean_record(2, 0);
        record.turns.push(TurnRecord {
            player: 0,
            events: vec![GameEvent::Drew {
                player: 0,
                matched: false,
            }],
            books_after_turn: vec![2, 3],
            actions: None,
        });
        record.winner = Some(1);
        let result = record.audit();
        assert_eq!(result.final_books, vec![2, 3]);
    }

    #[test]
    fn test_audit_all_consistent_collection() {
        let mut col = GameCollection::new();
        col.push(make_clean_record(2, 3));
        col.push(make_clean_record(3, 4));
        let results = col.audit_all();
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|r| r.is_consistent));
    }
}