void buildGateway(){
	resourceSemaphore = true;
	Unidade* worker = Protoss_Workers[numWorkers-1];
	Selected_Worker = worker;
	Unidade* Selected_Pylon = Protoss_Pylons[numPylons-1];
	Unidade* nexus = Protoss_Nexus;
	int delta_y;
	int delta_x;
	int desviox=0;
	int desvioy=0;
	delta_y	=	nexus->getPosition().y() - Selected_Pylon->getPosition().y();
	delta_x =	nexus->getPosition().x() - Selected_Pylon->getPosition().x();
	BWAPI::Position setPos = BWAPI::Position(Selected_Pylon->getPosition().x()-delta_x*3/2,Selected_Pylon->getPosition().y()-delta_y*3/2);
	worker->build(BWAPI::TilePosition(setPos),UnitTypes::Protoss_Gateway);
	while(!worker->isConstructing())
	{
		desviox += 5*(rand()%3-1);
		desvioy += 5*(rand()%3-1);
		setPos = BWAPI::Position(Selected_Pylon->getPosition().x()-delta_x*3/2+desviox,Selected_Pylon->getPosition().y()-delta_y*3/2+desvioy);
		worker->build(BWAPI::TilePosition(setPos),UnitTypes::Protoss_Gateway);
	}
	printf("X:%d Y:%d \n",setPos.x(),setPos.y());
	Selected_Worker = NULL;
	resourceSemaphore = false;
}
Ejemplo n.º 2
0
	// given a position, get the position we should move to to minimize distance
	BWAPI::Position getMoveTo(const BWAPI::Position p, const int lookAhead = 1) const
	{
		// the initial row an column
		int row = p.y() / 32;
		int col = p.x() / 32;
		
		// for each lookahead
		for (int i=0; i<lookAhead; ++i)
		{
			// get the index
			int index = getIndex(row,col);

			// adjust the row and column accordingly
			if (moveTo[index] == 'L')
			{
				col -= 1;
			} 
			else if (moveTo[index] == 'R')
			{
				col += 1;
			} 
			else if (moveTo[index] == 'U')
			{
				row -= 1;
			} 
			else
			{
				row += 1;
			}
		}

		// return the position
		return BWAPI::Position(col * 32 + 16, row * 32 + 16);
	}
Ejemplo n.º 3
0
void StarCraftAIModule::onNukeDetect(BWAPI::Position target)
{
	if (target!=Positions::Unknown)
		Broodwar->printf("Nuclear Launch Detected at (%d,%d)",target.x(),target.y());
	else
		Broodwar->printf("Nuclear Launch Detected");
}
Ejemplo n.º 4
0
void BattleBroodAI::onNukeDetect(BWAPI::Position target)
{
	micro->onNukeDetect(target);
    if (target!=Positions::Unknown)
    	Broodwar->printf("Nuclear Launch Detected at (%d,%d)",target.x(),target.y());
    else
    	Broodwar->printf("Nuclear Launch Detected");
}
Ejemplo n.º 5
0
	bool operator()(const BWAPI::Position lhs, const BWAPI::Position rhs)
	{
		if (lhs.getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition()) <
			rhs.getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition())) return true;
		//ensure each position gets added to the set
		if (lhs.getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition()) >
			rhs.getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition())) return false;
		return true;
	}
