Original Post
As you might already know, I''m very sceptical about the use of OOP (mostly because of my personal experience). However, I''m still interested in it''s capabilities. And since I prefer to see the real code instead of theoretical arguments, here is my question - how would you solve the following problem using OOP?
It''s a real-life problem, which I encountered in my current project. I''m trying to create a tactical AI for spaceships in a 2D shooter, which determines the best action (like turning and controlling thrust) by searching the trajectory tree (that is, all possible trajectories). I''m doing it using recursion and to decrease the number of examined trajectories I use a state machine.
The pseidocode for the algorithm is something like this:
For example, the initial state is FORWARD1, from which we can get into states FORWARD1 (that is, stay in this state) and TURN_LEFT, from TURN_LEFT we can get into states TURN_LEFT (keep turning) and FORWARD2, and from state FORWARD2 we can get only into state FORWARD2. Interestingly enough, this turns the time complexity of the algorithm from exponential into polinomial (at the expense of stupid trajectories like TURN_LEFT - TURN_RIGHT - TURN_LEFT - TURN_RIGHT - that is, turning into opposite directions each frame).
However, what I''m interested in is how would you create the state machine used by this algorithm (and not the algorithm itself) using OOP. Using procedural programming it''s trivial, but ugly, and I''m wondering whether there is some simple and elegant OOP solution. Probably that would be something like
but what goes in these classes? Is there a separate class for each state? Or maybe the design must be different?
// we don''t do actual trajectory calculation here, state_t represents only
// state of the algorithm, not some game object, and is used only to
// select the next state
void expand_state(state_t state, int recursion_level)
{
recursion_level++;
// we need to stop somewhere
if(recursion_level < max_recursion_level)
{
// to how many states we can get from this state
int n = get_num_next_states(state);
int i;
for(i = 0; i < n; i++)
{
// recursive function call for all such states
expand_state(get_next_state(state, i), recursion_level);
}
}
}
class State
{
public:
StateCollection GetNextStates();
};
class StateCollection
{
public:
int Count();
State GetState(int i);
};