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
//! Counter rules: compiling, testing and applying [`AuxRules`].

use crate::rules::*;

use super::{err, Game, Op, RulesError, State};

/// An event as the rules name it, with groups resolved to numbers.
#[derive(Clone, Debug)]
pub(crate) enum CEvent {
    Deal,
    Transfer { from: Option<u16>, to: Option<u16> },
    Refill { group: Option<u16> },
    Extract,
}

#[derive(Clone, Debug)]
pub(crate) enum CCond {
    Counter { slot: u8, cmp: AuxCmp, value: i16 },
    AnyEmpty(u16),
    AnyNonEmpty(u16),
    RankIsCounter { slot: u8, offset: i16 },
    SharesSet { slot: u8, sets: Vec<Vec<u16>> },
    Not(Box<CCond>),
    All(Vec<CCond>),
    Any(Vec<CCond>),
}

#[derive(Clone, Debug)]
pub(crate) struct CompiledAux {
    pub updates: Vec<(CEvent, Option<CCond>, u8, AuxOp)>,
    pub gates: Vec<(CEvent, CCond)>,
    /// Pile numbers within their groups matter to the rules.
    pub positional: bool,
}

/// What is happening, for matching events and testing conditions.
#[derive(Copy, Clone, Debug)]
pub(crate) enum AuxCtx {
    Deal,
    Transfer { from: u16, to: u16, n: usize },
    Refill { group: u16 },
    Extract,
}

fn cmp(c: AuxCmp, a: i16, b: i16) -> bool {
    match c {
        AuxCmp::Eq => a == b,
        AuxCmp::Ne => a != b,
        AuxCmp::Lt => a < b,
        AuxCmp::Le => a <= b,
        AuxCmp::Gt => a > b,
        AuxCmp::Ge => a >= b,
        #[allow(unreachable_patterns)]
        _ => false,
    }
}

fn compile_event(rules: &Rules, e: &AuxEvent) -> Result<CEvent, RulesError> {
    let find = |n: &str| {
        rules
            .groups
            .iter()
            .position(|g| g.name == n)
            .map(|i| i as u16)
            .ok_or_else(|| RulesError(format!("aux: no group named {n:?}")))
    };
    let opt = |n: &Option<String>| n.as_deref().map(find).transpose();
    Ok(match e {
        AuxEvent::Deal => CEvent::Deal,
        AuxEvent::Transfer { from, to } => CEvent::Transfer {
            from: opt(from)?,
            to: opt(to)?,
        },
        AuxEvent::Extract => CEvent::Extract,
        AuxEvent::Refill { group } => CEvent::Refill { group: opt(group)? },
        #[allow(unreachable_patterns)]
        _ => return err("aux: unsupported event"),
    })
}

fn compile_cond(rules: &Rules, c: &AuxCond, ev: &CEvent) -> Result<CCond, RulesError> {
    let find = |n: &str| {
        rules
            .groups
            .iter()
            .position(|g| g.name == n)
            .map(|i| i as u16)
            .ok_or_else(|| RulesError(format!("aux: no group named {n:?}")))
    };
    let slot_ok = |slot: u8| {
        if slot < 2 {
            Ok(slot)
        } else {
            err(format!("aux: counter {slot} does not exist (0 or 1)"))
        }
    };
    let is_move = matches!(ev, CEvent::Transfer { .. });
    Ok(match c {
        AuxCond::Counter { slot, cmp, value } => CCond::Counter {
            slot: slot_ok(*slot)?,
            cmp: *cmp,
            value: *value,
        },
        AuxCond::AnyEmpty { group } => CCond::AnyEmpty(find(group)?),
        AuxCond::AnyNonEmpty { group } => CCond::AnyNonEmpty(find(group)?),
        AuxCond::RankIsCounter { slot, offset } => {
            if !is_move {
                return err("aux: rank_is_counter needs a transfer event");
            }
            CCond::RankIsCounter {
                slot: slot_ok(*slot)?,
                offset: *offset,
            }
        }
        AuxCond::SharesSetWithSource { slot, sets } => {
            if !is_move {
                return err("aux: shares_set_with_source needs a transfer event");
            }
            CCond::SharesSet {
                slot: slot_ok(*slot)?,
                sets: sets.clone(),
            }
        }
        AuxCond::Not(c) => CCond::Not(Box::new(compile_cond(rules, c, ev)?)),
        AuxCond::All(v) => CCond::All(
            v.iter()
                .map(|c| compile_cond(rules, c, ev))
                .collect::<Result<_, _>>()?,
        ),
        AuxCond::Any(v) => CCond::Any(
            v.iter()
                .map(|c| compile_cond(rules, c, ev))
                .collect::<Result<_, _>>()?,
        ),
        #[allow(unreachable_patterns)]
        _ => return err("aux: unsupported condition"),
    })
}

fn uses_source_index(c: &CCond) -> bool {
    match c {
        CCond::SharesSet { .. } => true,
        CCond::Not(c) => uses_source_index(c),
        CCond::All(v) | CCond::Any(v) => v.iter().any(uses_source_index),
        _ => false,
    }
}