Ejemplo n.º 6
0
void UnitMng::move()
{
	BWAPI::Position* currentPosition= new BWAPI::Position((this->conUnit)->getPosition());
	BWAPI::Position *movePosition;
	int updown=128*(outputs[3]-0.5);
	int leftright=128*(outputs[4]-0.5);
	movePosition= new BWAPI::Position((currentPosition->x() + updown),(currentPosition->y()+leftright));
	movePosition->makeValid();
	this->conUnit->move(*movePosition);
}
Ejemplo n.º 7
0
 void calculate_walk_distances_area(const BWAPI::Position& start
                                    , int width
                                    , int height
                                    , int max_distance
                                    , RectangleArray<int>& distance_map)
 {
     Heap<BWAPI::Position, int> heap(true);
     for (unsigned int x = 0;x < distance_map.getWidth();x++) {
         for (unsigned int y = 0;y < distance_map.getHeight();y++) {
             distance_map[x][y] = -1;
         }
     }
     int sx = (int)start.x();
     int sy = (int)start.y();
     for (int x = sx;x < sx + width;x++) {
         for (int y = sy;y < sy + height;y++) {
             heap.push(std::make_pair(BWAPI::Position(x, y), 0));
             distance_map[x][y] = 0;
         }
     }
     while (!heap.empty()) {
         BWAPI::Position pos = heap.top().first;
         int distance = heap.top().second;
         heap.pop();
         int x = (int)pos.x();
         int y = (int)pos.y();
         if (distance > max_distance && max_distance > 0)
             break;
         int min_x = max(x - 1, 0);
         int max_x = min(x + 1, BWAPI::Broodwar->mapWidth() * 4 - 1);
         int min_y = max(y - 1, 0);
         int max_y = min(y + 1, BWAPI::Broodwar->mapHeight() * 4 - 1);
         for (int ix = min_x;ix <= max_x;ix++) {
             for (int iy = min_y;iy <= max_y;iy++) {
                 int f = abs(ix - x) * 10 + abs(iy - y) * 10;
                 if (f > 10) {
                     f = 14;
                 }
                 int v = distance + f;
                 if (distance_map[ix][iy] > v) {
                     heap.set(BWAPI::Position(x, y), v);
                     distance_map[ix][iy] = v;
                 } else {
                     if (distance_map[ix][iy] == -1 && MapData::rawWalkability[ix][iy] == true) {
                         distance_map[ix][iy] = v;
                         heap.push(std::make_pair(BWAPI::Position(ix, iy), v));
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 8
0
 void calculate_walk_distances(const RectangleArray<bool>& read_map
                               , const BWAPI::Position& start
                               , int max_distance
                               , RectangleArray<int>& distance_map)
 {
     Heap<BWAPI::Position, int> heap(true);
     for (unsigned int x = 0;x < distance_map.getWidth();x++) {
         for (unsigned int y = 0;y < distance_map.getHeight();y++) {
             distance_map[x][y] = -1;
         }
     }
     heap.push(std::make_pair(start, 0));
     int sx = (int)start.x();
     int sy = (int)start.y();
     distance_map[sx][sy] = 0;
     while (!heap.empty()) {
         BWAPI::Position pos = heap.top().first;
         int distance = heap.top().second;
         heap.pop();
         int x = (int)pos.x();
         int y = (int)pos.y();
         if (distance > max_distance && max_distance > 0)
             break;
         int min_x = max(x - 1, 0);
         int max_x = min(x + 1, read_map.getWidth() - 1);
         int min_y = max(y - 1, 0);
         int max_y = min(y + 1, read_map.getHeight() - 1);
         for (int ix = min_x;ix <= max_x;ix++) {
             for (int iy = min_y;iy <= max_y;iy++) {
                 int f = abs(ix - x) * 10 + abs(iy - y) * 10;
                 if (f > 10) {
                     f = 14;
                 }
                 int v = distance + f;
                 if (distance_map[ix][iy] > v) {
                     heap.set(BWAPI::Position(x, y), v);
                     distance_map[ix][iy] = v;
                 } else {
                     if (distance_map[ix][iy] == -1 && read_map[ix][iy] == true) {
                         distance_map[ix][iy] = v;
                         heap.push(std::make_pair(BWAPI::Position(ix, iy), v));
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 9
0
void PlayerSquad::printGraphicDebugInfo() const {
	// Skip if not turned on
	if (config::debug::GRAPHICS_VERBOSITY == config::debug::GraphicsVerbosity_Off || !isDebugOn())
	{
		return;
	}

	// Low
	// Print id, state, number of units and number of supplies.
	if (config::debug::GRAPHICS_VERBOSITY >= config::debug::GraphicsVerbosity_Low) {
		if (!mCenter.empty()) {
			BWAPI::Position squadCenterOnMap = BWAPI::Position(mCenter.front());

			BWAPI::Broodwar->drawTextMap(squadCenterOnMap.x(), squadCenterOnMap.y(), "%s", getDebugString().c_str());
		}
	}


	// Medium
	// Draw line from the front and back center, display the length of this line
	if (config::debug::GRAPHICS_VERBOSITY >= config::debug::GraphicsVerbosity_Medium) {
		if (!mCenter.empty()) {
			pair<Position, Position> squadMovement = make_pair(mCenter.front(), mCenter.back());

			// Length
			double length = (mCenter.front() - mCenter.back()).getLength();

			// Draw line
			Broodwar->drawLineMap(
				squadMovement.first.x(), squadMovement.first.y(),
				squadMovement.second.x(), squadMovement.second.y(),
				Colors::Purple
				);

			int xOffset = -64;

			// Draw text in back of line
			Broodwar->drawTextMap(
				squadMovement.second.x() + xOffset, squadMovement.second.y(),
				"%sLength: %g",
				TextColors::PURPLE.c_str(),
				length
				);

		}
	}
}
Ejemplo n.º 10
0
void Fireteam::moveFormation(BWAPI::Position pos) {
	mission.objectivePosition = pos;
	for(std::set<BWAPI::Unit*>::const_iterator i=units.begin(); i != units.end(); i++)
	{	
		
		(*i)->move(BWAPI::Position::Position(pos.x() + (int)formation.positionMap[(*i)].xOffset, pos.y() + (int)formation.positionMap[(*i)].yOffset), 0);
	}
}
Ejemplo n.º 11
0
	void AIModule::camera()
	{
		if (game->getMouseState(BWAPI::M_LEFT))
		{
			return;
		}

		const int CENTER_SCREEN_X = 320;
		const int CENTER_SCREEN_Y = 140;

		if (!autocam)
		{
			return;
		}

		UnitGroup interestingUnits = AllUnits()(isAttacking);

		if (interestingUnits.size() == 0)
		{
			return;
		}

		BWAPI::Unit *unit = (*interestingUnits.begin());

		BWAPI::Position unitPosition = unit->getPosition();

		int x, y;
		x = unitPosition.x() - CENTER_SCREEN_X;
		y = unitPosition.y() - CENTER_SCREEN_Y;

		if (x < 0)
		{
			x = 0;
		}

		if (y < 0)
		{
			y = 0;
		}

		BWAPI::Broodwar->setScreenPosition(x, y);
	}
BWAPI::Position getSectorCornerPosition (char s, int c){
	int width = centro.x()*2;
	int height = centro.y()*2;

	double C1 = width / 3;
	double C2 = (2*width) / 3;

	double L1 = height / 3;
	double L2 = (2*height) / 3;

	double halfSectorWidth = (C1 / 2);
	double halfSectorHeight = (L1 / 2);

	BWAPI::Position sectorCenter = getSectorCenter(s);

	if(c == 0) return BWAPI::Position((int) (sectorCenter.x() - halfSectorWidth), (int) (sectorCenter.y() - halfSectorHeight));
	if(c == 1) return BWAPI::Position((int) (sectorCenter.x() + halfSectorWidth), (int) (sectorCenter.y() - halfSectorHeight));
	if(c == 2) return BWAPI::Position((int) (sectorCenter.x() - halfSectorWidth), (int) (sectorCenter.y() + halfSectorHeight));
	if(c == 3) return BWAPI::Position((int) (sectorCenter.x() + halfSectorWidth), (int) (sectorCenter.y() + halfSectorHeight));
}
Ejemplo n.º 13
0
void ProductionManager::RushDefend(BWAPI::UnitType defendBuilding, int buildingCount, BWAPI::UnitType defendUnit, int unitCount)
{
	BWAPI::Position chokePosition = BWTA::getNearestChokepoint(BWAPI::Broodwar->self()->getStartLocation())->getCenter();
	BWAPI::Position basePositon = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());

	double2 direc = chokePosition - basePositon;
	double2 direcNormal = direc / direc.len();
	int targetx = (basePositon.x() + int(direcNormal.x * 32 * 10)) / 32;
	int targety = (basePositon.y() + int(direcNormal.y * 32 * 10)) / 32;

	for (int i = 0; i < unitCount; i++)
	{
		queue.queueAsHighestPriority(defendUnit, false);
	}

	for (int i = 0; i < buildingCount; i++)
	{
		queue.queueAsHighestPriority(MetaType(BWAPI::UnitTypes::Zerg_Creep_Colony, BWAPI::TilePosition(targetx, targety)), true);
		queue.queueAsHighestPriority(defendBuilding, false);
	}
}
Ejemplo n.º 14
0
	void AIModule::onSendText(std::string text)
	{
		game->printf(text.c_str());

		if (text == "dbg")
		{
			debug = !debug;

			buildOrderManager->setDebugMode(debug);

			game->printf("Debug turned %s.", (debug) ? "on" : "off");
		}

		if (text == "atc")
		{
			autocam = !autocam;

			game->printf("Autocam turned %s.", (autocam) ? "on" : "off");
		}

		if (text == "gsn")
		{
			localSpeed = 30;
			frameSkip = 0;

			updateGameSpeed();
		}

		if (text == "gsf")
		{
			localSpeed = 0;
			frameSkip = 0;

			updateGameSpeed();
		}

		if (text == "gsfs")
		{
			localSpeed = 0;
			frameSkip = 8;

			updateGameSpeed();
		}

		if (text == "atk")
		{
			BWAPI::Position mousePosition = game->getMousePosition();
			BWAPI::Position screenPosition = game->getScreenPosition();

			BWAPI::Position mapPosition = BWAPI::Position(mousePosition.x() + screenPosition.x(), mousePosition.y() + screenPosition.y());
			agentManager->attackMoveTo(mapPosition);

			game->printf("Issued manual attack at %d %d.", mapPosition.x(), mapPosition.y());
		}
	}
Ejemplo n.º 15
0
void ExampleAIModule::onNukeDetect(BWAPI::Position target)
{

  // Check if the target is a valid position
  if ( target )
  {

    // if so, print the location of the nuclear strike target
    Broodwar->printf("Nuclear Launch Detected at (%d,%d)", target.x(), target.y() );

  }
  else 
  {

    // Otherwise, ask other players where the nuke is!
    Broodwar->sendText("Where's the nuke?");

  }

  // You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!

}
BWAPI::Position getSectorCenter (char s){

	/*
		Dividindo o mapa em 9 setores:

			   (C1)   (C2)
			  A  |  B  |  C  
			----------------- (L1)
			  K  |  L  |  M  
			----------------- (L2)
			  X  |  Y  |  Z  

		A funcao recebe um setor e retorna o ponto central do setor
	*/

	int width = centro.x()*2;
	int height = centro.y()*2;

	double C1 = width / 3;
	double C2 = (2*width) / 3;

	double L1 = height / 3;
	double L2 = (2*height) / 3;

	double halfSectorWidth = (C1 / 2);
	double halfSectorHeight = (L1 / 2);

	if(s == 'A') return BWAPI::Position((int) halfSectorWidth, (int) halfSectorHeight);
	if(s == 'B') return BWAPI::Position((int) (C1 + halfSectorWidth), (int) halfSectorHeight);
	if(s == 'C') return BWAPI::Position((int) (C2 + halfSectorWidth), (int) halfSectorHeight);
	if(s == 'K') return BWAPI::Position((int) halfSectorWidth, (int) (L1 + halfSectorHeight));
	if(s == 'L') return BWAPI::Position((int) (C1 + halfSectorWidth), (int) (L1 + halfSectorHeight));
	if(s == 'M') return BWAPI::Position((int) (C2 + halfSectorWidth), (int) (L1 + halfSectorHeight));
	if(s == 'X') return BWAPI::Position((int) halfSectorWidth, (int) (L2 + halfSectorHeight));
	if(s == 'Y') return BWAPI::Position((int) (C1 + halfSectorWidth), (int) (L2 + halfSectorHeight));
	if(s == 'Z') return BWAPI::Position((int) (C2 + halfSectorWidth), (int) (L2 + halfSectorHeight));
}
Ejemplo n.º 17
0
// sets the starting states based on the combat units within a radius of a given position
// this center will most likely be the position of the forwardmost combat unit we control
void CombatSimulation::setCombatUnits(const BWAPI::Position & center, const int radius)
{
	MicroSearch::GameState s;
	s.setMaxUnits(100);

	BWAPI::Broodwar->drawCircleMap(center.x(), center.y(), 10, BWAPI::Colors::Red, true);

	std::vector<BWAPI::Unit *> ourCombatUnits;
	std::vector<UnitInfo> enemyCombatUnits;
	MapGrid::Instance().GetUnits(ourCombatUnits,   center, Options::Micro::COMBAT_REGROUP_RADIUS, true, false);
	InformationManager::Instance().getNearbyForce(enemyCombatUnits, center, BWAPI::Broodwar->enemy(), Options::Micro::COMBAT_REGROUP_RADIUS);


	int y = 0;

	BOOST_FOREACH (BWAPI::Unit * unit, ourCombatUnits)
	{
		if (InformationManager::Instance().isCombatUnit(unit->getType()))
		{
			s.addUnit(MicroSearch::Unit(unit, getPlayer(BWAPI::Broodwar->self()), BWAPI::Broodwar->getFrameCount()));
		}
	}

	y++;

	BOOST_FOREACH (UnitInfo ui, enemyCombatUnits)
	{
		if (!ui.type.isFlyer())
		{
			s.addUnit(getUnit(ui, getPlayer(BWAPI::Broodwar->enemy())));
		}
	}

	s.finishedMoving();

	state = s;
}
Ejemplo n.º 18
0
void Micro::SmartMove(BWAPI::UnitInterface* attacker, const BWAPI::Position & targetPosition)
{
    UAB_ASSERT(attacker, "SmartAttackMove: Attacker not valid");
    UAB_ASSERT(targetPosition.isValid(), "SmartAttackMove: targetPosition not valid");

    if (!attacker || !targetPosition.isValid())
    {
        return;
    }

    // if we have issued a command to this unit already this frame, ignore this one
    if (attacker->getLastCommandFrame() >= BWAPI::Broodwar->getFrameCount() || attacker->isAttackFrame())
    {
        return;
    }

    // get the unit's current command
    BWAPI::UnitCommand currentCommand(attacker->getLastCommand());

    // if we've already told this unit to move to this position, ignore this command
    if ((currentCommand.getType() == BWAPI::UnitCommandTypes::Move) && (currentCommand.getTargetPosition() == targetPosition) && attacker->isMoving())
    {
        return;
    }

    // if nothing prevents it, attack the target
    attacker->move(targetPosition);
    TotalCommands++;

    if (Config::Debug::DrawUnitTargetInfo) 
    {
        BWAPI::Broodwar->drawCircleMap(attacker->getPosition(), dotRadius, BWAPI::Colors::White, true);
        BWAPI::Broodwar->drawCircleMap(targetPosition, dotRadius, BWAPI::Colors::White, true);
        BWAPI::Broodwar->drawLineMap(attacker->getPosition(), targetPosition, BWAPI::Colors::White);
    }
}
BWAPI::Position nextSpiralPosition (Unidade* u, BWAPI::Position center){
	/*
		Faz o batedor andar em expiral, em torno da primeira unidade encontrada.

		Para cada volta, divide a circunferencia em quatro setores que serao para onde
		o batedor ira se mover. Se no final de uma volta, nao encontrar o centro de comando
		inicia mais uma volta porem dessa vez, com o raio maior em spiralRadiusDelta
	*/

	int spiralRadius = (spiralTurn*spiralRadiusDelta);

	if(distance(u->getPosition(), nextSpiralSectorPosition) > spiralGoalRadius){
		if(distance(u->getPosition(), nextSpiralSectorPosition) >= lastDistanceToNextSpiralSector){
			nextSpiralSectorReachTryAmount = nextSpiralSectorReachTryAmount + 1;
		}

		if(nextSpiralSectorReachTryAmount >= maxAmountTryReachSpiralGoalRadius){
			spiralSector = spiralSector + 1;
			nextSpiralSectorReachTryAmount = 0;
		}
	}else{
		nextSpiralSectorReachTryAmount = 0;
		spiralSector = spiralSector + 1;
	}

	if(spiralSector == 0){
		nextSpiralSectorPosition = BWAPI::Position(center.x(), (center.y() - spiralRadius));
	}else if(spiralSector == 1){
		nextSpiralSectorPosition = BWAPI::Position((center.x() + spiralRadius), center.y());
	}else if(spiralSector == 2){
		nextSpiralSectorPosition = BWAPI::Position(center.x(), (center.y() + spiralRadius));
	}else if(spiralSector == 3){
		nextSpiralSectorPosition = BWAPI::Position((center.x() - spiralRadius), center.y());

		// fim da volta. Incrementa a volta e reinicia o sector
		spiralTurn = spiralTurn + 1;
		spiralSector = -1;
	}

	return nextSpiralSectorPosition;
}
char getSector (BWAPI::Position p){
	/*
		Dividindo o mapa em 9 setores:

			   (C1)   (C2)
			  A  |  B  |  C  
			----------------- (L1)
			  K  |  L  |  M  
			----------------- (L2)
			  X  |  Y  |  Z  

		A funcao recebe uma posicao e retorna em qual setor estah
	*/

	int width = centro.x()*2;
	int height = centro.y()*2;

	double C1 = width / 3;
	double C2 = (2*width) / 3;

	double L1 = height / 3;
	double L2 = (2*height) / 3;

	if(p.x() < C1 && p.y() < L1) return 'A';
	if(p.x() > C1 && p.x() < C2 && p.y() < L1) return 'B';
	if(p.x() > C2 && p.y() < L1) return 'C';

	if(p.x() < C1 && p.y() > L1 && p.y() < L2) return 'K';
	if(p.x() > C1 && p.x() < C2 && p.y() > L1 && p.y() < L2) return 'L';
	if(p.x() > C2 && p.y() > L1 && p.y() < L2) return 'M';

	if(p.x() < C1 && p.y() > L2) return 'X';
	if(p.x() > C1 && p.x() < C2 && p.y() > L2) return 'Y';
	if(p.x() > C2 && p.y() > L2) return 'Z';
}
Ejemplo n.º 21
0
 BWAPI::Position getNearestUnwalkablePosition(BWAPI::Position position)
 {
   Polygon* p = BWTA::getNearestUnwalkablePolygon(position.x()/32,position.y()/32);
   BWAPI::Position nearest = BWAPI::Positions::None;
   if (p == NULL)
   {
     //use an edge of the map if we don't find a polygon
     nearest = BWAPI::Position(0,position.y());
   }
   else
   {
     nearest = p->getNearestPoint(position);
   }
   if (position.x()<position.getDistance(nearest))
     nearest=BWAPI::Position(0,position.y());
   if (position.y()<position.getDistance(nearest))
     nearest=BWAPI::Position(position.x(),0);
   if (BWAPI::Broodwar->mapWidth()*32-position.x()<position.getDistance(nearest))
     nearest=BWAPI::Position(BWAPI::Broodwar->mapWidth()*32,position.y());
   if (BWAPI::Broodwar->mapHeight()*32-position.y()<position.getDistance(nearest))
     nearest=BWAPI::Position(position.x(),BWAPI::Broodwar->mapHeight()*32);
   return nearest;
 }
Ejemplo n.º 22
0
void ColorNode::setCenter(BWAPI::Position regionCenter)
{
	center = BWAPI::Position(regionCenter.x(), regionCenter.y());
	updateAge();
}
int distance (BWAPI::Position p1, BWAPI::Position p2){
	return (int) sqrt(pow((double)(p1.x() - p2.x()), 2) + pow((double)(p1.y() - p2.y()), 2));
}
Ejemplo n.º 24
0
//dist is distance between middle unit and target gravity center, interval is length of arc between two units
bool MicroManager::formSquad(const BWAPI::Unitset & targets, int dist, int radius, double angle, int interval)
{
	const BWAPI::Unitset & meleeUnits = getUnits();
	bool attacked = false;
	BWAPI::Position tpos = targets.getPosition();
	BWAPI::Position mpos = meleeUnits.getPosition();

	//do not from squad when fighting or close to enemy
	for (auto & unit : meleeUnits){
		if (unit->isUnderAttack() || unit->isAttackFrame() || targets.size() == 0|| unit->getDistance(tpos) < 80)
			attacked = true;
	}
	if (attacked) {
		BWAPI::Broodwar->drawTextScreen(200, 340, "%s", "Attacked or No targets, Stop Formation");
		return false;
	}
	//if there is a building near the unit, do not form
	for (auto & target : targets){
		auto type = target->getType();
		if (type.isBuilding()){
			return false;
		}
	}
	//Formation is set false by Squad for 5 seconds after formation finished once
	if (!getFormation()){
		BWAPI::Broodwar->drawTextScreen(200, 340, "%s", "Finished Formation");
		return false;
	}
	//BWAPI::Broodwar->drawTextScreen(200, 340, "%s", "Forming");

	const double PI = 3.14159265;

	double ang = angle / 180 * PI;

	//the angle of mid_point on arc
	double m_ang = atan2(mpos.y - tpos.y, mpos.x - tpos.x);
	//circle center
	int cx = (int)(tpos.x - (radius-dist) * cos(m_ang));
	int cy = (int)(tpos.y - (radius-dist) * sin(m_ang));
	BWAPI::Position c;
	c.x = cx; c.y = cy;
	//mid_point on arc
	BWAPI::Position m;
	m.x = (int)(cx + radius*cos(m_ang));
	m.y = (int)(cy + radius*sin(m_ang));
	BWAPI::Broodwar->drawLineMap(c, m, BWAPI::Colors::Yellow);

	BWAPI::Unitset unassigned;
	for (auto & unit : meleeUnits){
		unassigned.insert(unit);
	}

	//move every positions on the arc to the closest unit
	BWAPI::Position tmp;
	int try_time = 0;
	int r = radius;
	int total_dest_dist = 0;
	int num_assigned = 0;

	while (unassigned.size() > 0 && try_time < 5){
		double ang_interval = interval * 1.0 / r;
		double final_ang;
		int num_to_assign;
		int max_units = (int)(ang / ang_interval) + 1;
		if (unassigned.size() < (unsigned)max_units){
			num_to_assign = unassigned.size();
			final_ang = ang_interval * num_to_assign;
		}
		else {
			num_to_assign = max_units;
			final_ang = ang;
		}
		for (int i = 0; i < num_to_assign; i++) {
			//assign from two ends to middle
			double a = m_ang + pow(-1, i % 2)*(final_ang / 2 - (i / 2)*ang_interval);
			int min_dist = MAXINT;
			BWAPI::Unit closest_unit = nullptr;
			tmp.x = (int)(cx + r * cos(a));
			tmp.y = (int)(cy + r * sin(a));
			for (auto & unit : unassigned){
				int d = unit->getDistance(tmp);
				if (d < min_dist){
					min_dist = d;
					closest_unit = unit;
				}
			}
			//if it's a unit far away from fight, do not assign it to a position
			if (closest_unit && min_dist > 300){
				unassigned.erase(closest_unit);
				continue;
			}
			if (tmp.isValid() && closest_unit){
				BWAPI::Broodwar->drawLineMap(closest_unit->getPosition(), tmp, BWAPI::Colors::Red);
				Micro::SmartMove(closest_unit, tmp);
				unassigned.erase(closest_unit);
				//find the total distance between unit and destination
				total_dest_dist += min_dist;
				num_assigned++;
			}		
		}
		r += 40;
		try_time++;
	}

	//if max destination distance less than 32, means forming has been finished
	if (num_assigned > 0 && total_dest_dist / num_assigned <= 32){
		return true;
	}
	else {
		BWAPI::Broodwar->drawTextScreen(200, 340, "%s", "Forming");
		return false;
	}
}
//ctx add
BWAPI::TilePosition BuildingPlacer::getBuildLocationFarFromChokePoint(const Building & b, int buildDist, bool horizontalOnly, bool flag) const
{
	SparCraft::Timer t;
	t.start();

	BWAPI::TilePosition startTitlePos = BWAPI::Broodwar->self()->getStartLocation();
	BWTA::Chokepoint *chokePoint = BWTA::getNearestChokepoint(startTitlePos);
	BWAPI::Position chokeCenterPosition = chokePoint->getCenter();
	BWTA::Region *baseRegion = BWTA::getRegion(BWAPI::Broodwar->self()->getStartLocation());
	BWTA::Polygon basePolygon = baseRegion->getPolygon();
	BWAPI::Position farPosition =  BWAPI::Position(0, 0);
	BWAPI::TilePosition resultPosition = BWAPI::TilePosition(0, 0);
	double dis = 0.0;

	

	for (int i = 0; i < (int)basePolygon.size(); i++) {
		BWAPI::Position point = basePolygon[i];
		double ms1 = t.getElapsedTimeInMilliSec();
		if (point.getDistance(chokeCenterPosition) > dis) {
			dis = point.getDistance(chokeCenterPosition);
			farPosition = point;
		}
	}

	const std::vector<BWAPI::TilePosition> & closestToBuilding = MapTools::Instance().getClosestTilesTo(BWAPI::Position(b.desiredPosition));

	//get best solution
	dis = farPosition.getDistance(BWAPI::Position(startTitlePos));
	
	if (flag == true) {
		for (size_t i = 0; i < closestToBuilding.size(); ++i)
		{
			double ms1 = t.getElapsedTimeInMilliSec();
			if (canBuildHereWithSpace(closestToBuilding[i], b, buildDist, horizontalOnly) && dis > farPosition.getDistance(BWAPI::Position(closestToBuilding[i])))
			{
				resultPosition = closestToBuilding[i];
				break;
				//return closestToBuilding[i];
			}
		}
	}
	else {
		for (size_t i = 0; i < closestToBuilding.size(); ++i)
		{
			double ms1 = t.getElapsedTimeInMilliSec();
			if (canBuildHereWithSpace(closestToBuilding[i], b, buildDist, horizontalOnly) && dis < farPosition.getDistance(BWAPI::Position(closestToBuilding[i])))
			{
				resultPosition = closestToBuilding[i];
				break;
				//return closestToBuilding[i];
			}
		}
	}
	
	if (!basePolygon.isInside(BWAPI::Position(resultPosition))) {
		resultPosition = getBuildLocationNear(b, buildDist, horizontalOnly);
	}

	return resultPosition;
}
Ejemplo n.º 26
0
void WraithManagerExt::executeMicro(const UnitVector & targets)
{
	const UnitVector & selectedUnits = getUnits();
	_noTurretTargetsNo = 0;

	// figure out targets
	UnitVector selectedUnitTargets;
	for (size_t i(0); i<targets.size(); i++)
	{
		// conditions for targeting
		if (targets[i]->isVisible())
		{
			selectedUnitTargets.push_back(targets[i]);

			if (!isTurret(targets[i]))
			{
				_noTurretTargetsNo++;
			}

		}
	}

	setAverageEnemyPosition(selectedUnitTargets);

	// For each unit
	BOOST_FOREACH(BWAPI::Unit * selectedUnit, selectedUnits)
	{
		// Adjust cloak to the situation
		manageCloak(selectedUnit, selectedUnitTargets);

		// if the order is to attack or defend
		if (order.type == order.Attack || order.type == order.Defend)
		{
			// if there are targets
			if (!selectedUnitTargets.empty())
			{
				// find the best target for this unit
				BWAPI::Unit * target = getTarget(selectedUnit, selectedUnitTargets);

				// attack it				
				kiteTarget(selectedUnit, target);

			}
			// if there are no targets
			else
			{
				// if we're not near the order position
				if (selectedUnit->getDistance(order.position) > 100)
				{
					// move to it	

					// Border movement
					BWAPI::Position movePosition;
					if (order.type == SquadOrder::Attack
						&& (StrategyManager::Instance().getCurrentStrategy() == StrategyManager::Instance().TerranWraithRush1Port))
					{
						movePosition = UnitManagerExt::Instance().getMovePosition(selectedUnit);
					}
					else
					{
						movePosition = order.position;
					}
					// eof Border movement
					if (!movePosition.isValid())
					{
						movePosition.makeValid();
					}

					smartAttackMove(selectedUnit, movePosition);
				}
			}
		}

		if (Options::Debug::DRAW_UALBERTABOT_DEBUG)
		{
			BWAPI::Broodwar->drawLineMap(selectedUnit->getPosition().x(), selectedUnit->getPosition().y(),
				selectedUnit->getTargetPosition().x(), selectedUnit->getTargetPosition().y(), Options::Debug::COLOR_LINE_TARGET);
		}
	}
Ejemplo n.º 27
0
	Vector Vector::fromPositions(const BWAPI::Position &from, const BWAPI::Position &to) {
		return Vector(to.x() - from.x(), to.y() - from.y());
	}
Ejemplo n.º 28
0
void CombatCommander::updateDefenseSquads() 
{
	if (_combatUnits.empty() || BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Terran_Science_Vessel) == 1)
    { 
        return; 
    }
    
    BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
    BWTA::Region * enemyRegion = nullptr;
    if (enemyBaseLocation)
    {
        enemyRegion = BWTA::getRegion(enemyBaseLocation->getPosition());
    }

	// for each of our occupied regions
	for (BWTA::Region * myRegion : InformationManager::Instance().getOccupiedRegions(BWAPI::Broodwar->self()))
	{
        // don't defend inside the enemy region, this will end badly when we are stealing gas
        if (myRegion == enemyRegion)
        {
            continue;
        }

		BWAPI::Position regionCenter = myRegion->getCenter();
		if (!regionCenter.isValid())
		{
			continue;
		}

		// start off assuming all enemy units in region are just workers
		int numDefendersPerEnemyUnit = 2;

		// all of the enemy units in this region
		BWAPI::Unitset enemyUnitsInRegion;
        for (auto & unit : BWAPI::Broodwar->enemy()->getUnits())
        {
            // if it's an overlord, don't worry about it for defense, we don't care what they see
            if (unit->getType() == BWAPI::UnitTypes::Zerg_Overlord)
            {
                continue;
            }

            if (BWTA::getRegion(BWAPI::TilePosition(unit->getPosition())) == myRegion)
            {
                enemyUnitsInRegion.insert(unit);
            }
        }

        // we can ignore the first enemy worker in our region since we assume it is a scout
        for (auto & unit : enemyUnitsInRegion)
        {
            if (unit->getType().isWorker())
            {
                enemyUnitsInRegion.erase(unit);
                break;
            }
        }

        int numEnemyFlyingInRegion = std::count_if(enemyUnitsInRegion.begin(), enemyUnitsInRegion.end(), [](BWAPI::Unit u) { return u->isFlying(); });
        int numEnemyGroundInRegion = std::count_if(enemyUnitsInRegion.begin(), enemyUnitsInRegion.end(), [](BWAPI::Unit u) { return !u->isFlying(); });

        std::stringstream squadName;
        squadName << "Base Defense " << regionCenter.x << " " << regionCenter.y; 
        
        // if there's nothing in this region to worry about
        if (enemyUnitsInRegion.empty())
        {
            // if a defense squad for this region exists, remove it
            if (_squadData.squadExists(squadName.str()))
            {
                _squadData.getSquad(squadName.str()).clear();
            }
            
            // and return, nothing to defend here
            continue;
        }
        else 
        {
            // if we don't have a squad assigned to this region already, create one
            if (!_squadData.squadExists(squadName.str()))
            {
                SquadOrder defendRegion(SquadOrderTypes::Defend, regionCenter, 32 * 25, "Defend Region!");
                _squadData.addSquad(squadName.str(), Squad(squadName.str(), defendRegion, BaseDefensePriority));
            }
        }

        // assign units to the squad
        if (_squadData.squadExists(squadName.str()))
        {
            Squad & defenseSquad = _squadData.getSquad(squadName.str());

            // figure out how many units we need on defense
	        int flyingDefendersNeeded = numDefendersPerEnemyUnit * numEnemyFlyingInRegion;
	        int groundDefensersNeeded = numDefendersPerEnemyUnit * numEnemyGroundInRegion;

            updateDefenseSquadUnits(defenseSquad, flyingDefendersNeeded, groundDefensersNeeded);
        }
        else
        {
            UAB_ASSERT_WARNING(false, "Squad should have existed: %s", squadName.str().c_str());
        }
	}

    // for each of our defense squads, if there aren't any enemy units near the position, remove the squad
    std::set<std::string> uselessDefenseSquads;
    for (const auto & kv : _squadData.getSquads())
    {
        const Squad & squad = kv.second;
        const SquadOrder & order = squad.getSquadOrder();

        if (order.getType() != SquadOrderTypes::Defend)
        {
            continue;
        }

        bool enemyUnitInRange = false;
        for (auto & unit : BWAPI::Broodwar->enemy()->getUnits())
        {
            if (unit->getPosition().getDistance(order.getPosition()) < order.getRadius())
            {
                enemyUnitInRange = true;
                break;
            }
        }

        if (!enemyUnitInRange)
        {
            _squadData.getSquad(squad.getName()).clear();
        }
    }
}
Ejemplo n.º 29
0
void BaitManager::initialize_map_points(std::string mapName)
{
	//BWAPI::Position mainBaseLocation = 
	//BWTA::BaseLocation * mainBaseLocation = BWTA::getStartLocation(BWAPI::Broodwar->self());
	BWAPI::Position mainBasePosition = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition();
	//BWAPI::Position mainBasePositon = mainBaseLocation->getPosition();
	mapLoaded = true;
	if (mapName == "(2)Benzene.scx")
	{	
		//set the point where the bait unit will wait for enemies
		if (mainBasePosition.getDistance(BWAPI::Position(400, 1953)) > mainBasePosition.getDistance(BWAPI::Position(3180, 1790)))
		{
			waitPoint = BWAPI::Position(400, 1953);
		}
		else
		{
			waitPoint = BWAPI::Position(3180, 1790);
		}
		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(1400, 960));
		chasePoints.push_back(BWAPI::Position(1050, 790));
		chasePoints.push_back(BWAPI::Position(1110, 500));
		chasePoints.push_back(BWAPI::Position(1400, 320));
		chasePoints.push_back(BWAPI::Position(1880, 604));	

		BWAPI::Broodwar->printf("Map Benzene Loaded");
		return;
	}
	else if (mapName == "(2)Destination.scx")
	{
		//set the point where the bait unit will wait for enemies
		if (mainBasePosition.getDistance(BWAPI::Position(1155, 3515)) > mainBasePosition.getDistance(BWAPI::Position(1890, 525)))
		{
			waitPoint = BWAPI::Position(1155, 3515);
		}
		else
		{
			waitPoint = BWAPI::Position(1890, 525);
		}
		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(1115, 1848));
		chasePoints.push_back(BWAPI::Position(1170, 1143));
		chasePoints.push_back(BWAPI::Position(1200, 2255));
		chasePoints.push_back(BWAPI::Position(958, 2770));
		chasePoints.push_back(BWAPI::Position(270, 1857));

		BWAPI::Broodwar->printf("Map Destination Loaded");
		return;
	}
	else if (mapName == "(2)Heartbreak Ridge.scx")
	{
		//set the point where the bait unit will wait for enemies
		if (mainBasePosition.getDistance(BWAPI::Position(3320, 930)) > mainBasePosition.getDistance(BWAPI::Position(720, 2175)))
		{
			waitPoint = BWAPI::Position(3320, 930);
		}
		else
		{
			waitPoint = BWAPI::Position(720, 2175);
		}
		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2050, 11));
		chasePoints.push_back(BWAPI::Position(3340, 34));
		chasePoints.push_back(BWAPI::Position(349, 175));
		chasePoints.push_back(BWAPI::Position(3180, 237));
		chasePoints.push_back(BWAPI::Position(690, 197));
		chasePoints.push_back(BWAPI::Position(373, 376));
		chasePoints.push_back(BWAPI::Position(215, 221));
		chasePoints.push_back(BWAPI::Position(395, 89));

		BWAPI::Broodwar->printf("Map Heartbreak Ridge Loaded");
		return;
	}

	//BWAPI::Position enemyBasePosition = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition();
	if (!InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getPosition().isValid())
	{
		mapLoaded = false;
		BWAPI::Broodwar->printf("Cannot load 3-4 player map until enemy base is found");
		return;
	}
	//create a set to add positions to sorted such the the closest one to the enemy base is first
	std::set<BWAPI::Position, posComp> basePoints;

	if (mapName == "(3)Aztec.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(3097, 366));
		basePoints.insert(BWAPI::Position(3321, 3798));
		basePoints.insert(BWAPI::Position(294, 1994));
		
		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2180, 3374));
		chasePoints.push_back(BWAPI::Position(1812, 2014));
		chasePoints.push_back(BWAPI::Position(2410, 1915));

		BWAPI::Broodwar->printf("Map Aztec Loaded");
	}
	else if (mapName == "(3)Tau Cross.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(2000, 3719));
		basePoints.insert(BWAPI::Position(563, 757));
		basePoints.insert(BWAPI::Position(3610, 1185));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2413, 2340));
		chasePoints.push_back(BWAPI::Position(1800, 2338));
		chasePoints.push_back(BWAPI::Position(1900, 1942));

		BWAPI::Broodwar->printf("Map Tau Cross Loaded");
	}
	else if (mapName == "(4)Andromeda.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(850, 951));
		basePoints.insert(BWAPI::Position(3248, 909));
		basePoints.insert(BWAPI::Position(3269, 3180));
		basePoints.insert(BWAPI::Position(875, 3153));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2030, 1180));
		chasePoints.push_back(BWAPI::Position(1095, 2035));
		chasePoints.push_back(BWAPI::Position(2068, 2780));
		chasePoints.push_back(BWAPI::Position(3000, 2017));

		BWAPI::Broodwar->printf("Map Andromeda Loaded");
	}
	else if (mapName == "(4)Circuit Breaker.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(3570, 1066));
		basePoints.insert(BWAPI::Position(3559, 3037));
		basePoints.insert(BWAPI::Position(500, 3030));
		basePoints.insert(BWAPI::Position(390, 1085));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(3570, 2305));
		chasePoints.push_back(BWAPI::Position(3900, 2045));
		chasePoints.push_back(BWAPI::Position(3480, 1806));
		chasePoints.push_back(BWAPI::Position(3326, 2075));

		BWAPI::Broodwar->printf("Map Circuit Breaker Loaded");
	}
	else if (mapName == "(4)Empire of the Sun.scm")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(1204, 3426));
		basePoints.insert(BWAPI::Position(1158, 592));
		basePoints.insert(BWAPI::Position(2943, 3508));
		basePoints.insert(BWAPI::Position(2910, 592));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(817, 1140));
		chasePoints.push_back(BWAPI::Position(200, 1569));
		chasePoints.push_back(BWAPI::Position(720, 1876));
		chasePoints.push_back(BWAPI::Position(1094, 1461));

		BWAPI::Broodwar->printf("Map Empire of the Sun Loaded");
	}
	else if (mapName == "(4)Fortress.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(1693, 3516));
		basePoints.insert(BWAPI::Position(980, 1692));
		basePoints.insert(BWAPI::Position(2356, 735));
		basePoints.insert(BWAPI::Position(3129, 2398));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2094, 3116));
		chasePoints.push_back(BWAPI::Position(1453, 1214));
		chasePoints.push_back(BWAPI::Position(1352, 2581));
		chasePoints.push_back(BWAPI::Position(4696, 1573));

		BWAPI::Broodwar->printf("Map Fortress Loaded");
	}
	else if (mapName == "(4)Python.scx")
	{
		//set the point where the bait unit will wait for enemies
		basePoints.insert(BWAPI::Position(699, 2051));
		basePoints.insert(BWAPI::Position(1818, 693));
		basePoints.insert(BWAPI::Position(3351, 2040));
		basePoints.insert(BWAPI::Position(2154, 3335));

		waitPoint = *basePoints.begin();

		//set the points where the bait unit will flee to
		chasePoints.push_back(BWAPI::Position(2919, 3389));
		chasePoints.push_back(BWAPI::Position(3740, 4051));
		chasePoints.push_back(BWAPI::Position(3892, 3851));
		chasePoints.push_back(BWAPI::Position(3388, 3221));
		chasePoints.push_back(BWAPI::Position(310, 3000));

		BWAPI::Broodwar->printf("Map Python Loaded");
	}


	else
	{
		mapLoaded = false;
		BWAPI::Broodwar->printf("Unrecognized Map File Name: %s", &(BWAPI::Broodwar->mapFileName())[0]);
		//BWAPI::Broodwar->printf(&(BWAPI::Broodwar->mapFileName())[0]);
	}



}
Ejemplo n.º 30
0
BWAPI::Position operator+(const BWAPI::Position &position, const dementor::Vector &vector) {
	return BWAPI::Position(position.x()+vector.getX(), position.y()+vector.getY());
}