dealbreaker 1.4.0

A data-driven solver for patience / solitaire card games: describe a game's rules as data, get solutions or proofs of unsolvability.
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Hints that respect hidden cards.
//!
//! [`crate::solve`] sees every card. A player doesn't, so a hint computed from the true deal
//! could leak where a face-down card is. [`hint`] instead treats every face-down card as
//! unknown: it deals the unknown cards at random among the face-down places many times, solves
//! each guess, and recommends the first step that wins most often.
//!
//! In a game played for points, every possible next step is tried on every guess instead, and
//! the step with the highest average best score is recommended.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::game::{Game, State, Step};
use crate::rng::Rng;
use crate::solver::{
    maximize, maximize_with_cancel, solve, solve_with_cancel, Outcome, SolveOptions,
};

fn default_max_candidates() -> usize {
    3
}

/// Hint settings.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
#[non_exhaustive]
pub struct HintOptions {
    /// Random guesses at the hidden cards (ignored when nothing is hidden).
    pub samples: u32,
    /// Search options for each guess. Its `max_states` is the budget for each guess.
    pub solve: SolveOptions,
    pub seed: u64,
    /// Maximum ranked candidates returned by [`hints`] (default 3).
    #[serde(default = "default_max_candidates")]
    pub max_candidates: usize,
}

impl Default for HintOptions {
    fn default() -> Self {
        HintOptions {
            samples: 16,
            solve: SolveOptions {
                max_states: 100_000,
                ..SolveOptions::default()
            },
            seed: 0,
            max_candidates: default_max_candidates(),
        }
    }
}

impl HintOptions {
    /// Random guesses at the hidden cards.
    pub fn samples(mut self, n: u32) -> Self {
        self.samples = n;
        self
    }

    /// Search options for each guess.
    pub fn solve(mut self, opts: SolveOptions) -> Self {
        self.solve = opts;
        self
    }

    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Maximum ranked candidates returned by [`hints`].
    pub fn max_candidates(mut self, n: usize) -> Self {
        self.max_candidates = n;
        self
    }
}

/// A recommended next step.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct Hint {
    pub step: Step,
    /// Guesses in which this step started a win.
    pub wins: u32,
    /// Guesses tried.
    pub samples: u32,
    /// Games played for points: the step's average best score over the guesses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub score: Option<f64>,
}

/// Ranked fair-hint recommendations along with sample outcome counts.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct HintReport {
    /// Recommended next steps, ranked best first (up to [`HintOptions::max_candidates`]).
    pub candidates: Vec<Hint>,
    /// Total samples completed.
    pub samples: u32,
    /// Samples for which a winning line was found (or scored rollout completed).
    pub solved_samples: u32,
    /// Samples proven unsolvable within the budget.
    pub unsolvable_samples: u32,
    /// Samples that hit the search budget or timeout without a verdict.
    pub gave_up_samples: u32,
}

/// Recommend a next step without looking at face-down cards. `None` if no guess could be won
/// within the budget.
pub fn hint(game: &Game, state: &State, opts: &HintOptions) -> Option<Hint> {
    hints_inner(game, state, opts, None)
        .candidates
        .into_iter()
        .next()
}

/// Like [`hint`], stopping early if `cancel` becomes `true`.
///
/// Checked between samples and periodically inside each underlying search. If cancelled after
/// some samples have already completed, returns the best recommendation from completed samples
/// (or `None` if none succeeded).
pub fn hint_with_cancel(
    game: &Game,
    state: &State,
    opts: &HintOptions,
    cancel: &AtomicBool,
) -> Option<Hint> {
    hints_inner(game, state, opts, Some(cancel))
        .candidates
        .into_iter()
        .next()
}

/// Recommend up to [`HintOptions::max_candidates`] ranked next steps without looking at
/// face-down cards, along with sample outcome counts (solved / unsolvable / gave up).
pub fn hints(game: &Game, state: &State, opts: &HintOptions) -> HintReport {
    hints_inner(game, state, opts, None)
}

