Position ObserverScoutTask::getStartLocation(Unit unit) const
{
	if(mData)
		return mData->getNextPosition(unit->getPosition());

	return unit->getPosition();
}
Position ObserverScoutTask::getEndLocation(Unit unit) const
{
	if(mData)
		return mData->getLastPosition(unit->getPosition());

	return unit->getPosition();
}
Example #3
0
double ScoutDataClass::getDistance(Unit unit)
{
	if(mPositions.size() == 1)
		return (*mPositions.begin()).getApproxDistance(unit->getPosition());
	else
		return getNextPosition(unit->getPosition()).getApproxDistance(unit->getPosition());
}
Example #4
0
    //Run the action
    //Log parameter indicate if we write something or not on the standard output
    void execute(bool log = false)
    {
        if (log)
            std::cout << "Unit " << unit_->getId() << " escape from " << unit_->getPosition();

        unit_->moveToPosition(-position_);

        if (log)
            std::cout << " to " << unit_->getPosition() << std::endl;
    }
Example #5
0
void MarinesAIModule::allUnitsAttackClosest() {
  for(std::map<Unit*, std::pair<bool, int>>::const_iterator it = ownUnits.begin(); it != ownUnits.end(); it++) {
    if (!sightedEnemies.empty() && !isFleeing((*it).first)) {
      Unit* target = getClosestUnit((*it).first);
      Unit* own = (*it).first;
      own->attackUnit(target);
      Broodwar->drawLine(CoordinateType::Map, own->getPosition().x(), own->getPosition().y(), target->getPosition().x(), target->getPosition().y(), Colors::Red);
    }
  }
}
Position ConstructionTask::getEndLocation(Unit unit) const
{
	if(mReservedLocation)
		return mReservedLocation->getPosition();

	return unit->getPosition();
}
Example #7
0
/**
  * Counts the barracks constructed or under construction around a command center
  */
