Example #1
0
//BWAPI calls this when a unit becomes accessible
void ExampleAIModule::onUnitDiscover(Unit unit){
	
	//Broodwar->sendText("Unit [%s] discovered ID [%d]", unit->getType().getName().c_str(), unit->getID());

	if (unit->getPlayer() == Broodwar->self() && unit->getType() == UnitTypes::Terran_Command_Center) {
		commandCenters.insert(unit);
	}
	else if(unit->getPlayer() == Broodwar->self() && unit->getType() == UnitTypes::Terran_SCV){
		// Add SCV to map
		SCVAgent *agent = new SCVAgent(unit, this);
		scvMap[unit->getID()] = agent;
		//(*scvMap)[unit->getID()] = agent; When SCVmap is a pointer
	}
	else if(unit->getPlayer() == Broodwar->self() && unit->getType() == UnitTypes::Terran_Marine){
		// Add marine to HashTable
		marines[unit->getID()] = new MarineAgent(unit);
	}

	

	//new mineral discovered, is it at the range of a command center?
	//framecount test prevents checking on unacessible minerals at game begin
	if(Broodwar->getFrameCount() != 0 && unit->getType() == UnitTypes::Resource_Mineral_Field){
		discoveredMineralPositions.push_back(unit->getPosition());
	}
	
}
Example #2
0
int UnitClass::getTimeToKill(Unit unit)
{
	int health = unit->totalHitPoints();

	BWAPI::WeaponType weapon = getWeapon(unit);

	int weaponDamage = weapon.damageAmount() + (weapon.damageFactor() * getPlayer()->getUpgradeLevel(weapon.upgradeType()));
	if(weaponDamage == 0)
		return 5000;

	int thisNumberOfShots = health / weaponDamage;

	if(weapon.damageType() == BWAPI::DamageTypes::Concussive)
	{
		if(unit->getType().size() == BWAPI::UnitSizeTypes::Large)
			thisNumberOfShots *= 4;
		else if(unit->getType().size() == BWAPI::UnitSizeTypes::Medium)
			thisNumberOfShots += thisNumberOfShots;
	}
	else if(weapon.damageType() == BWAPI::DamageTypes::Explosive)
	{
		if(unit->getType().size() == BWAPI::UnitSizeTypes::Small)
			thisNumberOfShots += thisNumberOfShots;
		else if(unit->getType().size() == BWAPI::UnitSizeTypes::Medium)
			thisNumberOfShots += thisNumberOfShots / 2;
	}

	if((BWAPI::Broodwar->getGroundHeight(getTilePosition()) - BWAPI::Broodwar->getGroundHeight(unit->getTilePosition())) < 0)
		thisNumberOfShots += thisNumberOfShots;

	return thisNumberOfShots * weapon.damageCooldown();
}
Example #3
0
/**
 * @param p the priority of this event
 * @param str the structure which repair
 */