pub(crate) fn compile_aux(rules: &Rules) -> Result<Option<CompiledAux>, RulesError> {
    let Some(a) = &rules.aux else { return Ok(None) };
    let mut out = CompiledAux {
        updates: Vec::new(),
        gates: Vec::new(),
        positional: false,
    };
    for u in &a.updates {
        if u.slot >= 2 {
            return err(format!("aux: counter {} does not exist (0 or 1)", u.slot));
        }
        let ev = compile_event(rules, &u.on)?;
        if matches!(ev, CEvent::Refill { .. }) {
            return err("aux: refills can be gated, not counted");
        }
        match &u.op {
            AuxOp::SourcePile => {
                if !matches!(ev, CEvent::Transfer { .. }) {
                    return err("aux: source_pile needs a transfer event");
                }
                out.positional = true;
            }
            AuxOp::Add {
                modulo: Some(m), ..
            } if *m <= 0 => return err("aux: modulo must be positive"),
            _ => {}
        }
        let when = u
            .when
            .as_ref()
            .map(|c| compile_cond(rules, c, &ev))
            .transpose()?;
        if when.as_ref().is_some_and(uses_source_index) {
            out.positional = true;
        }
        out.updates.push((ev, when, u.slot, u.op.clone()));
    }
    for g in &a.gates {
        let ev = compile_event(rules, &g.on)?;
        let c = compile_cond(rules, &g.require, &ev)?;
        if uses_source_index(&c) {
            out.positional = true;
        }
        out.gates.push((ev, c));
    }
    Ok(Some(out))
}

impl CEvent {
    fn matches(&self, g: &Game, ctx: AuxCtx) -> bool {
        match (self, ctx) {
            (CEvent::Deal, AuxCtx::Deal) => true,
            (CEvent::Transfer { from, to }, AuxCtx::Transfer { from: f, to: t, .. }) => {
                from.is_none_or(|x| x == g.pile_group[f as usize])
                    && to.is_none_or(|x| x == g.pile_group[t as usize])
            }
            (CEvent::Refill { group }, AuxCtx::Refill { group: gi }) => {
                group.is_none_or(|x| x == gi)
            }
            (CEvent::Extract, AuxCtx::Extract) => true,
            _ => false,
        }
    }
}

impl Game {
    /// Does this game keep counters?
    pub fn uses_aux(&self) -> bool {
        self.aux.is_some()
            || self.rounds.is_some()
            || matches!(self.win, crate::game::Win::TargetCard { .. })
    }

    fn aux_cond(&self, s: &State, c: &CCond, ctx: AuxCtx) -> bool {
        match c {
            CCond::Counter {
                slot,
                cmp: op,
                value,
            } => cmp(*op, s.aux[*slot as usize], *value),
            CCond::AnyEmpty(gi) => self.groups[*gi as usize]
                .piles()
                .any(|p| s.piles[p as usize].is_empty()),
            CCond::AnyNonEmpty(gi) => self.groups[*gi as usize]
                .piles()
                .any(|p| !s.piles[p as usize].is_empty()),
            CCond::RankIsCounter { slot, offset } => match ctx {
                AuxCtx::Transfer { from, n, .. } => {
                    let pile = &s.piles[from as usize];
                    n > 0
                        && n <= pile.len()
                        && i16::from(pile[pile.len() - n].rank()) == s.aux[*slot as usize] + *offset
                }
                _ => false,
            },
            CCond::SharesSet { slot, sets } => match ctx {
                AuxCtx::Transfer { from, .. } => {
                    let held = s.aux[*slot as usize];
                    let idx = from - self.group_of(from).start;
                    held >= 0
                        && sets
                            .iter()
                            .any(|set| set.contains(&(held as u16)) && set.contains(&idx))
                }
                _ => false,
            },
            CCond::Not(c) => !self.aux_cond(s, c, ctx),
            CCond::All(v) => v.iter().all(|c| self.aux_cond(s, c, ctx)),
            CCond::Any(v) => v.iter().any(|c| self.aux_cond(s, c, ctx)),
        }
    }

    /// Do the counter rules allow this event in `s`?
    pub(crate) fn aux_allows(&self, s: &State, ctx: AuxCtx) -> bool {
        let Some(a) = &self.aux else { return true };
        a.gates
            .iter()
            .all(|(ev, c)| !ev.matches(self, ctx) || self.aux_cond(s, c, ctx))
    }

    /// Apply the counter changes for an event about to happen (tested on `s` as it is now).
    pub(crate) fn aux_update(&self, s: &mut State, j: &mut Vec<Op>, ctx: AuxCtx) {
        let Some(a) = &self.aux else { return };
        let mut todo: Vec<(u8, AuxOp)> = Vec::new();
        for (ev, when, slot, op) in &a.updates {
            if ev.matches(self, ctx) && when.as_ref().is_none_or(|c| self.aux_cond(s, c, ctx)) {
                todo.push((*slot, op.clone()));
            }
        }
        for (slot, op) in todo {
            let was = s.aux[slot as usize];
            let now = match op {
                AuxOp::Set(v) => v,
                AuxOp::Add { by, modulo, floor } => {
                    let base = floor.map_or(was, |f| was.max(f));
                    let v = base + by;
                    modulo.map_or(v, |m| v.rem_euclid(m))
                }
                AuxOp::SourcePile => match ctx {
                    AuxCtx::Transfer { from, .. } => (from - self.group_of(from).start) as i16,
                    _ => was,
                },
                #[allow(unreachable_patterns)]
                _ => was,
            };
            if now != was {
                self.push(s, j, Op::SetAux { slot, was, now });
            }
        }
    }
}