int ExampleAIModule::calculateBarracksFromCommandCenter(Unit cmdCenter) {

	//first: count built barracks around the command center
	Position commandCenterPos = cmdCenter->getPosition();
	
	Unitset units = Broodwar->getUnitsInRadius(commandCenterPos, BASE_RADIUS);
	int builtBarracks = 0;
	for ( Unitset::iterator u = units.begin(); u != units.end(); ++u ) {
		if ( u->getType() == UnitTypes::Terran_Barracks && u->isCompleted()) {
			builtBarracks++;
		}
	}
	
	//second: count the SCVs constructing around the command center
	int scheduledForConstruction = 0;
	for(auto scv = scvMap.begin(); scv != scvMap.end(); scv++){
		//if SCV is not constructing the barracks but is moving towards it...
		if(scv->second->state == BUILDING_BARRACKS && Position(scv->second->newBuildingLocation).getApproxDistance(commandCenterPos) < BASE_RADIUS ){
			
			Broodwar->drawCircleMap(scv->second->gameUnit->getPosition(),20,Color(Colors::Cyan));
			scheduledForConstruction++;
		}
	}
	//Broodwar->sendText("%d - %d",builtBarracks,scheduledForConstruction);
	return builtBarracks + scheduledForConstruction;
}
sf::Vector2f sbe::Seek::use(Unit& unit)
{
	std::random_device rd;
	std::mt19937_64 gen(rd());
	std::uniform_int_distribution<int> disInt;

	sf::Vector2f desiredVelocity = target - unit.getPosition();
	float distance = sbe::AdvMath::magnitude(desiredVelocity);

	desiredVelocity = sbe::AdvMath::normalize(desiredVelocity);
	desiredVelocity = sbe::AdvMath::multiply(desiredVelocity, unit.getMaxVelocity());

	if (distance < slowingRadius) // arrival
	{
		desiredVelocity = sbe::AdvMath::multiply(desiredVelocity, distance / slowingRadius);
	}

	sf::Vector2f steering = desiredVelocity - unit.getVelocity();
	steering = sbe::AdvMath::multiply(steering, 1.f / unit.getMass());

	sf::Vector2f newVelocity = unit.getVelocity() + steering;
	if (sbe::AdvMath::magnitude(newVelocity) > unit.getMaxVelocity())
	{
		newVelocity = sbe::AdvMath::normalize(newVelocity);
		newVelocity = sbe::AdvMath::multiply(newVelocity, unit.getMaxVelocity());
	}

	return newVelocity;
}
Example #9
0
void UnitClass::returnCargo(Unit unit)
{
	if(!unit)
		return;

	if(!unit->exists() || !unit->isCompleted())
	{
		move(unit->getPosition());
		return;
	}

	if(exists())
	{
		if(mUnit->getOrder() == BWAPI::Orders::ResetCollision)
			return;
		
		if(mUnit->getOrder() == BWAPI::Orders::ReturnGas || mUnit->getOrder() == BWAPI::Orders::ReturnMinerals)
		{
			if(mUnit->getOrderTarget() == unit->mUnit)
				return;
		}

		if(mUnit->getLastCommand().getType() == BWAPI::UnitCommandTypes::Right_Click_Unit && mUnit->getLastCommand().getTarget() == unit->mUnit)
		{
			if(mLastOrderExecuteTime >= BWAPI::Broodwar->getFrameCount())
				return;
		}

		if(mUnit->rightClick(unit->mUnit))
			mLastOrderExecuteTime = BWAPI::Broodwar->getFrameCount() + BWAPI::Broodwar->getRemainingLatencyFrames();
	}
}
Example #10
0
void UnitClass::useTech(BWAPI::TechType tech, Unit target)
{
	if(exists() && target)
	{
		if(!target->exists())
		{
			move(target->getPosition());
			return;
		}

		if(mUnit->getOrder() == tech.getOrder())
		{
			if(mUnit->getOrderTarget() == target->mUnit)
				return;
		}

		if(mUnit->getLastCommand().getType() == BWAPI::UnitCommandTypes::Use_Tech_Unit && mUnit->getLastCommand().getTechType() == tech && mUnit->getLastCommand().getTarget() == target->mUnit)
		{
			if(mLastOrderExecuteTime >= BWAPI::Broodwar->getFrameCount())
				return;
		}

		if(mUnit->useTech(tech, target->mUnit))
			mLastOrderExecuteTime = BWAPI::Broodwar->getFrameCount() + BWAPI::Broodwar->getRemainingLatencyFrames();
	}
}
Example #11
0
void UnitClass::attack(Unit unit)
{
	if(exists() && unit)
	{
		if(!unit->exists())
		{
			move(unit->getPosition());
			return;
		}

		if(mUnit->getOrder() == BWAPI::Orders::AttackUnit)
		{
			if(mUnit->getOrderTarget() == unit->mUnit)
				return;
		}

		if(mUnit->getLastCommand().getType() == BWAPI::UnitCommandTypes::Attack_Unit && mUnit->getLastCommand().getTarget() == unit->mUnit)
		{
			if(mLastOrderExecuteTime >= BWAPI::Broodwar->getFrameCount())
				return;
		}

		if(mUnit->attack(unit->mUnit))
			mLastOrderExecuteTime = BWAPI::Broodwar->getFrameCount() + BWAPI::Broodwar->getRemainingLatencyFrames();
	}
}
Example #12
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 #13
0
int UnitClass::getDistance(Unit unit)
{
	if(!unit)
		return 0;

	return getDistance(unit->getType(), unit->getPosition());
}
Example #14
0
std::list<Unit*>* AI::collisionDetection(Unit& unit, std::list<Unit*>* Units){
    float lowTheta = unit.getTheta()-10;
    float upTheta  = unit.getTheta()+10;
    float upRad  = unit.getGame()->getWorldRadius().y;
    float lowRad = unit.getGame()->getWorldRadius().x;
    
    CIwFVec2 Pos = unit.getPosition()+unit.getVelocity();
    float rad = unit.ConvertToRTheta(Pos).x;
    float theta = unit.ConvertToRTheta(Pos).y;
    float size = unit.getSize();
   
    
    std::list<Unit*>* collide_array = new std::list<Unit*>();
    if(lowRad <= rad <= upRad){
        return NULL;
    }
    for(std::list<Unit*>::iterator itr = Units->begin(); itr != Units->end(); itr++){
        Unit *temp = *itr;
        if(lowTheta <= temp->getTheta() <= upTheta){
            CIwFVec2 tempPos = temp->getPosition();
            float dist = sqrt((tempPos.x+Pos.x)*(tempPos.x+Pos.x)+(tempPos.y+Pos.y)*(tempPos.y+Pos.y));
            if (dist<=(size+temp->getSize())) {
                collide_array->push_back(temp);
            }
        }
    }
    return collide_array;
}
void ClientGameSession::AddDisc( unsigned char column, bool isPlayer0 )
{
    Vector2D spawnPos( 5.0f + column * 70.0f, 50.0f );
    Vector2D targetPos;

    for( int y = 0; y < ROW_COUNT; ++y )
    {
        if( mBoard[column][y] == BoardTile::BLANK )
        {
            targetPos = Vector2D( 5.0f + column * 70.0f, 105.0f + ( ROW_COUNT - y ) * 70.0f );
            break;
        }
    }

    Unit* discUnit;

    if( isPlayer0 )
    {
        discUnit = new Unit( spawnPos,
                             new Animation( mpTexture2DManager->getTexture( "Disc0" ), 1, Vector2D( 0, 0 ), 70, 70, 60, false ), Vector2D( 1, 1 ), "Disc0", false );
    }
    else
    {
        discUnit = new Unit( spawnPos,
                             new Animation( mpTexture2DManager->getTexture( "Disc1" ), 1, Vector2D( 0, 0 ), 70, 70, 60, false ), Vector2D( 1, 1 ), "Disc1", false );
    }

    mpUnitManager->addUnit( discUnit );

    //1 second lerp
    discUnit->LerpTo( targetPos, ( targetPos - discUnit->getPosition() ).getLength() * 1.0f );
}
Example #16
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 #17
0
	void ZombieGame::shotHit(Position startPosition, Position hitPosition, Unit& unit) {
		Animation* dieAnimation = &humanInjured_;
		if (unit.isInfected()) {
			++zombiesKilled_;
			dieAnimation = &zombieInjured_;
		}

		activateFirstFreeSlot(graphicAnimations_, unit.getPosition(), unit.getDirection(), *dieAnimation);
	}
