goap_ai/
model.rs

1use std::collections::HashMap;
2
3use crate::{Action, Goal, State};
4
5#[derive(Debug, Clone)]
6pub struct Model {
7    pub time: i32,
8    pub state: State,
9    pub goals: HashMap<String, Goal>,
10    pub action_history: Vec<(String, Action)>,
11}
12
13impl Model {
14    /// Create a new model with the given state and goals.
15    pub fn new(state: State, goals: HashMap<String, Goal>) -> Self {
16        Self {
17            time: 0,
18            state,
19            goals,
20            action_history: vec![],
21        }
22    }
23
24    pub fn apply(&self, label: String, action: &Action) -> Option<Self> {
25        if let Some(next_state) = self.state.apply(action) {
26            let mut updated_action_history = self.action_history.clone();
27            updated_action_history.push((label, action.clone()));
28            Some(Self {
29                time: self.time + action.duration,
30                state: next_state,
31                goals: self.goals.clone(),
32                action_history: updated_action_history,
33            })
34        } else {
35            None
36        }
37    }
38
39    pub fn calculate_discontentment(&self) -> f32 {
40        let mut total_discontentment = 0.0;
41        for (name, goal) in self.goals.iter() {
42            let current_value = *self.state.get(name).unwrap_or(&0);
43            let discontentment = goal.discontentment(current_value);
44            total_discontentment += discontentment;
45        }
46        total_discontentment
47    }
48}