diff --git a/src/commands/games/classic.rs b/src/commands/games/classic.rs index bc5f8f2..220d899 100644 --- a/src/commands/games/classic.rs +++ b/src/commands/games/classic.rs @@ -4,7 +4,7 @@ use crate::ui::Card; use rand::RngExt as _; use std::time::Duration; -// ---- tic-tac-toe (Dezio never loses — try to draw!) --------------------------------------------------------- +// ---- tic-tac-toe (Dezio plays like a person: it usually spots wins and threats, but not always) --------------------------------------------------------- const LINES: [[usize; 3]; 8] = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]; const MARKS: [&str; 2] = ["❌", "⭕"]; @@ -18,7 +18,8 @@ fn ttt_winner(b: &Board) -> Option<(u8, [usize; 3])> { }) } -/// Score for the player to move (`me`): 1 win, 0 draw, -1 loss. +/// Score for the player to move (`me`): 1 win, 0 draw, -1 loss (only the tests use the perfect player now). +#[cfg(test)] fn minimax(b: &mut Board, me: u8) -> i32 { if let Some((w, _)) = ttt_winner(b) { return if w == me { 1 } else { -1 }; @@ -40,7 +41,47 @@ fn minimax(b: &mut Board, me: u8) -> i32 { best } +/// The cells where `who` would win on the next move. +fn winning_cells(b: &Board, who: u8) -> Vec { + let mut work = *b; + let mut out = Vec::new(); + for i in 0..9 { + if work[i].is_none() { + work[i] = Some(who); + if ttt_winner(&work).is_some_and(|w| w.0 == who) { + out.push(i); + } + work[i] = None; + } + } + out +} + +/// A human-like move: usually takes a win and blocks a threat, but misses them sometimes, and otherwise +/// likes the centre and corners without planning ahead — so it can be beaten (a fork wins). fn ttt_best_move(b: &Board, me: u8) -> usize { + let mut rng = rand::rng(); + let wins = winning_cells(b, me); + if !wins.is_empty() && rng.random_bool(0.9) { + return wins[rng.random_range(0..wins.len())]; + } + let threats = winning_cells(b, 1 - me); + if !threats.is_empty() && rng.random_bool(0.7) { + return threats[rng.random_range(0..threats.len())]; + } + let empty: Vec = (0..9).filter(|i| b[*i].is_none()).collect(); + if b[4].is_none() && rng.random_bool(0.45) { + return 4; + } + let corners: Vec = empty.iter().copied().filter(|i| [0, 2, 6, 8].contains(i)).collect(); + if !corners.is_empty() && rng.random_bool(0.4) { + return corners[rng.random_range(0..corners.len())]; + } + empty[rng.random_range(0..empty.len())] +} + +#[cfg(test)] +fn ttt_perfect_move(b: &Board, me: u8) -> usize { let mut scores = Vec::new(); let mut work = *b; for i in 0..9 { @@ -256,7 +297,15 @@ fn negamax(g: &mut Grid, depth: u32, me: u8, mut alpha: i32, beta: i32, last: (u best } -fn c4_best_move(board: &Grid, me: u8, depth: u32) -> usize { +/// A casual player: looks only 1–3 moves ahead (so it sees a four coming but misses long plans) and +/// now and then just drops a disc somewhere. +fn c4_best_move(board: &Grid, me: u8, _depth: u32) -> usize { + let mut rng = rand::rng(); + let open: Vec = ORDER.iter().copied().filter(|c| drop_row(board, *c).is_some()).collect(); + if open.len() > 1 && rng.random_bool(0.12) { + return open[rng.random_range(0..open.len())]; + } + let depth = [1u32, 2, 2, 3][rng.random_range(0..4)]; let mut g = *board; let mut scores = Vec::new(); for col in ORDER { @@ -502,25 +551,30 @@ mod tests { } #[test] - fn dezio_never_loses_at_tic_tac_toe() { - // play every possible human line against the bot: it must never lose - fn explore(g: &Ttt, depth: u32) { - if g.over { - if let Some((w, _)) = ttt_winner(&g.board) { - assert_eq!(w, 1, "the human won?!"); - } - return; + fn dezio_at_tic_tac_toe_can_be_beaten_but_still_plays_sensibly() { + // a perfect player against the bot: it should win some games (the bot misses things) but the bot must + // also win or block often enough to be a real opponent + let (mut human_wins, mut bot_wins) = (0, 0); + for round in 0..400 { + let mut g = Ttt::new(human(1), robot(), round % 2); + while !g.over { + let cell = ttt_perfect_move(&g.board, g.turn as u8); + g.click(1, &format!("m{cell}"), &[], &Default::default()); } - for i in 0..9 { - if g.board[i].is_none() { - let mut next = Ttt { p: g.p.clone(), board: g.board, turn: g.turn, starter: g.starter, over: false, timed_out: false }; - next.click(1, &format!("m{i}"), &[], &Default::default()); - explore(&next, depth + 1); - } + match ttt_winner(&g.board) { + Some((w, _)) if g.p[w as usize].bot => bot_wins += 1, + Some(_) => human_wins += 1, + None => {} } } - explore(&Ttt::new(human(1), robot(), 0), 0); - explore(&Ttt::new(human(1), robot(), 1), 0); + assert!(human_wins > 20, "never beatable: {human_wins}"); + assert!(bot_wins > 0 || human_wins < 400, "{bot_wins} {human_wins}"); + // it takes an open win and blocks an open threat most of the time + let board = [Some(1), Some(1), None, Some(0), Some(0), None, None, None, None]; + let wins = (0..200).filter(|_| ttt_best_move(&board, 1) == 2).count(); + assert!(wins > 140, "{wins}"); + let blocks = (0..200).filter(|_| ttt_best_move(&[Some(0), Some(0), None, None, Some(1), None, None, None, None], 1) == 2).count(); + assert!(blocks > 100, "{blocks}"); } #[test] diff --git a/src/commands/games/hangman.rs b/src/commands/games/hangman.rs index 592d4e4..5735a75 100644 --- a/src/commands/games/hangman.rs +++ b/src/commands/games/hangman.rs @@ -1,9 +1,9 @@ -//! Hangman. Pick letters from the two dropdowns or guess the whole word. +//! Hangman. Guess a letter (a button that opens a text box) or guess the whole word. //! //! * Random word from a category — you (and your opponent, if you named one) guess together. //! * Custom word — the person who set it can't guess; their opponent (or anyone, if no opponent was named) does. use super::*; -use crate::ui::{select_menu, Card}; +use crate::ui::Card; const STAGES: [&str; 7] = [ " ┌───┐\n │\n │\n │\n ═╧═", @@ -104,14 +104,7 @@ impl Game for Hangman { wrong.dedup(); card = card.text(&format!("{status}{}", if wrong.is_empty() { String::new() } else { format!("\n-# Wrong: {}", wrong.join(", ")) })); if !self.over { - let remaining: Vec = ('a'..='z').filter(|c| !self.guessed.contains(c) && !self.misses.contains(&c.to_string())).collect(); - for (half, action, letters) in [("A–M", "la", remaining.iter().filter(|c| **c <= 'm').collect::>()), ("N–Z", "lb", remaining.iter().filter(|c| **c > 'm').collect::>())] { - let options = if letters.is_empty() { vec![opt("-", "-")] } else { letters.iter().map(|c| opt(&c.to_uppercase().to_string(), &c.to_string())).collect() }; - let mut menu = select_menu(&format!("gm:{t}:{action}"), &if letters.is_empty() { format!("No letters left in {half}") } else { format!("Pick a letter ({half})") }, options); - menu.disabled = letters.is_empty(); - card = card.select(menu); - } - card = card.row(vec![btn(t, "word", "Guess the word", "💬", ButtonStyle::Primary, false)]); + card = card.row(vec![btn(t, "letter", "Guess a letter", "🔤", ButtonStyle::Primary, false), btn(t, "word", "Guess the word", "💬", ButtonStyle::Secondary, false)]); let who = if self.custom && self.guessers.is_empty() { format!("anyone except {}", self.setter.name()) } else { self.guessers.iter().map(P::name).collect::>().join(", ") }; card = card.footer(&format!("Guessing: {who}{}", if self.custom { format!(" · word set by {}", self.setter.name()) } else { String::new() })); } else if !self.custom && !self.timed_out { @@ -123,11 +116,18 @@ impl Game for Hangman { fn click(&mut self, who: u64, action: &str, values: &[String], fields: &HashMap) -> Reply { let name = |me: &Hangman| me.guessers.iter().find(|p| p.id == who).map(|p| p.name()).unwrap_or_else(|| "someone".into()); match action { - "la" | "lb" => { - let Some(letter) = values.first().and_then(|v| v.chars().next()).filter(|c| c.is_ascii_lowercase()) else { return Reply::Ignore }; - if self.over || self.guessed.contains(&letter) || self.misses.contains(&letter.to_string()) { + "letter" => Reply::Modal { action: "lettersub".into(), title: "Guess a letter".into(), fields: vec![crate::interact::text_field("letter", "One letter", None, "", 1, false, Some("e.g. e"))] }, + "lettersub" | "la" | "lb" => { + let typed = fields.get("letter").cloned().or_else(|| values.first().cloned()).unwrap_or_default(); + let Some(letter) = typed.trim().to_lowercase().chars().next().filter(|c| c.is_alphabetic()) else { + return Reply::Private("Type a single letter.".into()); + }; + if self.over { return Reply::Ignore; } + if self.guessed.contains(&letter) || self.misses.contains(&letter.to_string()) { + return Reply::Private(format!("**{}** was already guessed.", letter.to_uppercase())); + } if self.word.contains(letter) { self.guessed.push(letter); if self.won() {