Example #18
0
void UnitAgent::debug_showGoal()
{
	if (!isAlive()) return;
	if (unit->isLoaded()) return;
	if (unit->isBeingConstructed()) return;
	if (!unit->isCompleted()) return;
	
	if (goal.x() >= 0 && unit->isMoving())
	{
		Position a = Position(unit->getPosition());
		Position b = Position(goal);
		Broodwar->drawLine(CoordinateType::Map,a.x(),a.y(),b.x(),b.y(),Colors::Teal);

		Broodwar->drawText(CoordinateType::Map, a.x(), a.y() - 5, "Move (%d,%d)", goal.x(), goal.y());
	}

	if (!unit->isIdle())
	{
		Unit* targ = unit->getOrderTarget();
		if (targ != NULL)
		{
			Position a = Position(unit->getPosition());
			Position b = Position(targ->getPosition());

			if (targ->getPlayer()->isEnemy(Broodwar->self()))
			{
				if (targ->exists())
				{
					Broodwar->drawLine(CoordinateType::Map,a.x(),a.y(),b.x(),b.y(),Colors::Red);
					Broodwar->drawText(CoordinateType::Map, unit->getPosition().x(), unit->getPosition().y(), "Attack %s", targ->getType().getName().c_str());
				}
			}
			else
			{
				if (targ->exists())
				{
					Broodwar->drawLine(CoordinateType::Map,a.x(),a.y(),b.x(),b.y(),Colors::Green);
					Broodwar->drawText(CoordinateType::Map, unit->getPosition().x(), unit->getPosition().y(), "%s", targ->getType().getName().c_str());
				}
			}
		}
	}

	if (unit->isBeingHealed())
	{
		Broodwar->drawCircle(CoordinateType::Map, unit->getPosition().x(), unit->getPosition().y(), 32, Colors::White, false);
	}

	if (unit->getType().isDetector())
	{
		double range = unit->getType().sightRange();
		int x = unit->getPosition().x();
		int y = unit->getPosition().y();
		Broodwar->drawCircle(CoordinateType::Map,x,y,(int)range, Colors::Red, false);
	}
}
Example #19
0
	void ZombieGame::moveUnits(Unit& unit, Unit& human) {
		Position diff = unit.getPosition() - human.getPosition();
		double inner = 10;
		double outer = 200;
		if (diff.LengthSquared() > outer * outer) {
			// Move unit if possible.
			if (vaildSpawningPoints_.size() > 0) {
				Position p = vaildSpawningPoints_[randomInt(0, vaildSpawningPoints_.size() - 1)];
				float angle = calculateAnglePointToPoint(p, human.getPosition());
				State state(p, ORIGO, angle);
				unit.setState(state);
			}
			else {
				// Deactivate.
				unit.setActive(false);
				unit.setAwake(false);
			}
		}
	}
