Research Article

Artificial Intelligence in Video Games: Towards a Unified Framework

Algorithm 19

Conceptual view code in the onFrame callback function. The RegisterDMController creates a CptBot, which uses the Graven targeting AI to attack enemies, and adds it to the list of controllers of the CptMvAgent2D.
void  GravenAIModule::onFrame()
{
 //For each unit visible to the player
Unitset units = Broodwar->getAllUnits();
for  (Unitset::iterator u = units.begin(); u != units.end(); ++u)
{
  //Ignore neutral units which include mineral fields and critters
  if  (u->getPlayer()->isNeutral())
   continue;
  //Get the projection of the unit in CDS
CptMvAgent2D  cptUnit =  dynamic_cast <CptMvAgent2D>(cptEntityMgr->GetEntityFromID
(u->getID()));
  //Projection found, synchronize state and update controllers
  if  (cptUnit)
{
syncUnit(cptUnit,  u);
cptUnit->Update();
}
  //Projection not found, create one
  else if  (u->exists() && u->isCompleted())
{
cptUnit =  new  CptMvAgent2D(cptWorld);
syncUnit(cptUnit,  u);
cptWorld->pAddBot(cptUnit);
cptEntityMgr->RegisterEntity(cptUnit);
   //If the unit can attack, register the targeting AI
   if  (u->getPlayer() == Broodwar->self() && u->canAttack())
{
RegisterDMController(cptUnit);
}
}
}
 //Remove projections of units that no longer exist in the game
std::list<CptMvAgent2D> cptUnits = cptWorld->GetAllBots();
for  (std::list<CptMvAgent2D>::iterator c = cptUnits.begin(); c != cptUnits.end(); ++c)
{
  if  (!Broodwar->getUnit((c)->ID())    !Broodwar->getUnit((c)->ID())->exists())
{
cptEntityMgr->RemoveEntity(c);
cptWorld->pRemoveBot((c)->ID());
}
}
}