-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathState.cpp
More file actions
72 lines (62 loc) · 1.79 KB
/
State.cpp
File metadata and controls
72 lines (62 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// https://github.com/knickers/StateMachine
#include "State.h"
State::State() {
transitions = new LinkedList<struct Transition*>();
};
State::~State() {};
/*
* Adds a transition structure to the list of transitions
* for this state.
* Params:
* conditionFunction is the address of a function that will be evaluated
* to determine if the transition occurs
* state is the state to transition to
*/
void State::addTransition(bool (*conditionFunction)(), State* s) {
struct Transition* t = new Transition{conditionFunction,s->index};
transitions->add(t);
}
/*
* Adds a transition structure to the list of transitions
* for this state.
* Params:
* conditionFunction is the address of a function that will be evaluated
* to determine if the transition occurs
* stateNumber is the number of the state to transition to
*/
void State::addTransition(bool (*conditionFunction)(), int stateNumber) {
struct Transition* t = new Transition{conditionFunction,stateNumber};
transitions->add(t);
}
/*
* Evals all transitions sequentially until one of them is true.
* Returns:
* The stateNumber of the transition that evaluates to true
* -1 if none evaluate to true
*/
int State::evalTransitions() {
if (transitions->size() == 0) return -1;
for (int i=0; i<transitions->size(); i++) {
if (transitions->get(i)->conditionFunction()) {
return transitions->get(i)->stateNumber;
}
}
return -1;
}
/*
* Execute runs the stateLogic and then evaluates
* all available transitions. The transition that
* returns true is returned.
*/
int State::execute() {
stateLogic();
return evalTransitions();
}
/*
* Method to dynamically set a transition
*/
int State::setTransition(int index, int stateNo) {
if (transitions->size() == 0) return -1;
transitions->get(index)->stateNumber = stateNo;
return stateNo;
}