SimpleAI
 All Classes Namespaces Files Functions Variables Typedefs Macros Groups Pages
ProbabilitySelector.h
Go to the documentation of this file.
1 
4 #pragma once
5 
6 #include "tree/Selector.h"
7 #include <vector>
8 #include "AI.h"
9 #include "common/String.h"
10 #include "common/Random.h"
11 
12 namespace ai {
13 
21 protected:
22  std::vector<float> _weights;
23  float _weightSum;
24 public:
25  ProbabilitySelector(const std::string& name, const std::string& parameters, const ConditionPtr& condition) :
26  Selector(name, parameters, condition), _weightSum(0.0f) {
27  std::vector<std::string> tokens;
28  Str::splitString(parameters, tokens, ",");
29  const int weightAmount = static_cast<int>(tokens.size());
30  for (int i = 0; i < weightAmount; i++) {
31  const float weight = Str::strToFloat(tokens[i]);
32  _weightSum += weight;
33  _weights[i] = weight;
34  }
35  }
36 
37  virtual ~ProbabilitySelector() {
38  }
39 
41 
42  TreeNodeStatus execute(const AIPtr& entity, int64_t deltaMillis) override {
43  if (Selector::execute(entity, deltaMillis) == CANNOTEXECUTE)
44  return CANNOTEXECUTE;
45 
46  int index = getSelectorState(entity);
47  if (index == AI_NOTHING_SELECTED) {
48  float rndIndex = ai::randomf(_weightSum);
49  const int weightAmount = static_cast<int>(_weights.size());
50  for (; index < weightAmount; ++index) {
51  if (rndIndex < _weights[index])
52  break;
53  rndIndex -= _weights[index];
54  }
55  }
56 
57  const TreeNodePtr& child = _children[index];
58  const TreeNodeStatus result = child->execute(entity, deltaMillis);
59  if (result == RUNNING) {
60  setSelectorState(entity, index);
61  } else {
62  setSelectorState(entity, AI_NOTHING_SELECTED);
63  }
64  child->resetState(entity);
65 
66  const int size = static_cast<int>(_children.size());
67  for (int i = 0; i < size; ++i) {
68  if (i == index)
69  continue;
70  _children[i]->resetState(entity);
71  }
72  return state(entity, result);
73  }
74 };
75 
76 }
virtual TreeNodeStatus execute(const AIPtr &entity, int64_t deltaMillis)
Definition: TreeNodeImpl.h:184
Base class for all type of TreeNode selectors.
Definition: Selector.h:25
This node executes one of the attached children randomly based on the given weights. The node is executed until it is no longer in the running state.
Definition: ProbabilitySelector.h:20
#define NODE_FACTORY(NodeName)
A node factory macro to ease and unify the registration at AIRegistry.
Definition: TreeNode.h:54
TreeNodeStatus execute(const AIPtr &entity, int64_t deltaMillis) override
Definition: ProbabilitySelector.h:42