Example #20
0
	void UnitList::recreateLists(const VC2 &size)
	{
		VC2	mmin(-size.x, -size.y);
		VC2 mmax( size.x,  size.y);

		LinkedListIterator iter(allUnits);
		while (iter.iterateAvailable())
		{
			Unit *u = (Unit *)iter.iterateNext();
			if (u->getUnitListEntity() != NULL)
			{
				delete u->getUnitListEntity();
				u->setUnitListEntity(NULL);
			}
		}

		impl->tree.reset(new UnitQTree(mmin, mmax));

		iter = LinkedListIterator(allUnits);
		while (iter.iterateAvailable())
		{
			Unit *u = (Unit *)iter.iterateNext();
			//assert(u->getUnitListEntity() != NULL);
			//delete u->getUnitListEntity();

			float radius = UNIT_QTREE_RADIUS_HACK;
			// grow the radius for non-boned units only
			// (as boned units may have 15m radius or such because of changing animations)
			if (u->getUnitType()->getBonesFilename() == NULL)
			{
				if (u->getVisualObject() != NULL
					&& u->getVisualObject()->getStormModel() != NULL)
				{
					float radius2 = u->getVisualObject()->getStormModel()->GetRadius();
					if (radius2 > radius) radius = radius2;
				}
			}
			u->setUnitListEntity(new UnitListEntity());
			u->getUnitListEntity()->entity = impl->tree->insert(u, u->getPosition(), radius);
			u->getUnitListEntity()->lastUpdatePosition = u->getPosition();
		}

	}
