Skip to main content

hivetuilib_ai/
lib.rs

1const INTERNAL_ERROR: &str = "Internal error in AI algorithm!";
2
3type IndexType = u32;
4// used by rating algorithm
5pub type RatingType = i32;
6
7mod algorithm;
8mod engine_stepper;
9mod params;
10mod search_tree_state;
11
12pub mod rater;
13
14pub use algorithm::*;
15pub use params::*;
16
17#[cfg(test)]
18pub(crate) mod test {
19    use crate::{
20        rater::{DecisionType, Rater},
21        RateAndMap, RatingType,
22    };
23    use hivetuilib::{plain_decision::PlainDecision, GameData, RevEffect};
24
25    pub(crate) fn type_mapping(context: &ZeroOneContext) -> DecisionType {
26        match context {
27            ZeroOneContext::Flat | ZeroOneContext::ZeroAnd | ZeroOneContext::OneAnd => {
28                DecisionType::BottomLevel
29            }
30            ZeroOneContext::Base => DecisionType::HigherLevel,
31        }
32    }
33
34    /// A game where zeros and ones are counted and the state is represented by the sum of each.
35    #[derive(Debug, Clone)]
36    pub(crate) struct ZeroOneGame {
37        pub num_zeros: u32,
38        pub num_ones: u32,
39        pub use_high_level: bool,
40        pub player: usize,
41        pub finished_at: u32,
42    }
43
44    impl ZeroOneGame {
45        pub(crate) fn new(use_high_level: bool, finished_at: u32) -> Self {
46            Self {
47                num_zeros: 0,
48                num_ones: 0,
49                use_high_level,
50                player: 0,
51                finished_at,
52            }
53        }
54
55        fn update(&mut self) {
56            self.use_high_level = !self.use_high_level;
57            self.player = (self.player + 1) % 2;
58        }
59    }
60
61    fn chain<F, G, R>(f: F, g: G) -> impl Fn(&mut ZeroOneGame) -> R + Clone
62    where
63        F: Fn(&mut ZeroOneGame) -> R + Clone,
64        G: Fn(&mut ZeroOneGame) -> R + Clone,
65    {
66        move |data| {
67            f(data);
68            g(data)
69        }
70    }
71
72    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
73    pub(crate) enum ZeroOneContext {
74        Flat,
75        Base,
76        ZeroAnd,
77        OneAnd,
78    }
79
80    impl GameData for ZeroOneGame {
81        type Context = ZeroOneContext;
82        type EffectType = dyn RevEffect<Self>;
83
84        fn next_decision(&self) -> Option<Box<dyn hivetuilib::Decision<Self>>> {
85            if self.num_zeros + self.num_ones >= self.finished_at {
86                return None;
87            }
88
89            let player = self.player;
90            let apply_zero = |data: &mut ZeroOneGame| {
91                data.num_zeros += 1;
92                None
93            };
94            let undo_zero = |data: &mut ZeroOneGame| {
95                data.num_zeros -= 1;
96            };
97            let apply_one = |data: &mut ZeroOneGame| {
98                data.num_ones += 1;
99                None
100            };
101            let undo_one = |data: &mut ZeroOneGame| {
102                data.num_ones -= 1;
103            };
104            let apply_update = |data: &mut ZeroOneGame| {
105                data.update();
106                None
107            };
108            let update = |data: &mut ZeroOneGame| {
109                data.update();
110            };
111
112            if self.use_high_level {
113                let mut dec = PlainDecision::with_context(player, ZeroOneContext::Base);
114                dec.add_follow_up(move |_| {
115                    let mut zero_dec = PlainDecision::with_context(player, ZeroOneContext::ZeroAnd);
116                    zero_dec.add_rev_effect(
117                        chain(chain(apply_zero, apply_zero), apply_update),
118                        chain(chain(undo_zero, undo_zero), update),
119                    );
120                    zero_dec.add_rev_effect(
121                        chain(chain(apply_zero, apply_one), apply_update),
122                        chain(chain(undo_one, undo_zero), update),
123                    );
124                    zero_dec
125                });
126                dec.add_follow_up(move |_| {
127                    let mut one_dec = PlainDecision::with_context(player, ZeroOneContext::OneAnd);
128                    one_dec.add_rev_effect(
129                        chain(chain(apply_one, apply_zero), apply_update),
130                        chain(chain(undo_one, undo_zero), update),
131                    );
132                    one_dec.add_rev_effect(
133                        chain(chain(apply_one, apply_one), apply_update),
134                        chain(chain(undo_one, undo_one), update),
135                    );
136                    one_dec
137                });
138                Some(Box::new(dec))
139            } else {
140                let mut dec = PlainDecision::with_context(player, ZeroOneContext::Flat);
141                dec.add_rev_effect(chain(apply_zero, apply_update), chain(undo_zero, update));
142                dec.add_rev_effect(chain(apply_one, apply_update), chain(undo_one, update));
143                Some(Box::new(dec))
144            }
145        }
146    }
147
148    #[derive(Debug, Clone, Copy)]
149    pub(crate) struct RateAndMapZeroOne;
150
151    impl RateAndMap<ZeroOneGame> for RateAndMapZeroOne {
152        fn apply_type_mapping(&self, context: &ZeroOneContext) -> DecisionType {
153            type_mapping(context)
154        }
155
156        fn rate_moves(
157            &self,
158            rater: &mut Rater,
159            context: &[ZeroOneContext],
160            data: &ZeroOneGame,
161            _old_context: &[(ZeroOneContext, usize)],
162        ) {
163            for (i, c) in context.iter().enumerate() {
164                match c {
165                    ZeroOneContext::Flat => {
166                        if data.player == 0 {
167                            rater.rate(i, 0, 1);
168                            rater.rate(i, 1, 0);
169                        } else {
170                            rater.rate(i, 0, 0);
171                            rater.rate(i, 1, 1);
172                        }
173                    }
174                    ZeroOneContext::ZeroAnd => {
175                        if data.player == 0 {
176                            rater.rate(i, 0, 2);
177                            rater.rate(i, 1, 0);
178                        } else {
179                            rater.rate(i, 0, -2);
180                            rater.rate(i, 1, 0);
181                        }
182                    }
183                    ZeroOneContext::OneAnd => {
184                        if data.player == 0 {
185                            rater.rate(i, 0, 0);
186                            rater.rate(i, 1, -2);
187                        } else {
188                            rater.rate(i, 0, 0);
189                            rater.rate(i, 1, 2);
190                        }
191                    }
192                    ZeroOneContext::Base => unreachable!(),
193                }
194            }
195        }
196
197        fn rate_game_state(
198            &self,
199            data: &ZeroOneGame,
200            _old_context: &[(ZeroOneContext, usize)],
201            player: usize,
202        ) -> RatingType {
203            let mut diff = data.num_ones as i32 - data.num_zeros as i32;
204            if player == 0 {
205                diff = -diff;
206            }
207            diff * diff.abs()
208        }
209    }
210}