Skip to main content

beetry_core/leaf/
condition.rs

1use crate::{Node, TickStatus};
2
3pub trait Behavior {
4    /// Evaluate the condition for the current tick.
5    ///
6    /// Returning `true` maps to [`TickStatus::Success`] and `false` maps to
7    /// [`TickStatus::Failure`] in [`Condition`].
8    fn cond(&mut self) -> bool;
9
10    /// Reset any condition-local state for a fresh run.
11    fn reset(&mut self) {}
12}
13
14pub type BoxBehavior = Box<dyn Behavior>;
15impl Behavior for BoxBehavior {
16    fn cond(&mut self) -> bool {
17        (**self).cond()
18    }
19    fn reset(&mut self) {
20        (**self).reset();
21    }
22}
23
24/// Synchronous leaf node backed by a [`Behavior`] implementation.
25pub struct Condition<B>
26where
27    B: Behavior,
28{
29    behavior: B,
30}
31
32impl<B> Condition<B>
33where
34    B: Behavior,
35{
36    pub fn new(behavior: B) -> Self {
37        Self { behavior }
38    }
39}
40
41impl<B> Node for Condition<B>
42where
43    B: Behavior,
44{
45    fn tick(&mut self) -> TickStatus {
46        if self.behavior.cond() {
47            TickStatus::Success
48        } else {
49            TickStatus::Failure
50        }
51    }
52    fn reset(&mut self) {
53        self.behavior.reset();
54    }
55}