Trait emergent::decision_makers::DecisionMaker
source · pub trait DecisionMaker<M = (), K = DefaultKey>: Send + Sync {
// Required methods
fn decide(&mut self, memory: &mut M) -> Option<K>;
fn change_mind(&mut self, id: Option<K>, memory: &mut M) -> bool;
}
Expand description
Iterface for all decision making engines.
Example
use emergent::prelude::*;
struct Switcher<M = ()> {
states: [Box<dyn Task<M>>; 2],
active_index: Option<usize>,
}
impl<M> DecisionMaker<M, usize> for Switcher<M> {
fn decide(&mut self, memory: &mut M) -> Option<usize> {
if let Some(index) = self.active_index {
self.states[index].on_exit(memory);
}
let index = self.active_index.map(|index| (index + 1) % 2).unwrap_or_default();
self.states[index].on_enter(memory);
self.active_index = Some(index);
self.active_index
}
fn change_mind(&mut self, id: Option<usize>, memory: &mut M) -> bool {
if id == self.active_index {
return false;
}
if let Some(index) = self.active_index {
self.states[index].on_exit(memory);
}
if let Some(index) = id {
self.states[index].on_enter(memory);
}
self.active_index = id;
true
}
}
let mut switcher = Switcher {
states: [
Box::new(NoTask::default()),
Box::new(NoTask::default()),
],
active_index: None,
};
assert_eq!(switcher.active_index, None);
assert_eq!(switcher.decide(&mut ()), Some(0));
assert_eq!(switcher.decide(&mut ()), Some(1));
assert_eq!(switcher.decide(&mut ()), Some(0));
assert!(switcher.change_mind(None, &mut ()));
assert_eq!(switcher.active_index, None);
Required Methods§
sourcefn decide(&mut self, memory: &mut M) -> Option<K>
fn decide(&mut self, memory: &mut M) -> Option<K>
Performs decision making and returns the key of the state it switched into.
sourcefn change_mind(&mut self, id: Option<K>, memory: &mut M) -> bool
fn change_mind(&mut self, id: Option<K>, memory: &mut M) -> bool
Force switch into state (Some
activates new state, None
deactivates current state).
Returns true if successfully changed into new state.