Example #21
0
void AssetCollection::updateUnits(const float deltaT)
{
    ListNode<Unit*>* node;
    ListNode<Unit*>* temp;

    // release requested from previous frame, if any
    if(!m_UnitReleaseStack.empty())
    {
        Unit* u;
        node = m_UnitReleaseStack.headNode();
        while(node)
        {
            u = node->item;
            clearUnitArray((unsigned short)u->getPosition()->x, (unsigned short)u->getPosition()->y, u->getWidth(), u->getHeight());
            u->release();
            delete u;
            node = m_UnitReleaseStack.removeGetNext(node);
        }
    }

    // update units
    node = units.tailNode();
    while(node)
    {
        if(node->item->update(deltaT) == IAsset::RESULT_DELETEME)
        {
            // store next node to go
            temp = node;
            node = node->prev;
            // delete asset
            notifyAssetReleased(temp->item);

            //temp->item->release();
            //delete temp->item;
            m_UnitReleaseStack.pushHead(temp->item);

            // delete node
            units.remove(temp);
        }
        else
            node = node->prev;
    }
}
Example #22
0
//----------------------------------------------------------------------------------------------
bool StarCraftEntity::AttackEntity(TID p_targetEntityObjectId)
{
    Unit attacker = m_unit;
    Unit target;

    target = Broodwar->getUnit(p_targetEntityObjectId);

    if (!target)
        throw ItemNotFoundException(XcptHere);

    return attacker->attack(target->getPosition());
};
Example #23
0
	void ZombieGame::calculateValidSpawningPoints(Unit& human) {
		vaildSpawningPoints_.clear();
		float inner = 10;
		float outer = 200;
		Position humanPos = human.getPosition();
		for (Position p : spawningPoints_) {
			Position diff = p - humanPos;
			if (diff.LengthSquared() > inner*inner && diff.LengthSquared() < outer*outer) {
				// Spawningpoint is valid!
				vaildSpawningPoints_.push_back(p);
			}
		}
	}
sf::Vector2f sbe::Pursuit::use(Unit& unit)
{
	if (targetUnit.get() != nullptr)
	{
		float T = sbe::AdvMath::magnitude(unit.getPosition() - targetUnit->getPosition()) / targetUnit->getMaxVelocity();
		sf::Vector2f futurePosition = targetUnit->getPosition() + sbe::AdvMath::multiply(targetUnit->getVelocity(), T);

		setTarget(futurePosition);

		return Seek::use(unit);
	}
	return sf::Vector2f(0, 0);
}
Example #25
0
	void ZombieGame::unitDied(Unit& unit) {
		--nbrUnits_;

		Animation* dieAnimation = &humanDie_;
		if (unit.isInfected()) {
			++zombiesKilled_;
			dieAnimation = &zombieDie_;
		}

		activateFirstFreeSlot(graphicAnimations_, unit.getPosition(), unit.getDirection(), *dieAnimation);

		unit.setActive(false);
		unit.setAwake(false);
	}
Example #26
0
//----------------------------------------------------------------------------------------------
bool StarCraftModel::StarCraftEntity::IsTraining(TID p_traineeId) const
{
    Unit traineeObj = Broodwar->getUnit(p_traineeId);

    if (nullptr == traineeObj)
        throw ItemNotFoundException(XcptHere);

    return MathHelper::RectangleMembership(
        m_unit->getLeft(),
        m_unit->getTop(),
        m_unit->getRight() - m_unit->getLeft(),
        m_unit->getBottom() - m_unit->getTop(),
        traineeObj->getPosition().x,
        traineeObj->getPosition().y);
}
Example #27
0
	void ZombieGame::shot(Unit& shooter, float speed, float explodeTime, float damage, float explosionRadius, float force) {
		for (auto& missile : missiles_) {
			if (!missile.isActive()) {
				float x = shooter.getGrip().x;
				float y = shooter.getGrip().y;
				float angle = shooter.getDirection();
				float s = std::sin(angle);
				float c = std::cos(angle);
				Position release = Position(c * x - s * y, s * x + c * y);  // Rotates the vector.
				missile.create(shooter.getPosition() + release,
					angle, speed, explodeTime, damage, explosionRadius, force);
				// Only send one missile.
				break;
			}
		}
	}