BRepairUnitAnimEvent::BRepairUnitAnimEvent(uint32_t p, Structure *str) : BuildingAnimEvent(p,str,8)
{
    int		un_cost;
    Sint16	health;
    Unit	*UnitToFix = NULL;

    // The Anim is not finished
	done		= false;
    // Structure to Apply
    this->strct = str;

    StartFrame	= 0;
    frame		= 0;

	UnitToFix = p::uspool->getUnitAt(strct->UnitToRepairPos);

	if (UnitToFix == 0)
	{
		logger->error ("%s line %i: Structure anim unit not found\n", __FILE__, __LINE__);
		stop();
		return;
	}

	health = UnitToFix->getHealth();
	un_cost = UnitToFix->getType()->getCost();
	if (health > 0) {
		dmg_cost = (Uint16)(((double)un_cost/(double)UnitToFix->getType()->getMaxHealth()) * ((double)UnitToFix->getType()->getMaxHealth() - (double)health));
	} else {
		dmg_cost = (Uint16)un_cost;
    }

    setDelay(1);
}
Unit* CompaniaDefensiva::buscarObjetivosMarines() {
    // Los marines atacan a cualquier unidad enemiga que haya entrado a la region defendida por la compañia defensiva
    Unit *objetivo = NULL;

    if (!Broodwar->enemy()->getUnits().empty()) {
        std::set<Unit*>::const_iterator ItObj;

        Region *inicial = BWTA::getStartLocation(Broodwar->self())->getRegion();

        ItObj = Broodwar->enemy()->getUnits().begin();
        while (ItObj != Broodwar->enemy()->getUnits().end()) {
            // Busca la primer unidad enemiga que este dentro de la region defendida por la compañia defensiva
            if ((*ItObj)->exists() && ((*ItObj)->isVisible()) && ((*ItObj)->isDetected()) && (inicial->getPolygon().isInside((*ItObj)->getPosition()))) {
                if (objetivo == NULL) {
                    objetivo = (*ItObj);
                    return objetivo;
                }
                else {
                    if ((objetivo->getType().size() == UnitSizeTypes::Large) && (((*ItObj)->getType().size() == UnitSizeTypes::Medium) || ((*ItObj)->getType().size() == UnitSizeTypes::Small)))
                        objetivo = (*ItObj);
                    else if ((objetivo->getType().size() == UnitSizeTypes::Medium) && ((*ItObj)->getType().size() == UnitSizeTypes::Small))
                        objetivo = (*ItObj);
                }
            }

            ItObj++;
        }
    }

    return objetivo;
}
Unit* CompaniaDefensiva::buscarObjetivosGhost() {
    // Los objetivos para los fantasmas seran unidades mecanicas, ya que las mismas pueden ser locked down
    Unit *objetivo = NULL;

    if (!Broodwar->enemy()->getUnits().empty()) {
        std::set<Unit*>::const_iterator ItObj;

        Region *inicial = BWTA::getStartLocation(Broodwar->self())->getRegion();

        ItObj = Broodwar->enemy()->getUnits().begin();
        while (ItObj != Broodwar->enemy()->getUnits().end()) {
            // Busca una unidad mecanica que este dentro de la region defendida por el fantasma o una unidad mecanica que este atacando alguna unidad nuestra que este dentro de la region defendida por la compañia defensiva
            if ((*ItObj)->exists() && ((*ItObj)->isVisible()) && (*ItObj)->getType().isMechanical() && (!(*ItObj)->isLockedDown()) && (inicial->getPolygon().isInside((*ItObj)->getPosition()) || ((*ItObj)->getOrderTarget() != NULL && inicial->getPolygon().isInside((*ItObj)->getOrderTarget()->getPosition())) || (((*ItObj)->getTarget() != NULL) && inicial->getPolygon().isInside((*ItObj)->getTarget()->getPosition())))) {
                if (objetivo == NULL) {
                    objetivo = (*ItObj);
                    return objetivo;
                }
                else {
                    // Busca unidad enemiga de mayor tamaño que cumpla las condiciones para ser atacada por los fantasmas
                    if ((objetivo->getType().size() == UnitSizeTypes::Small) && (((*ItObj)->getType().size() == UnitSizeTypes::Medium) || ((*ItObj)->getType().size() == UnitSizeTypes::Large)))
                        objetivo = (*ItObj);
                    else if ((objetivo->getType().size() == UnitSizeTypes::Medium) && ((*ItObj)->getType().size() == UnitSizeTypes::Large))
                        objetivo = (*ItObj);
                }
            }

            ItObj++;
        }
    }

    return objetivo;
}
Example #6
0
void Bases::onUnitDestroy(Unit unit)
{
	if (unit->getType() == UnitTypes::Protoss_Nexus)
		removeNexus(unit->getID());

	if (unit->getType() == UnitTypes::Protoss_Probe)
		removeWorker(unit->getID());
}
Example #7
0
void Bases::onUnitCreate(Unit unit)
{
	if (unit->getType() == UnitTypes::Protoss_Nexus)
		addNexus(unit->getID());

	if (unit->getType() == UnitTypes::Protoss_Probe)
		addWorker(unit->getID());
}
Example #8
0
void Economy::onUnitDestroy(Unit unit)
{
	if (unit->getType() == UnitTypes::Protoss_Probe || UnitTypes::Protoss_Nexus)
		Bases.onUnitDestroy(unit);

	if (unit->getType() == UnitTypes::Protoss_Pylon)
		Bp.onUnitDestroy(unit);
}
Example #9
0
void BRepairUnitAnimEvent::run()
{
	Unit* UnitToFix = 0;
	Sint16 health;
	uint16_t cost;

//	updateDamaged();

	if( !strct->isAlive() || done ) {
		delete this;
		return;
	}

	UnitToFix = p::uspool->getUnitAt(strct->UnitToRepairPos);

	if (UnitToFix == NULL){
		delete this;
		return;
	}

	health = UnitToFix->getHealth();

	if (health < UnitToFix->getType()->getMaxHealth()){
		cost = (Uint16)((double)dmg_cost/((double)UnitToFix->getType()->getMaxHealth() - (double)health));
		Player* Owner = p::ppool->getPlayer(UnitToFix->getOwner());
		if (Owner->getMoney() > cost){
			Owner->changeMoney(-1 * cost);
			dmg_cost -= cost;
			UnitToFix->ChangeHealth (1);
			UnitToFix->updateDamaged();
		}
	}else{
		//printf ("%s line %i: Unit repaired\n", __FILE__, __LINE__);
		// @todo ADD "Unit repaired" sound
		//pc::sfxeng->PlaySound(pc::Config.UnitRepaired);
		stop();
	}

	if (frame < 6){
		frame++;
	}else{
		frame = 0;
	}

	if (strct->getNumbImages (0) > frame){
		strct->setImageNum(frame,0);
	}else{
		logger->error ("%s line %i: Failed to set frame %i\n", __FILE__, __LINE__, frame);
	}

	setDelay(3);
	p::aequeue->scheduleEvent(this);
}
Example #10
0
void AgentManager::removeAgent(Unit unit)
{
	for (auto &a : agents)
	{
		if (a->matches(unit))
		{
			if (a->isBuilding())
			{
				BuildingPlacer::getInstance()->buildingDestroyed(unit);
			}

			a->destroyed();
			Commander::getInstance()->unitDestroyed(a);

			//Special case: If a bunker is destroyed, we need to remove
			//the bunker squad.
			if (unit->getType().getID() == UnitTypes::Terran_Bunker.getID())
			{
				int squadID = a->getSquadID();
				Commander::getInstance()->removeSquad(squadID);
			}

			return;
		}
	}
}
Example #11
0
void TestModule::onUnitDestroy(Unit unit)
{
  if (unit!=NULL)
    Broodwar->printf("A %s [%p] has been destroyed",unit->getType().c_str(),unit);
  else
    Broodwar->printf("A %p has been destroyed",unit);
}
bool BattlecruiserAgent::useAbilities()
{
	//To prevent order spamming
	lastOrderFrame = Broodwar->getFrameCount();

	if (Broodwar->getFrameCount() - lastUseFrame >= 80 && (unit->isIdle() || unit->isMoving()))
	{
		TechType gun = TechTypes::Yamato_Gun;
		if (Broodwar->self()->hasResearched(gun))
		{
			if (unit->getEnergy() >= gun.energyCost())
			{
				int range = gun.getWeapon().maxRange();
				
				Unit target = TargetingAgent::findHighprioTarget(this, range, true, true);
				if (target != NULL)
				{
					Broodwar << "Yamato Gun used on " << target->getType().getName() << endl;
					unit->useTech(gun, target);
					lastUseFrame = Broodwar->getFrameCount();
					return true;
				}
			}
		}
	}

	return false;
}
Example #13
0
void Economy::onUnitMorph(Unit unit)
{
	if (unit->getType().isRefinery())
		assimilatorUnderConstruction = false;
	
	Bases.onUnitMorph(unit);
}
Example #14
0
int DefenseSquadTask::getPriority(Unit unit) const
{
	if(!unit->getType().isWorker())
	{
		bool isNeeded = false;
		if(mNeedsAntiAir && unit->canAttackAir())
			isNeeded = true;
		
		if(mNeedsAntiGround && unit->canAttackGround())
			isNeeded = true;

		if(isNeeded)
			return 30;
		else
			return 1;
	}

	int workersToReturn = int(mWorkerDefenders.size()) - mNeededWorkers;
	if(workersToReturn > 0)
	{
		int count = 1;
		for each(Unit worker in mWorkerDefenders)
		{
			if(worker == unit)
			{
				if(count <= workersToReturn)
					return 1;
				break;
			}
			++count;
		}
	}
Example #15
0
int UnitClass::getDistance(Unit unit)
{
	if(!unit)
		return 0;

	return getDistance(unit->getType(), unit->getPosition());
}
Example #16
0
void Game::handleAiCommands()
{
	for (unsigned int n = 0; n<p::uspool->getNumbUnits(); n++)
	{
		Unit* unit = p::uspool->getUnit(n);
		if (unit!=0){
		if (!unit->IsMoving() && !unit->IsAttacking() && !unit->IsHarvesting())
		{
			if (unit->aiCommandList.size()>0)
			{
				AiCommand* com = unit->aiCommandList[0];
				//if (com->getId() == 3 || com->getId() == 8)
				{
					logger->debug("AICOMMAND MOVE UNIT = %s \n", unit->getType()->getTName());
					Uint32 pos = p::ccmap->getWaypoint(com->getWaypoint());
					logger->debug("here$-1%d\n", pos);
					unit->move(pos, true);
					vector<AiCommand*>::iterator i = unit->aiCommandList.begin();
					unit->aiCommandList.erase(i);
				}
			}
		}
	}
	}


}
Example #17
0
void GeneticAlgorithm::mutation(Army *ind, int degree)
{
    int unitID = rand()%ind->nUnits();
    Unit *unit = ind->getUnitAtIndex(unitID);

    int tacticID = rand()%unit->getTacticSize();
    Tactic *tactic = unit->getTacticAt(tacticID);

    int newType = unit->getType();

    switch(degree)
    {
        case MUTATION_UNIT_TYPE:{ //Mutate a unit type
            mutateUnitType(ind, unitID, newType);
        }
        break;

        case MUTATION_UNIT_TACTIC: //Mutate a unit tactic
            mutateTactic(tactic, rand()%4);
        break;

        case MUTATION_UNIT_POSITION: //Mutate a unit position
            unit->setBluePrintCoord( Coordinates(rand()%COMBAT_AREA_WIDTH + 150, rand()%COMBAT_AREA_HEIGHT + 50) );
        break;

        default:
            break;
    }
    GoldCap(ind);
}
Example #18
0
  //--------------------------------------------- IS IN WEAPON RANGE -----------------------------------------
  bool UnitInterface::isInWeaponRange(Unit target) const
  {
    // Preliminary checks
    if ( !this->exists() || !target || !target->exists() || this == target )
      return false;

    // Store the types as locals
    UnitType thisType = getType();
    UnitType targType = target->getType();

    // Obtain the weapon type
    WeaponType wpn = target->isFlying() ? thisType.airWeapon() : thisType.groundWeapon();

    // Return if there is no weapon type
    if ( wpn == WeaponTypes::None || wpn == WeaponTypes::Unknown )
      return false;

    // Retrieve the min and max weapon ranges
    int minRange = wpn.minRange();
    int maxRange = getPlayer()->weaponMaxRange(wpn);

    // Check if the distance to the unit is within the weapon range
    int distance = this->getDistance(target);
    return (minRange ? minRange < distance : true) && distance <= maxRange;
  }
bool UnitAndStructurePool::getUnitOrStructureLimAt(Uint32 curpos, float* width,
        float* height, Uint32* cellpos, Uint8* igroup, Uint8* owner,
        Uint8* pcol, bool* blocked)
{
    Uint32 cval = unitandstructmat[curpos];
    if (cval & US_IS_UNIT) {
        Unit* un = unitpool[cval&0xffff];
        *width   = 0.75f;
        *height  = 0.75f;
        *owner   = un->getOwner();
        *pcol    = p::ppool->getPlayer(*owner)->getStructpalNum();
        *igroup  = 0;
        *cellpos = un->getPos();
        *blocked = true;
        if (un->getType()->isInfantry()) {
            InfantryGroup* igrp = un->getInfantryGroup();
            for (int i=0;i<5;++i)
                if (igrp->unitAt(i) != NULL)
                    *igroup |= 1<<i;
        }
        return true;
    } else if ((cval & US_IS_STRUCTURE) || (cval & US_IS_WALL)) {
        Structure* st = structurepool[cval&0xffff];
        *width   = 1.0f;
        *height  = 1.0f;
        *owner   = st->getOwner();
        *pcol    = p::ppool->getPlayer(*owner)->getStructpalNum();
        *igroup  = 0;
        *cellpos = st->getBPos(curpos);
        *blocked = true;
        return true;
    }
    return false;
}
Example #20
0
void GeneticAlgorithm::mutateUnitType(Army* ind, int unitID, int newType)
{
    Unit *removed = ind->getUnitAtIndex(unitID);

    if(removed->getType() == 0)    //Do not let mothership's type mutate
        return;

    while(newType == removed->getType())
        newType = rand()%(N_UNIT_TYPE-1) + 1;   //Mothership is always 0

    ind->removeUnit(unitID);
    Unit *newUnit = ind->createUnit(removed->getID(), newType, removed->getBluePrintCoord());
    for (unsigned int i = 0; i < removed->getTacticSize(); ++i)
        newUnit->addTactic( Tactic::copy(removed->getTacticAt(i)) );
    delete removed;
}
Example #21
0
bool PFManager::moveToGoal(BaseAgent* agent,  TilePosition checkpoint, TilePosition goal)
{
	if (checkpoint.x() == -1 || goal.x() == -1) return false;
	Unit* unit = agent->getUnit();

	if (unit->isStartingAttack() || unit->isAttacking())
	{
		return false;
	}

	Position toReach = Position(checkpoint);
	double distToReach = toReach.getDistance(unit->getPosition());

	int engageDist = unit->getType().groundWeapon().maxRange();
	if (agent->isOfType(UnitTypes::Terran_Medic))
	{
		engageDist = 6 * 32;
	}
	if (engageDist <= 64)
	{
		engageDist = 64;
	}
	
	if (distToReach <= engageDist)
	{
		if (unit->isMoving()) unit->stop();
		return true;
	}
	
	//Move
	if (!unit->isMoving()) return unit->attack(toReach);
	else return true;
}
Example #22
0
void ConstructionTask::giveUnit(Unit unit)
{
	if(unit->getType() == mType.whatBuilds().first)
	{
		LOGMESSAGE(String_Builder() << "ConstructionTask : " << mType.getName() << " : Given Builder");
		assert(!mBuilder);
		mBuilder = unit;
		reserveResources();
	}
	else if(unit == mReservedLocation->getUnitPrediction() || unit->getTilePosition() == mReservedLocation->getTilePosition())
	{
		LOGMESSAGE(String_Builder() << "ConstructionTask : " << mType.getName() << " : Given Produced Unit");

		assert(!mProducedUnit || !mProducedUnit->exists());

		mProducedUnit = unit;
		if(mProducedUnit->exists())
		{
			freeResources();
			freeLocation();
		}
	}
	else
		assert(false);
}
Example #23
0
bool AgentFactory::isOfType(Unit unit, UnitType type)
{
	if (unit->getType().getID() == type.getID())
	{
		return true;
	}
	return false;
}
Example #24
0
void		Unit::attack(Unit &target) const
{
	if (_die)
		return ;
	std::cout << "Unit #" << _index << " (" << _type << ") damaged unit #" << target.getIndex();
	std::cout << " (" << target.getType() << ")." << std::endl;
	target -= _damage;
}
Example #25
0
void BlobGame::updateVision(){
	std::vector<Tile*> tiles2;
	std::vector<Tile*> tiles3;
	std::vector<Enemy*> enemies;
	Sprite2d* sprite;
	Vector3 colorVec(150,150,150);
	Vector3 colorVec2(70,70,70);
	Unit* unit;
	int i;
	std::vector<Tile*> tiles = *m_Level->getTiles();
	for(i = 0;i < m_Level->getNumberOfHorizontalTiles()*
				  m_Level->getNumberOfVerticalTiles();i++){
		if(!ContainsFlags(tiles[i]->getTileTypes(),Hole) && 
						  tiles[i]->getSprite()->getColor() != colorVec2){
		   tiles[i]->getSprite()->setColor(colorVec2);
		}
	}
	for(i = 0;i < m_GameObjects->size();i++){
		unit = (Unit*)(*m_GameObjects)[i];
		if(unit->getAllegiance() == "Foe"){
			unit->getSprite()->setHiden(true);
			enemies.push_back((Enemy*)unit);
		}
		else if(unit->getType() == "Blob"){
			tiles3 = getSquareVision(m_Level,ALLY_VISION,unit->getCurrentTile());
			for(int j = 0;j < tiles3.size();j++){
				if(tiles2.size() == 0){
					tiles2.push_back(tiles3[j]);
					if(!ContainsFlags(tiles3[j]->getTileTypes(),Hole) &&
						tiles3[j]->getSprite()->getColor() != colorVec){
						tiles3[j]->getSprite()->setColor(150,150,150,255);
					}
					continue;
				}
				for(int k = 0;k < tiles2.size();k++){
					if(tiles2[k] == tiles3[j]){
						break;
					}
					else if(k == tiles2.size()-1){
						tiles2.push_back(tiles3[j]);
						if(!ContainsFlags(tiles3[j]->getTileTypes(),Hole) &&
							tiles3[j]->getSprite()->getColor() != colorVec){
							tiles3[j]->getSprite()->setColor(150,150,150,255);
						}
					}
				}
			}
		}
	}
	for(i= 0;i < tiles2.size();i++){
		for(int k = 0;k < enemies.size();k++){
			if(tiles2[i] == enemies[k]->getCurrentTile()){
				enemies[k]->getSprite()->setHiden(false);
			}
		}
	}
}
Example #26
0
void DropAction::removeUnit(Unit unit)
{
	mUnits.erase(unit);

	if(unit != mShuttle)
		mFreeSpace += unit->getType().spaceRequired();
	else
		mShuttle = StaticUnits::nullunit;
}
Example #27
0
int UnitClass::getWeaponMinRange(Unit unit)
{
	if(!unit)
		return 0;

	if(unit->getType().isFlyer() || unit->isLifted())
		return getType().airWeapon().minRange();
	else
		return getType().groundWeapon().minRange();
}
Example #28
0
int UnitClass::getRemainingCooldown(Unit unit)
{
	if(!unit)
		return 0;

	if(unit->getType().isFlyer() || unit->isLifted())
		return getRemainingAirCooldown();
	else
		return getRemainingGroundCooldown();
}
Example #29
0
void TechTask::giveUnit(Unit unit)
{
	if(unit->getType() == mType.whatResearches())
	{
		mUnit = unit;
		assert(mReservedResources == false);
		ResourceTracker::Instance().reserveCurrentMinerals(mRequiredSatisfyTime, mType.mineralPrice());
		ResourceTracker::Instance().reserveCurrentGas(mRequiredSatisfyTime, mType.gasPrice());
		mReservedResources = true;
	}
}
/// retrieves infantry group from a given cell
InfantryGroup* UnitAndStructurePool::getInfantryGroupAt(Uint32 cell)
{
    Unit* un;
    if (unitandstructmat[cell] & US_IS_UNIT) {
        un = unitpool[unitandstructmat[cell]&0xffff];
        if( ((UnitType *)un->getType())->isInfantry() ) {
            return un->getInfantryGroup();
        }
    }
    return NULL;
}