/// Like [`hints`], stopping early if `cancel` becomes `true`.
pub fn hints_with_cancel(
    game: &Game,
    state: &State,
    opts: &HintOptions,
    cancel: &AtomicBool,
) -> HintReport {
    hints_inner(game, state, opts, Some(cancel))
}

fn empty_report() -> HintReport {
    HintReport {
        candidates: Vec::new(),
        samples: 0,
        solved_samples: 0,
        unsolvable_samples: 0,
        gave_up_samples: 0,
    }
}

fn hints_inner(
    game: &Game,
    state: &State,
    opts: &HintOptions,
    cancel: Option<&AtomicBool>,
) -> HintReport {
    if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
        return empty_report();
    }
    let hidden: Vec<(usize, usize)> = state
        .piles
        .iter()
        .enumerate()
        .flat_map(|(p, pile)| {
            pile.iter()
                .enumerate()
                .filter(|(_, c)| !c.is_face_up())
                .map(move |(i, _)| (p, i))
        })
        .collect();
    // A shuffling redeal makes the future unknown even with every card face up.
    let random_future = game.rules().redeal.as_ref().is_some_and(|r| {
        matches!(
            r.how,
            crate::rules::RedealHow::Shuffle { .. }
                | crate::rules::RedealHow::ShuffleTopUp { .. }
                | crate::rules::RedealHow::ShuffleRedeal
                | crate::rules::RedealHow::ShuffleFill { .. }
                | crate::rules::RedealHow::GridShuffle
                | crate::rules::RedealHow::GridShuffleRandomGaps
                | crate::rules::RedealHow::GridShuffleEndGaps
        )
    }) || game.rules().stock.as_ref().is_some_and(|st| {
        st.redeal_shuffle || st.fill_empty_or_reshuffle || st.reshuffle_at_counter.is_some()
    });
    let samples = if hidden.is_empty() && !random_future {
        1
    } else {
        opts.samples.max(1)
    };
    let mut rng = Rng::new(opts.seed);
    let guess = |rng: &mut Rng| {
        let mut guess = state.clone();
        // Future shuffles are unknown too.
        if random_future {
            guess.seed = rng.next_u64();
        }
        let mut cards: Vec<_> = hidden.iter().map(|&(p, i)| state.piles[p][i]).collect();
        rng.shuffle(&mut cards);
        for (&(p, i), c) in hidden.iter().zip(cards) {
            guess.piles[p][i] = c;
        }
        guess
    };
    if game.is_scored() {
        return scored_hints(game, state, opts, samples, cancel, || guess(&mut rng));
    }
    #[cfg(feature = "parallel")]
    enum SampleOutcome {
        Solved(Option<Step>),
        Unsolvable,
        GaveUp,
    }
    let mut votes: HashMap<String, (Step, u32)> = HashMap::new();
    let mut order: Vec<String> = Vec::new();
    let mut tried = 0u32;
    let mut solved_samples = 0u32;
    let mut unsolvable_samples = 0u32;
    let mut gave_up_samples = 0u32;
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        const CHUNK: u32 = 256;
        let mut remaining = samples;
        while remaining > 0 {
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                break;
            }
            let batch = remaining.min(CHUNK);
            remaining -= batch;
            let guesses: Vec<State> = (0..batch).map(|_| guess(&mut rng)).collect();
            let outcomes: Vec<Option<SampleOutcome>> = guesses
                .par_iter()
                .map(|g| {
                    if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                        return None;
                    }
                    let r = match cancel {
                        Some(c) => solve_with_cancel(game, g, &opts.solve, c),
                        None => solve(game, g, &opts.solve),
                    };
                    let outcome = match r.outcome {
                        Outcome::Solved(moves) => {
                            SampleOutcome::Solved(game.steps(g, &moves).into_iter().next())
                        }
                        Outcome::Unsolvable => SampleOutcome::Unsolvable,
                        Outcome::GaveUp => SampleOutcome::GaveUp,
                    };
                    Some(outcome)
                })
                .collect();
            for item in outcomes {
                let Some(outcome) = item else {
                    continue;
                };
                tried += 1;
                match outcome {
                    SampleOutcome::Solved(step_opt) => {
                        solved_samples += 1;
                        if let Some(step) = step_opt {
                            let key = format!("{step:?}");
                            let e = votes.entry(key.clone()).or_insert_with(|| {
                                order.push(key);
                                (step, 0)
                            });
                            e.1 += 1;
                        }
                    }
                    SampleOutcome::Unsolvable => unsolvable_samples += 1,
                    SampleOutcome::GaveUp => gave_up_samples += 1,
                }
            }
        }
    }
    #[cfg(not(feature = "parallel"))]
    for _ in 0..samples {
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            break;
        }
        let guess = guess(&mut rng);
        let r = match cancel {
            Some(c) => solve_with_cancel(game, &guess, &opts.solve, c),
            None => solve(game, &guess, &opts.solve),
        };
        tried += 1;
        match r.outcome {
            Outcome::Solved(moves) => {
                solved_samples += 1;
                if let Some(step) = game.steps(&guess, &moves).into_iter().next() {
                    let key = format!("{step:?}");
                    let e = votes.entry(key.clone()).or_insert_with(|| {
                        order.push(key);
                        (step, 0)
                    });
                    e.1 += 1;
                }
            }
            Outcome::Unsolvable => unsolvable_samples += 1,
            Outcome::GaveUp => gave_up_samples += 1,
        }
    }
    // Most wins; earliest found breaks ties.
    let mut ranked: Vec<(usize, String)> = order.into_iter().enumerate().collect();
    ranked.sort_by(|(ia, ka), (ib, kb)| votes[kb].1.cmp(&votes[ka].1).then_with(|| ia.cmp(ib)));
    let limit = opts.max_candidates.max(1);
    let candidates = ranked
        .into_iter()
        .take(limit)
        .filter_map(|(_, k)| {
            let (step, wins) = votes.remove(&k)?;
            Some(Hint {
                step,
                wins,
                samples: tried,
                score: None,
            })
        })
        .collect();
    HintReport {
        candidates,
        samples: tried,
        solved_samples,
        unsolvable_samples,
        gave_up_samples,
    }
}