/*---------------------------------------------------------------------*//**
	フレーム処理
**//*---------------------------------------------------------------------*/
void MapMod10221::exec(ExecRes* res, const ExecCtx* ec)
{
	SoundMngr* sndmng = Game::getGame()->getSoundManager(); ASSERT(sndmng != 0L);
	u16 musicidCur = (sndmng->getReservedMusicId() != 0) ? sndmng->getReservedMusicId() : sndmng->getCurrentPlayMusicId();
	{
		u16 musicidNew = musicidCur;

		// キャラクタの位置によって曲を変える
		Unit* unitMy = Game::getGame()->getMyParty()->pcUnit(MyParty::PC_MY);
		if(unitMy != 0L)
		{
			const Vector3F* posMy = unitMy->getPosition();
			///TRACE("> {%f,%f,%f}\n", posMy->x(), posMy->y(), posMy->z());
			if(posMy->z() > 0.0f)
			{
				// 門を出た
				if(_cntKeep < 0)	{	_cntKeep = 0;	}
				else				{	_cntKeep++;		}
			}
			else if(posMy->z() < 0.0f)
			{
				// 村に入った
				if(_cntKeep > 0)	{	_cntKeep = 0;	}
				else				{	_cntKeep--;		}
			}

			if(_cntKeep >= KEEPCNT_CHANGE_MUSIC)
			{
				musicidNew = GameSoundDef::BGM_106_FIELD;
			}
			else if(_cntKeep <= (- KEEPCNT_CHANGE_MUSIC))
			{
				musicidNew = GameSoundDef::BGM_103_VILLAGE;
			}
		}

		// 曲の変更
		if(musicidNew != musicidCur)
		{
			sndmng->playBgm(musicidNew, true, 1.0f, false, 60, 30, 0);
		}
	}

	MapMod10000::exec(res, ec);
}
Example #29
0
void UnitClass::gather(Unit unit)
{
	if(exists() && unit)
	{
		if(!unit->exists())
		{
			move(unit->getPosition());
			return;
		}
	
		if(unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field)
		{
			if(mUnit->getOrder() == BWAPI::Orders::MoveToMinerals || mUnit->getOrder() == BWAPI::Orders::WaitForMinerals || mUnit->getOrder() == BWAPI::Orders::MiningMinerals)
			{
				if(mUnit->getOrderTarget() == unit->mUnit)
					return;
			}
		}
		else if(unit->getType().isRefinery())
		{
			if(mUnit->getOrder() == BWAPI::Orders::Harvest1)
				return;
			else if(mUnit->getOrder() == BWAPI::Orders::MoveToGas || mUnit->getOrder() == BWAPI::Orders::WaitForGas || mUnit->getOrder() == BWAPI::Orders::HarvestGas)
			{
				if(mUnit->getOrderTarget() == unit->mUnit)
					return;
			}
		}
		else
			return;

		if(mUnit->getLastCommand().getType() == BWAPI::UnitCommandTypes::Gather && mUnit->getLastCommand().getTarget() == unit->mUnit)
		{
			if(mLastOrderExecuteTime >= BWAPI::Broodwar->getFrameCount())
				return;
		}

		if(mUnit->gather(unit->mUnit))
			mLastOrderExecuteTime = BWAPI::Broodwar->getFrameCount() + BWAPI::Broodwar->getRemainingLatencyFrames();
	}
}
Example #30
0
Unit* AI::detectEnemy(Unit& unit, std::list<Unit*>* Units){
	float sight = unit.getSight();
    float lowTheta = unit.getTheta()-sight;
    float upTheta = unit.getTheta()+sight;
    CIwFVec2 Pos = unit.getPosition()+unit.getVelocity();
    float minDist=1000;
    Unit *Enemy;
    for(std::list<Unit*>::iterator itr = Units->begin(); itr != Units->end(); itr++){
        Unit *temp = *itr;
        if(lowTheta <= temp->getTheta() <= upTheta){
            CIwFVec2 tempPos = temp->getPosition();
            float dist = sqrt((tempPos.x+Pos.x)*(tempPos.x+Pos.x)+(tempPos.y+Pos.y)*(tempPos.y+Pos.y));
            if (dist<=minDist) {
                minDist = dist;
                Enemy = temp;
            }
        }
    }
    return Enemy;

}