Skip to main content

ai_backgammon/
protocol.rs

1use crate::{
2    Dice, Game, GameKind, GameOutcome, GamePhase, Location, Player, Point, SearchReport, Searcher,
3    Step, Turn, search_preset,
4};
5use std::fmt::Write;
6
7/// A stateful text-protocol session for native clients and the WASM worker.
8pub struct Engine {
9    game: Game,
10    turn: Option<Turn>,
11    last_roll: Option<[u8; 2]>,
12    last_step: Option<Step>,
13    last_passed: Option<Player>,
14    last_analysis: Option<SearchReport>,
15    searcher: Searcher,
16}
17
18impl Default for Engine {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl Engine {
25    pub fn new() -> Self {
26        Self {
27            game: Game::new(),
28            turn: None,
29            last_roll: None,
30            last_step: None,
31            last_passed: None,
32            last_analysis: None,
33            searcher: Searcher::new(),
34        }
35    }
36
37    /// Runs one protocol command and returns zero or more response lines.
38    ///
39    /// The commands are `gai`, `isready`, `newgame`, `opening`, `roll`,
40    /// `step`, `undo`, `search`, `state`, and `quit`.
41    pub fn command(&mut self, line: &str) -> Vec<String> {
42        let words = line.split_whitespace().collect::<Vec<_>>();
43        let Some(command) = words.first().copied() else {
44            return vec![error("empty command")];
45        };
46        match command {
47            "gai" => vec![
48                "id name ai-backgammon".to_owned(),
49                "id game backgammon".to_owned(),
50                "gaiok".to_owned(),
51            ],
52            "isready" => vec!["readyok".to_owned()],
53            "newgame" if words.len() == 1 => {
54                self.replace_game();
55                Vec::new()
56            }
57            "opening" => self.opening_roll(&words[1..]),
58            "roll" => self.roll(&words[1..]),
59            "step" => self.step(&words[1..]),
60            "undo" if words.len() == 1 => self.undo(),
61            "search" => self.search(&words[1..]),
62            "state" if words.len() == 1 => vec![format!("state {}", self.snapshot_json())],
63            "quit" => Vec::new(),
64            _ => vec![error("unknown command or invalid arguments")],
65        }
66    }
67
68    /// Serializes the current game, partial turn, and last search report as JSON.
69    pub fn snapshot_json(&self) -> String {
70        let position = self
71            .turn
72            .as_ref()
73            .map_or_else(|| self.game.position(), Turn::preview_position);
74        let phase = self.game.phase();
75        let mut json = String::with_capacity(2_048);
76        json.push_str("{\"points\":[");
77        for (index, count) in position.points().iter().enumerate() {
78            if index > 0 {
79                json.push(',');
80            }
81            write!(json, "{count}").expect("writing to a String cannot fail");
82        }
83        write!(
84            json,
85            "],\"bar\":{{\"white\":{},\"black\":{}}},\"off\":{{\"white\":{},\"black\":{}}},",
86            position.bar(Player::White),
87            position.bar(Player::Black),
88            position.off(Player::White),
89            position.off(Player::Black),
90        )
91        .expect("writing to a String cannot fail");
92        write!(
93            json,
94            "\"sideToMove\":\"{}\",\"phase\":\"{}\",",
95            position.side_to_move(),
96            phase_name(phase),
97        )
98        .expect("writing to a String cannot fail");
99        json.push_str("\"dice\":");
100        write_dice(&mut json, self.last_roll);
101        json.push_str(",\"remainingDice\":[");
102        if let Some(turn) = &self.turn {
103            write_numbers(&mut json, &turn.remaining_dice());
104        }
105        json.push_str("],\"legalSteps\":[");
106        if let Some(turn) = &self.turn {
107            write_steps(&mut json, &turn.legal_steps());
108        }
109        json.push_str("],\"turnSteps\":[");
110        if let Some(turn) = &self.turn {
111            write_steps(&mut json, turn.steps());
112        }
113        json.push_str("],\"lastStep\":");
114        if let Some(step) = self.last_step {
115            write_step(&mut json, step);
116        } else {
117            json.push_str("null");
118        }
119        write!(
120            json,
121            ",\"canUndo\":{},\"openingTied\":{},\"lastPassed\":{},\"result\":{},\"analysis\":{}",
122            self.turn
123                .as_ref()
124                .is_some_and(|turn| !turn.steps().is_empty()),
125            matches!(phase, GamePhase::OpeningRoll) && self.last_roll.is_some(),
126            player_json(self.last_passed),
127            result_json(phase),
128            analysis_json(self.last_analysis.as_ref()),
129        )
130        .expect("writing to a String cannot fail");
131        json.push('}');
132        json
133    }
134
135    fn opening_roll(&mut self, words: &[&str]) -> Vec<String> {
136        let Some([white, black]) = parse_dice(words) else {
137            return vec![error("expected: opening WHITE_DIE BLACK_DIE")];
138        };
139        match self.game.opening_roll(white, black) {
140            Ok(false) => {
141                self.last_analysis = None;
142                self.last_roll = Some([white, black]);
143                self.last_step = None;
144                self.last_passed = None;
145                vec!["info string opening roll tied".to_owned()]
146            }
147            Ok(true) => {
148                self.last_analysis = None;
149                self.last_roll = Some([white, black]);
150                self.last_step = None;
151                self.last_passed = None;
152                self.begin_turn()
153            }
154            Err(message) => vec![error(&message.to_string())],
155        }
156    }
157
158    fn roll(&mut self, words: &[&str]) -> Vec<String> {
159        let Some([first, second]) = parse_dice(words) else {
160            return vec![error("expected: roll FIRST_DIE SECOND_DIE")];
161        };
162        let dice = Dice::new(first, second).expect("parsed dice are valid");
163        match self.game.roll(dice) {
164            Ok(()) => {
165                self.last_analysis = None;
166                self.last_roll = Some([first, second]);
167                self.last_step = None;
168                self.last_passed = None;
169                self.begin_turn()
170            }
171            Err(message) => vec![error(&message.to_string())],
172        }
173    }
174
175    fn begin_turn(&mut self) -> Vec<String> {
176        let GamePhase::CheckerPlay(dice) = self.game.phase() else {
177            return vec![error("checker play did not start")];
178        };
179        let turn = match Turn::new(self.game.position(), dice) {
180            Ok(turn) => turn,
181            Err(message) => return vec![error(&message.to_string())],
182        };
183        if turn.is_pass() {
184            let passed = self.game.position().side_to_move();
185            let play = turn.finish().expect("a pass is a complete play");
186            if let Err(message) = self.game.play(&play) {
187                return vec![error(&message.to_string())];
188            }
189            self.turn = None;
190            self.last_passed = Some(passed);
191            vec![format!("info string {passed} has no legal checker play")]
192        } else {
193            self.turn = Some(turn);
194            Vec::new()
195        }
196    }
197
198    fn step(&mut self, words: &[&str]) -> Vec<String> {
199        let [from, to, die] = words else {
200            return vec![error("expected: step FROM TO DIE")];
201        };
202        let Some(from) = parse_location(from) else {
203            return vec![error("step source must be bar or p1 through p24")];
204        };
205        let Some(to) = parse_location(to) else {
206            return vec![error("step destination must be off or p1 through p24")];
207        };
208        let Ok(die) = die.parse::<u8>() else {
209            return vec![error("step die must be from 1 through 6")];
210        };
211        let Ok(step) = Step::new(from, to, die) else {
212            return vec![error("step needs a valid source, destination, and die")];
213        };
214        let Some(turn) = self.turn.as_mut() else {
215            return vec![error("there is no checker turn in progress")];
216        };
217        if let Err(message) = turn.select(step) {
218            return vec![error(&message.to_string())];
219        }
220        self.last_analysis = None;
221        self.last_step = Some(step);
222        if !turn.is_complete() {
223            return Vec::new();
224        }
225        let turn = self.turn.take().expect("the completed turn exists");
226        let play = turn
227            .finish()
228            .expect("the selected checker turn is complete");
229        match self.game.play(&play) {
230            Ok(()) => Vec::new(),
231            Err(message) => vec![error(&message.to_string())],
232        }
233    }
234
235    fn undo(&mut self) -> Vec<String> {
236        let Some(turn) = self.turn.as_mut() else {
237            return vec![error("there is no checker step to undo")];
238        };
239        if !turn.undo() {
240            return vec![error("there is no checker step to undo")];
241        }
242        self.last_analysis = None;
243        self.last_step = turn.steps().last().copied();
244        Vec::new()
245    }
246
247    fn replace_game(&mut self) {
248        self.game.restart();
249        self.turn = None;
250        self.last_roll = None;
251        self.last_step = None;
252        self.last_passed = None;
253        self.last_analysis = None;
254    }
255
256    fn search(&mut self, words: &[&str]) -> Vec<String> {
257        let [name] = words else {
258            return vec![error("expected: search PRESET")];
259        };
260        let Some(preset) = search_preset(name) else {
261            return vec![error("unknown search preset")];
262        };
263        let GamePhase::CheckerPlay(dice) = self.game.phase() else {
264            return vec![error("search requires a checker turn")];
265        };
266        if self
267            .turn
268            .as_ref()
269            .is_none_or(|turn| !turn.steps().is_empty())
270        {
271            return vec![error("search requires the start of a checker turn")];
272        }
273
274        let report = self
275            .searcher
276            .search(self.game.position(), dice, preset.options);
277        let Some(play) = report.best_play.as_ref() else {
278            return vec![error("search found no legal checker play")];
279        };
280        let output = vec![
281            format!(
282                "info depth {} nodes {} chance {} tthits {} equity {:.4}",
283                report.depth,
284                report.nodes,
285                report.chance_nodes,
286                report.tt_hits,
287                report.equity.expected_points(),
288            ),
289            format!("bestplay {play}"),
290        ];
291        self.last_analysis = Some(report);
292        output
293    }
294}
295
296fn parse_dice(words: &[&str]) -> Option<[u8; 2]> {
297    let [first, second] = words else {
298        return None;
299    };
300    let first = first.parse::<u8>().ok()?;
301    let second = second.parse::<u8>().ok()?;
302    Dice::new(first, second).ok()?;
303    Some([first, second])
304}
305
306fn parse_location(word: &str) -> Option<Location> {
307    match word {
308        "bar" => Some(Location::Bar),
309        "off" => Some(Location::Off),
310        _ => word
311            .strip_prefix('p')?
312            .parse::<u8>()
313            .ok()
314            .and_then(Point::new)
315            .map(Location::Point),
316    }
317}
318
319fn phase_name(phase: GamePhase) -> &'static str {
320    match phase {
321        GamePhase::OpeningRoll => "opening-roll",
322        GamePhase::PreRoll => "pre-roll",
323        GamePhase::CheckerPlay(_) => "checker-play",
324        GamePhase::GameOver(_) => "game-over",
325    }
326}
327
328fn player_json(player: Option<Player>) -> &'static str {
329    match player {
330        Some(Player::White) => "\"white\"",
331        Some(Player::Black) => "\"black\"",
332        None => "null",
333    }
334}
335
336fn result_json(phase: GamePhase) -> String {
337    let outcome = match phase {
338        GamePhase::GameOver(outcome) => outcome,
339        _ => return "null".to_owned(),
340    };
341    let mut json = String::new();
342    write!(
343        json,
344        "{{\"winner\":\"{}\",\"kind\":\"{}\"}}",
345        outcome.winner,
346        game_kind_name(outcome),
347    )
348    .expect("writing to a String cannot fail");
349    json
350}
351
352fn analysis_json(analysis: Option<&SearchReport>) -> String {
353    let Some(analysis) = analysis else {
354        return "null".to_owned();
355    };
356    let mut json = String::new();
357    json.push_str("{\"play\":[");
358    if let Some(play) = &analysis.best_play {
359        write_steps(&mut json, play.steps());
360    }
361    let outcomes = analysis.equity.outcomes();
362    write!(
363        json,
364        "],\"outcomes\":[{:.6},{:.6},{:.6},{:.6},{:.6},{:.6}],\"expectedPoints\":{:.6},\"depth\":{},\"nodes\":{},\"chanceNodes\":{},\"ttHits\":{},\"stopped\":{}}}",
365        outcomes[0],
366        outcomes[1],
367        outcomes[2],
368        outcomes[3],
369        outcomes[4],
370        outcomes[5],
371        analysis.equity.expected_points(),
372        analysis.depth,
373        analysis.nodes,
374        analysis.chance_nodes,
375        analysis.tt_hits,
376        analysis.stopped,
377    )
378    .expect("writing to a String cannot fail");
379    json
380}
381
382fn game_kind_name(outcome: GameOutcome) -> &'static str {
383    match outcome.kind {
384        GameKind::Single => "single",
385        GameKind::Gammon => "gammon",
386        GameKind::Backgammon => "backgammon",
387    }
388}
389
390fn write_dice(json: &mut String, dice: Option<[u8; 2]>) {
391    if let Some([first, second]) = dice {
392        write!(json, "[{first},{second}]").expect("writing to a String cannot fail");
393    } else {
394        json.push_str("null");
395    }
396}
397
398fn write_numbers(json: &mut String, numbers: &[u8]) {
399    for (index, number) in numbers.iter().enumerate() {
400        if index > 0 {
401            json.push(',');
402        }
403        write!(json, "{number}").expect("writing to a String cannot fail");
404    }
405}
406
407fn write_steps(json: &mut String, steps: &[Step]) {
408    for (index, step) in steps.iter().enumerate() {
409        if index > 0 {
410            json.push(',');
411        }
412        write_step(json, *step);
413    }
414}
415
416fn write_step(json: &mut String, step: Step) {
417    write!(
418        json,
419        "{{\"from\":\"{}\",\"to\":\"{}\",\"die\":{}}}",
420        location_name(step.from()),
421        location_name(step.to()),
422        step.die(),
423    )
424    .expect("writing to a String cannot fail");
425}
426
427fn location_name(location: Location) -> String {
428    match location {
429        Location::Bar => "bar".to_owned(),
430        Location::Point(point) => format!("p{}", point.number()),
431        Location::Off => "off".to_owned(),
432    }
433}
434
435fn error(message: &str) -> String {
436    format!("info string error {message}")
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    #[test]
444    fn opening_roll_and_checker_steps_follow_the_game() {
445        let mut engine = Engine::new();
446        assert!(engine.command("opening 4 4")[0].contains("tied"));
447        assert!(engine.snapshot_json().contains("\"openingTied\":true"));
448
449        assert!(engine.command("opening 6 1").is_empty());
450        assert!(
451            engine
452                .snapshot_json()
453                .contains("\"phase\":\"checker-play\"")
454        );
455        let play = engine.game.legal_plays()[0].clone();
456        for step in play.steps() {
457            let output = engine.command(&format!(
458                "step {} {} {}",
459                location_name(step.from()),
460                location_name(step.to()),
461                step.die(),
462            ));
463            assert!(output.is_empty());
464        }
465        assert_eq!(engine.game.phase(), GamePhase::PreRoll);
466        assert!(engine.turn.is_none());
467    }
468
469    #[test]
470    fn undo_only_changes_the_pending_checker_turn() {
471        let mut engine = Engine::new();
472        engine.command("opening 6 1");
473        let initial = engine.game.position();
474        let step = engine.turn.as_ref().unwrap().legal_steps()[0];
475        engine.command(&format!(
476            "step {} {} {}",
477            location_name(step.from()),
478            location_name(step.to()),
479            step.die(),
480        ));
481        assert_ne!(engine.turn.as_ref().unwrap().preview_position(), initial);
482        assert!(engine.command("undo").is_empty());
483        assert_eq!(engine.turn.as_ref().unwrap().preview_position(), initial);
484        assert!(!engine.command("undo")[0].is_empty());
485    }
486
487    #[test]
488    fn new_game_clears_an_active_turn_and_transient_state() {
489        let mut engine = Engine::new();
490        engine.command("opening 6 1");
491        engine.command("search beginner");
492        let step = engine.turn.as_ref().unwrap().legal_steps()[0];
493        engine.command(&format!(
494            "step {} {} {}",
495            location_name(step.from()),
496            location_name(step.to()),
497            step.die(),
498        ));
499
500        assert!(engine.command("newgame").is_empty());
501        assert_eq!(engine.game, Game::new());
502        assert!(engine.turn.is_none());
503        assert!(engine.last_roll.is_none());
504        assert!(engine.last_step.is_none());
505        assert!(engine.last_analysis.is_none());
506        assert!(
507            engine
508                .snapshot_json()
509                .contains("\"phase\":\"opening-roll\"")
510        );
511    }
512
513    #[test]
514    fn malformed_commands_do_not_change_state() {
515        let mut engine = Engine::new();
516        let before = engine.snapshot_json();
517        assert!(engine.command("opening 7 1")[0].starts_with("info string error"));
518        assert!(engine.command("roll 6 6")[0].starts_with("info string error"));
519        assert!(engine.command("step p24 p23 1")[0].starts_with("info string error"));
520        assert!(engine.command("newgame extra")[0].starts_with("info string error"));
521        assert_eq!(engine.snapshot_json(), before);
522    }
523
524    #[test]
525    fn search_reports_a_complete_legal_play_without_moving() {
526        let mut engine = Engine::new();
527        engine.command("opening 6 1");
528        let before = engine.game.position();
529        let output = engine.command("search medium");
530        let analysis = engine.last_analysis.as_ref().unwrap();
531        let play = analysis.best_play.as_ref().unwrap();
532
533        assert!(output[0].starts_with("info depth "));
534        assert!(output[1].starts_with("bestplay "));
535        assert!(before.legal_plays(Dice::new(6, 1).unwrap()).contains(play));
536        assert_eq!(engine.game.position(), before);
537        assert!(engine.snapshot_json().contains("\"analysis\":{\"play\":["));
538    }
539
540    #[test]
541    fn search_rejects_wrong_phases_presets_and_partial_turns_without_mutation() {
542        let mut engine = Engine::new();
543        let opening = engine.snapshot_json();
544        assert!(engine.command("search medium")[0].contains("requires a checker turn"));
545        assert!(engine.command("search bogus")[0].contains("unknown search preset"));
546        assert_eq!(engine.snapshot_json(), opening);
547
548        engine.command("opening 6 1");
549        let step = engine.turn.as_ref().unwrap().legal_steps()[0];
550        engine.command(&format!(
551            "step {} {} {}",
552            location_name(step.from()),
553            location_name(step.to()),
554            step.die(),
555        ));
556        let partial = engine.snapshot_json();
557        assert!(engine.command("search medium")[0].contains("start of a checker turn"));
558        assert_eq!(engine.snapshot_json(), partial);
559    }
560
561    #[test]
562    fn successful_state_changes_clear_stale_analysis() {
563        let mut engine = Engine::new();
564        engine.command("opening 6 1");
565        engine.command("search beginner");
566        assert!(engine.last_analysis.is_some());
567        let step = engine.turn.as_ref().unwrap().legal_steps()[0];
568        assert!(
569            engine
570                .command(&format!(
571                    "step {} {} {}",
572                    location_name(step.from()),
573                    location_name(step.to()),
574                    step.die(),
575                ))
576                .is_empty()
577        );
578        assert!(engine.last_analysis.is_none());
579        assert!(engine.snapshot_json().contains("\"analysis\":null"));
580    }
581
582    #[test]
583    fn analysis_json_contains_normalized_outcomes_and_search_counts() {
584        let mut engine = Engine::new();
585        engine.command("opening 3 1");
586        engine.command("search easy");
587        let snapshot = engine.snapshot_json();
588        assert!(snapshot.contains("\"outcomes\":["));
589        assert!(snapshot.contains("\"expectedPoints\":"));
590        assert!(snapshot.contains("\"depth\":1"));
591        assert!(snapshot.contains("\"nodes\":"));
592        assert!(snapshot.contains("\"chanceNodes\":"));
593        assert!(snapshot.contains("\"ttHits\":"));
594    }
595
596    #[test]
597    fn snapshot_contains_only_single_game_state() {
598        let snapshot = Engine::new().snapshot_json();
599
600        assert!(snapshot.contains("\"phase\":\"opening-roll\""));
601        assert!(snapshot.contains("\"sideToMove\":\"white\""));
602        assert!(snapshot.contains("\"result\":null"));
603    }
604
605    #[test]
606    fn completed_game_result_has_only_the_natural_outcome() {
607        let phase = GamePhase::GameOver(GameOutcome {
608            winner: Player::Black,
609            kind: GameKind::Backgammon,
610        });
611
612        assert_eq!(
613            result_json(phase),
614            "{\"winner\":\"black\",\"kind\":\"backgammon\"}",
615        );
616    }
617}