/// Try every distinct next step on every guess; recommend the best average scores. `wins`
/// counts guesses where the step's best line reached the game's target score, if it has one.
fn scored_hints(
    game: &Game,
    state: &State,
    opts: &HintOptions,
    samples: u32,
    cancel: Option<&AtomicBool>,
    mut guess: impl FnMut() -> State,
) -> HintReport {
    let moves = game.distinct_moves(state);
    match moves.as_slice() {
        [] => return empty_report(),
        // Nothing to choose between.
        [m] => {
            let candidates = game
                .steps(state, &[*m])
                .into_iter()
                .next()
                .map(|step| Hint {
                    step,
                    wins: 0,
                    samples: 0,
                    score: None,
                })
                .into_iter()
                .collect();
            return HintReport {
                candidates,
                samples: 0,
                solved_samples: 0,
                unsolvable_samples: 0,
                gave_up_samples: 0,
            };
        }
        _ => {}
    }
    let per = SolveOptions {
        max_states: (opts.solve.max_states / moves.len() as u64).max(1),
        ..opts.solve.clone()
    };
    let mut totals = vec![(0u64, 0u32); moves.len()];
    let mut completed = 0u32;
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        const CHUNK: u32 = 256;
        let mut remaining = samples;
        while remaining > 0 {
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                break;
            }
            let batch = remaining.min(CHUNK);
            remaining -= batch;
            let guesses: Vec<State> = (0..batch).map(|_| guess()).collect();
            let results: Vec<Option<Vec<(u64, u32)>>> = guesses
                .par_iter()
                .map(|g| {
                    let mut scores = vec![(0u64, 0u32); moves.len()];
                    for (i, &m) in moves.iter().enumerate() {
                        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                            return None;
                        }
                        let mut s = g.clone();
                        if game.play(&mut s, m).is_err() {
                            continue;
                        }
                        let r = match cancel {
                            Some(c) => maximize_with_cancel(game, &s, &per, c),
                            None => maximize(game, &s, &per),
                        };
                        scores[i].0 = r.score as u64;
                        if game.target_score().is_some_and(|t| r.score >= t) {
                            scores[i].1 = 1;
                        }
                    }
                    Some(scores)
                })
                .collect();
            for scores in results.into_iter().flatten() {
                for (t, &(sc, w)) in totals.iter_mut().zip(&scores) {
                    t.0 += sc;
                    t.1 += w;
                }
                completed += 1;
            }
        }
    }
    #[cfg(not(feature = "parallel"))]
    {
        let mut sample_scores = vec![(0u64, 0u32); moves.len()];
        'samples: for _ in 0..samples {
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                break;
            }
            let g = guess();
            sample_scores.fill((0, 0));
            for (i, &m) in moves.iter().enumerate() {
                if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                    break 'samples;
                }
                let mut s = g.clone();
                if game.play(&mut s, m).is_err() {
                    continue;
                }
                let r = match cancel {
                    Some(c) => maximize_with_cancel(game, &s, &per, c),
                    None => maximize(game, &s, &per),
                };
                sample_scores[i].0 = r.score as u64;
                if game.target_score().is_some_and(|t| r.score >= t) {
                    sample_scores[i].1 = 1;
                }
            }
            for (t, &(sc, w)) in totals.iter_mut().zip(&sample_scores) {
                t.0 += sc;
                t.1 += w;
            }
            completed += 1;
        }
    }
    if completed == 0 {
        return empty_report();
    }
    // Highest total; the earliest step breaks ties.
    let mut order: Vec<usize> = (0..moves.len()).collect();
    order.sort_by(|&a, &b| totals[b].0.cmp(&totals[a].0).then_with(|| a.cmp(&b)));
    let limit = opts.max_candidates.max(1);
    let candidates = order
        .into_iter()
        .take(limit)
        .filter_map(|i| {
            let (total, wins) = totals[i];
            let step = game.steps(state, &[moves[i]]).into_iter().next()?;
            Some(Hint {
                step,
                wins,
                samples: completed,
                score: Some(total as f64 / completed as f64),
            })
        })
        .collect();
    HintReport {
        candidates,
        samples: completed,
        solved_samples: completed,
        unsolvable_samples: 0,
        gave_up_samples: 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::presets;

    #[test]
    fn hint_random_future_and_budget_exhaustion() {
        // La Belle Lucie has a shuffling redeal, so even with all cards face up it samples.
        let g = Game::new(presets::la_belle_lucie()).unwrap();
        let s = g.deal(1);
        let opts = HintOptions::default()
            .samples(2)
            .seed(7)
            .solve(SolveOptions::default().max_states(5_000));
        if let Some(h) = hint(&g, &s, &opts) {
            assert_eq!(h.samples, 2);
            assert!(h.wins >= 1);
        }

        // Tiny budget on an unsolved position yields None.
        let fc = Game::new(presets::freecell()).unwrap();
        let fs = fc.deal(1);
        let tiny = HintOptions::default().solve(SolveOptions::default().max_states(1));
        assert!(hint(&fc, &fs, &tiny).is_none());
    }

    #[test]
    fn scored_hint_edge_cases() {
        let g = Game::new(presets::poker_squares()).unwrap();
        let mut s = g.deal(1);
        // Play 25 cards to leave 0 legal moves.
        let mut plays = 0;
        while plays < 25 {
            let moves = g.distinct_moves(&s);
            if moves.is_empty() {
                break;
            }
            g.play(&mut s, moves[0]).unwrap();
            plays += 1;
        }
        assert!(hint(&g, &s, &HintOptions::default()).is_none());

        // Back up by 1 card (24 placed -> only 1 empty cell left, so 1 distinct move).
        let mut s24 = g.deal(1);
        for _ in 0..24 {
            let m = g.distinct_moves(&s24)[0];
            g.play(&mut s24, m).unwrap();
        }
        let h = hint(&g, &s24, &HintOptions::default()).expect("single forced move");
        assert_eq!(h.samples, 0);
        assert_eq!(h.score, None);
    }

    #[test]
    fn hint_with_cancel_stops_immediately() {
        let cancel = AtomicBool::new(true);
        let kl = Game::new(presets::klondike1()).unwrap();
        let ks = kl.deal(1);
        assert!(hint_with_cancel(&kl, &ks, &HintOptions::default(), &cancel).is_none());

        let ps = Game::new(presets::poker_squares()).unwrap();
        let pstate = ps.deal(1);
        assert!(hint_with_cancel(&ps, &pstate, &HintOptions::default(), &cancel).is_none());
    }

    #[test]
    fn hint_is_deterministic_across_repeated_calls() {
        let kl = Game::new(presets::klondike1()).unwrap();
        let ks = kl.deal(2);
        let opts = HintOptions::default()
            .samples(4)
            .seed(42)
            .solve(SolveOptions::default().max_states(10_000));
        let h1 = hint(&kl, &ks, &opts);
        let h2 = hint(&kl, &ks, &opts);
        assert_eq!(h1, h2);
    }

    #[test]
    fn scored_hint_is_deterministic_across_repeated_calls() {
        let ps = Game::new(presets::poker_squares()).unwrap();
        let mut s = ps.deal(5);
        for i in 0..3 {
            let to = ps.pile_index("tableau", i * 6).unwrap();
            let from = ps.pile_index("waste", 0).unwrap();
            ps.play(
                &mut s,
                crate::game::Move::new(crate::game::Action::Transfer { from, to, count: 1 }),
            )
            .unwrap();
        }
        let opts = HintOptions::default()
            .samples(4)
            .seed(11)
            .solve(SolveOptions::default().max_states(2_000));
        let h1 = hint(&ps, &s, &opts);
        let h2 = hint(&ps, &s, &opts);
        assert_eq!(h1, h2);
        assert!(h1.is_some());
    }

    #[test]
    fn hints_returns_ranked_candidates_and_outcome_counts() {
        // Scored game returns multiple ranked candidates sorted by average score.
        let ps = Game::new(presets::poker_squares()).unwrap();
        let mut s = ps.deal(5);
        for i in 0..3 {
            let to = ps.pile_index("tableau", i * 6).unwrap();
            let from = ps.pile_index("waste", 0).unwrap();
            ps.play(
                &mut s,
                crate::game::Move::new(crate::game::Action::Transfer { from, to, count: 1 }),
            )
            .unwrap();
        }
        let opts = HintOptions::default()
            .samples(3)
            .seed(11)
            .max_candidates(3)
            .solve(SolveOptions::default().max_states(1_000));
        let report = hints(&ps, &s, &opts);
        assert_eq!(report.samples, 3);
        assert_eq!(report.solved_samples, 3);
        assert!(report.candidates.len() >= 2);
        assert!(report.candidates.len() <= 3);
        // Candidates are sorted non-increasing by average score.
        for pair in report.candidates.windows(2) {
            assert!(pair[0].score.unwrap() >= pair[1].score.unwrap());
        }
        assert_eq!(report.candidates[0], hint(&ps, &s, &opts).unwrap());

        // Tiny budget on FreeCell records gave_up_samples accurately.
        let fc = Game::new(presets::freecell()).unwrap();
        let fs = fc.deal(1);
        let tiny = HintOptions::default().solve(SolveOptions::default().max_states(1));
        let r = hints(&fc, &fs, &tiny);
        assert!(r.candidates.is_empty());
        assert_eq!(r.samples, 1);
        assert_eq!(r.gave_up_samples, 1);
        assert_eq!(r.solved_samples, 0);
    }
}