Game Development Reference
In-Depth Information
if(ai.getCurrentState() != null &&
ai.getCurrentState().getClass() == state){
amount++;
}
}
return amount;
}
9. Comparing the current gathers with the required amount, we know whether to in-
crease or decrease the number of food gatherers. We then set the state to change
according to whether more or less food gatherers are required, as shown in the
following code:
int foodGatherers =
workersByState(GatherFoodState.class);
int toSet = requiredFoodGatherers - foodGatherers;
Class<? extends AIStateRTS> state = null;
if(toSet > 0){
state = GatherFoodState.class;
} else if (toSet < 0){
state = GatherWoodState.class;
toSet = -toSet;
}
10. We can create another method, called
setWorkerState
, that loops through
aiList
and calls
setCurrentState
of the first available worker. It reruns
true
if it has successfully set the state of a unit, as shown in the following code:
private boolean setWorkerState(Class<? extends
AIStateRTS> state){
for(AIControl_RTS ai: aiList){
if(ai.getCurrentState() == null ||
ai.getCurrentState().getClass() != state){
ai.setCurrentState(state);
((GatherResourceState)ai.getCurrentState()).setResource(resources.get(state));
return true;
}
}