BWAPI Filters

From StarCraft AI, the resource for custom StarCraft Brood War AIs
Jump to: navigation, search

BWAPI 4 introduced a new feature: Filters.

UnitFilter is a new powerful function composition object and function predicate for use with getUnits_ functions throughout the interface (UnitInterface::getClosestUnit, UnitInterface::getUnitsInRadius). It can generally be combined with any other functional object (including lambdas) using operators && and ||, as well as ! for the inverse. (Example: !(IsFlyer || IsLifted) )

CompareFilter is a sister function composition object that compares the values returned from the call to the object, and can be combined using operators ==, <, <=, >, >=, and !=. (Example: GetType == UnitTypes::Terran_SCV && HP_Percent < 100)

Example of usage:

// Get main building closest to start location.
Unit pMain =Broodwar->getClosestUnit(Broodwar->self()->getStartLocation(), Filter::IsResourceDepot );
if ( pMain ) // check if pMain is valid
{
  // Get sets of resources and workers
 Unitset myResources = pMain->getUnitsInRadius(1024, Filter::IsMineralField);
  if ( !myResources.empty() ) // check if we have resources nearby
  {
   Unitset myWorkers = pMain->getUnitsInRadius(512, Filter::IsWorker && Filter::IsIdle && Filter::IsOwned );
    while ( !myWorkers.empty() ) // make sure we command all nearby idle workers, if any
    {
      for ( auto u = myResources.begin(); u != myResources.end() && !myWorkers.empty(); ++u )
      {
        myWorkers.back()->gather(*u);
        myWorkers.pop_back();
      }
    }
  } // myResources not empty
} // pMain != nullptr