コード例 #1
0
//DONE
//given path --> find if next coordinate is outside of map
//not sure if i need to check for size of char array
static int isLegalPathToCamp(path destination) {
    assert(strlen(destination)  <  PATH_LIMIT);
    int isLegal = TRUE;
    int i = 0;
    coordinates oldxy;
    coordinates newxy;
    oldxy.x = 5;
    oldxy.y = 0;
    oldxy.direction = SOUTH_EAST;
    newxy = oldxy;
    //testing if is even legal path input
    while(destination[i] != '\0'  &&  i < PATH_LIMIT) {
        if(!(destination[i] == 'L' ||
             destination[i] == 'R' || destination[i] == 'B')) {
            isLegal = FALSE;
        }
        i++;
    }
    //code for checking size of char array
    //testing if path goes into water
    i = 0;
    while(isLegal == TRUE  &&  destination[i] != '\0'  &&
          i < PATH_LIMIT) {
        newxy = newCoords(newxy, destination[i]);
        newxy.direction = newDirection(newxy.direction,
                                       destination[i]);
        if(isInBounds(newxy) == FALSE) {
            isLegal = FALSE;
        }
        i++;
    }
    return isLegal;
}
コード例 #2
0
// create recursive compare function that utilizes DX[] 
// and DY[] to state true or false vaules. True continues 
// search, false ends the search at that index.
char* searchBoard(int x, int y, int location, char*** board, char*** sortedDictionary, int length, int rows, int cols, int i){

	char tempString[MAX_STRING_LENGTH];

	for (i = i; i < DX_SIZE; i++){

		// Checks if the location is inside the board.
		if (isInBounds(x, y, rows, cols) == 1){

			// Concatenate chars from the board on to tempString.
			// Run tempString
			//strcat(tempString, board[][]);

			// Returns the word from the word search if found
			// found in the dictionary.
			if (binaryCharSearch(sortedDictionary, tempString, length) == 1){
				return tempString;
			}
		}
	}

	// Recursively call the funciton until all possible moves have been checked.
	//return searchBoard(x, y, location, board, sortedDictionary, length, rows + DX[i], cols + DY[i], i);

	return "";
	
}
コード例 #3
0
void Image::setPixel(int r, int c, double val)
{
  if( isInBounds(r, c) )
    {
    m_pixels[r * m_numCols + c] = val;
    }
}
コード例 #4
0
unsigned int ConnectFour::Board::recursiveCheckMove(const CoordinateXY& coordinate, const Player& player, const Direction& direction) const
{
    const CoordinateXY& newCoordinate = coordinate + direction.coordinate();
    if(isInBounds(newCoordinate))
        return recursiveCheckMove(newCoordinate, player, direction) + 1;

    return 0;
}
コード例 #5
0
/** (private for tryXXX)
 * to see if the player is allowed to move there
 */
static int isFree(Uint8 x, Uint8 y) {
	return (isInBounds(x, y) &&
			(level->field[x][y] == BT_EMPTY ||
			level->field[x][y] == BT_ABOMB ||
			level->field[x][y] == BT_TRAP ||
			level->field[x][y] == BT_TRIGGERED) &&
			level->blocks[x][y] == BT_NULL);
}
コード例 #6
0
ファイル: Maze.cpp プロジェクト: SourKream/MazeSolver
void Maze::setVisited(Point pt)
{
    checkIndices(pt);
    if(isInBounds(pt))
        visited[pt.getRow()][pt.getColumn()] = true;
    DrawBox(pt.getColumn(), pt.getRow(), VISITED);
    XFlush(dsp);
    usleep(200000/Speed);
}
コード例 #7
0
ファイル: Room.cpp プロジェクト: Faianca/hikari
    const int Room::getAttributeAt(int tileX, int tileY) const {
        // Make coordinates relative
        tileX = tileX - getX();
        tileY = tileY - getY();

        if(isInBounds(tileX, tileY)) {
            return attr[tileX + (tileY * getWidth())];
        }

        return NO_TILE;
    }
コード例 #8
0
bool ConnectFour::Board::testMove(const Move& move) const
{
    if(!isInBounds(move))
        return false;

    unsigned int x = move.column();
    // The move comes in on top of the column, so its (size - 1) + 1
    unsigned int y = (unsigned int)m_board[x].size();

    return checkMove({x, y}, move.player());
}
コード例 #9
0
ファイル: Maze.cpp プロジェクト: SourKream/MazeSolver
void Maze::checkIndices(Point pt)
{
    if(!isInBounds(pt))
    {
        string err_msg;
        err_msg += "bad indices : row = ";
        err_msg += pt.getRow();
        err_msg += ", column = ";
        err_msg += pt.getColumn();
        printAndExit(err_msg);
    }
}
コード例 #10
0
bool ConnectFour::Board::addMove(const Move& move)
{
    if(!isInBounds(move))
        return false;

    m_solved = m_solved || testMove(move);
    m_board[move.column()].push_back(move.player());

    if(m_solved)
        m_winningPlayer = &(move.player());
    if(m_board[move.column()].size() == COLUMN_SIZE)
        ++m_filledColumns;

    return m_solved;
}
/********** d�lacement sur un point **********/ 
int itsHybridContinuousInteractingAntColony::antMoveTo( int antId, vector<double> aPoint )
{

  // v�ifie la pr�ence dans les bornes
  if( ! isInBounds(aPoint,this->getProblem()->boundsMinima(),this->getProblem()->boundsMaxima()) ) {
    // renvoi false, ne peut sortir de l'espace de recherche
    return 0;
  }
  
  // change la coordonn� de la fourmi
  antCurrentPoint[ antId ] = aPoint;
  
  // met �jour la valeur de la fonction objectif
  itsPoint p;
  p.setSolution( aPoint );
  antCurrentValue[ antId ] = evaluate( p ).getValues()[0];

  // renvoi true, la fourmi �boug�
  return 1;
}
コード例 #12
0
ファイル: Stage.cpp プロジェクト: Tirmenat/solara
void Stage::adjustUnits()
{
  bool topleft,topright,botleft,botright;
  
  for(int i = 0; i<units.size(); i++)
    {
      //      cout << "Needing to adjust unit" << endl;
      if(units[i]->isBullet())
	{
	  if(!isInBounds(units[i]->getx(), units[i]->gety()))
	    {

		  
		  //		  cout << "subtracting from hero's current bullets" << endl;
	      units[i]->setHealth(0);
	      continue;
	    }
	  else if(isOffScreen(units[i]))
	    {
	      units[i]->setHealth(0);
	      continue;
	    }
	}
      else
	{
	  topleft = topright = botleft = botright = 1;
	  //if topleft is in bounds
	  //if top right is in bounds
	  //if bottom left is in bounds
	  //if bottom right is in bounds
	  
	  for(int j =0; j<sqrt(((units[i]->getx()*units[i]->getx())+(units[i]->gety()*units[i]->gety())));j++)
	    {
	     
	      if(isInBounds(units[i]->getx(),units[i]->gety()))
		topleft = 0;
	      if(isInBounds(units[i]->getx()+SPRWIDTH,units[i]->gety()))
		topright = 0;
	      if(isInBounds(units[i]->getx(),units[i]->gety()+SPRLENGTH))
		botleft = 0;
	      if(isInBounds(units[i]->getx()+SPRWIDTH,units[i]->gety()+SPRLENGTH))
		botright = 0;
	      
	      if(topright || botright || botleft || topleft)
		{
		  if(topright)
		    {
		      if(botright)
			{
			  units[i]->setx(units[i]->getx()-1);
			}
		      if(topleft)
			{
			  units[i]->sety(units[i]->gety()+1);
			}
		      if(!botright && !topleft)
			{
			  units[i]->setx(units[i]->getx()-1);
			  units[i]->sety(units[i]->gety()+1);
			}
		    }
		  else if(topleft)
		    {
		      if(botleft)
			{
			  units[i]->setx(units[i]->getx()+1); 
			}
		      else
			{
			  units[i]->setx(units[i]->getx()+1);
			  units[i]->sety(units[i]->gety()+1);
			}
		    }
		  else if(botright)
		    {
		      if(botleft)
			{
			  units[i]->sety(units[i]->gety()-1);
			}
		      else
			{
			  units[i]->sety(units[i]->gety()-1);
			  units[i]->setx(units[i]->getx()-1);
			}
		    }
		  else
		    {
		      units[i]->sety(units[i]->gety()-1);
		      units[i]->setx(units[i]->getx()+1);
		    }
		}
	      else
		break;
	    }
	}      
    }
}
コード例 #13
0
ファイル: DFGArrayMode.cpp プロジェクト: boska/webkit
bool ArrayMode::permitsBoundsCheckLowering() const
{
    return DFG::permitsBoundsCheckLowering(type()) && isInBounds();
}
コード例 #14
0
ファイル: DFGArrayMode.cpp プロジェクト: boska/webkit
ArrayMode ArrayMode::refine(
    Graph& graph, CodeOrigin codeOrigin,
    SpeculatedType base, SpeculatedType index, SpeculatedType value,
    NodeFlags flags) const
{
    if (!base || !index) {
        // It can be that we had a legitimate arrayMode but no incoming predictions. That'll
        // happen if we inlined code based on, say, a global variable watchpoint, but later
        // realized that the callsite could not have possibly executed. It may be worthwhile
        // to fix that, but for now I'm leaving it as-is.
        return ArrayMode(Array::ForceExit);
    }
    
    if (!isInt32Speculation(index))
        return ArrayMode(Array::Generic);
    
    // Note: our profiling currently doesn't give us good information in case we have
    // an unlikely control flow path that sets the base to a non-cell value. Value
    // profiling and prediction propagation will probably tell us that the value is
    // either a cell or not, but that doesn't tell us which is more likely: that this
    // is an array access on a cell (what we want and can optimize) or that the user is
    // doing a crazy by-val access on a primitive (we can't easily optimize this and
    // don't want to). So, for now, we assume that if the base is not a cell according
    // to value profiling, but the array profile tells us something else, then we
    // should just trust the array profile.
    
    switch (type()) {
    case Array::Unprofiled:
        return ArrayMode(Array::ForceExit);
        
    case Array::Undecided:
        if (!value)
            return withType(Array::ForceExit);
        if (isInt32Speculation(value))
            return withTypeAndConversion(Array::Int32, Array::Convert);
        if (isFullNumberSpeculation(value))
            return withTypeAndConversion(Array::Double, Array::Convert);
        return withTypeAndConversion(Array::Contiguous, Array::Convert);
        
    case Array::Int32:
        if (!value || isInt32Speculation(value))
            return *this;
        if (isFullNumberSpeculation(value))
            return withTypeAndConversion(Array::Double, Array::Convert);
        return withTypeAndConversion(Array::Contiguous, Array::Convert);
        
    case Array::Double:
        if (flags & NodeBytecodeUsesAsInt)
            return withTypeAndConversion(Array::Contiguous, Array::RageConvert);
        if (!value || isFullNumberSpeculation(value))
            return *this;
        return withTypeAndConversion(Array::Contiguous, Array::Convert);
        
    case Array::Contiguous:
        if (doesConversion() && (flags & NodeBytecodeUsesAsInt))
            return withConversion(Array::RageConvert);
        return *this;
        
    case Array::SelectUsingPredictions: {
        base &= ~SpecOther;
        
        if (isStringSpeculation(base))
            return withType(Array::String);
        
        if (isArgumentsSpeculation(base))
            return withType(Array::Arguments);
        
        ArrayMode result;
        if (graph.hasExitSite(codeOrigin, OutOfBounds) || !isInBounds())
            result = withSpeculation(Array::OutOfBounds);
        else
            result = withSpeculation(Array::InBounds);
        
        if (isInt8ArraySpeculation(base))
            return result.withType(Array::Int8Array);
        
        if (isInt16ArraySpeculation(base))
            return result.withType(Array::Int16Array);
        
        if (isInt32ArraySpeculation(base))
            return result.withType(Array::Int32Array);
        
        if (isUint8ArraySpeculation(base))
            return result.withType(Array::Uint8Array);
        
        if (isUint8ClampedArraySpeculation(base))
            return result.withType(Array::Uint8ClampedArray);
        
        if (isUint16ArraySpeculation(base))
            return result.withType(Array::Uint16Array);
        
        if (isUint32ArraySpeculation(base))
            return result.withType(Array::Uint32Array);
        
        if (isFloat32ArraySpeculation(base))
            return result.withType(Array::Float32Array);
        
        if (isFloat64ArraySpeculation(base))
            return result.withType(Array::Float64Array);

        return ArrayMode(Array::Generic);
    }

    default:
        return *this;
    }
}
コード例 #15
0
void BossBot::update(Game *game){
	////////////////////////
	///////////////////////
	///////////////////////
	if(dead) {
		return;
	}
	// If hitpoints are 0, remove it
	if(hitPoints <= 0){
		setCurrentState(direction==1?DYING_RIGHT:DYING_LEFT);
		game->getGSM()->getSpriteManager()->addBotToRemovalList(this, 15);
		dead = true;
		game->getGSM()->goToLevelWon();
		return;
	}

	// Decrement frames since last attack
	cooldownCounter--;
	if(getCurrentState()==ATTACKING_RIGHT||getCurrentState()==ATTACKING_LEFT){
		if(this->getFrameIndex()==10)
			setCurrentState(direction==1?IDLE_RIGHT:IDLE_LEFT);
	}
	// If can attack, check if player in range.
	if(cooldownCounter <= 0){
		// If player is next to this bot, do something different
		int botX = getCurrentBodyX() * BOX2D_CONVERSION_FACTOR;
		int pX = game->getGSM()->getSpriteManager()->getPlayer()->getCurrentBodyX() * BOX2D_CONVERSION_FACTOR;

		// If the player is within the bots targeting area, go after the player
		if(isInBounds(pX)) {
			int botY = getCurrentBodyY() * BOX2D_CONVERSION_FACTOR;
			int pY = game->getGSM()->getSpriteManager()->getPlayer()->getCurrentBodyY() * BOX2D_CONVERSION_FACTOR;
			// Make sure the player is in the same y area
			if(std::abs(botY - pY) < 200){
				if (pX<botX)
					direction=-1;
				else 
					direction=1;
				cooldownCounter = attackCooldown;
				this->setCurrentState(direction==1?ATTACKING_RIGHT:ATTACKING_LEFT);
				// Seed
				AnimatedSpriteType *seedSpriteType = game->getGSM()->getSpriteManager()->getSpriteType(3);
				Seed *seed = new Seed(PROJECTILE_DESIGNATION, true);

				seed->setHitPoints(1);
				seed->setDamage(SEED_DAMAGE);
				seed->setSpriteType(seedSpriteType);
				seed->setAlpha(255);
				seed->setCurrentState(IDLE_LEFT);
				PhysicalProperties *seedProps = seed->getPhysicalProperties();
				seedProps->setX(botX);
				seedProps->setY(game->getGSM()->getWorld()->getWorldHeight() - botY);
				seedProps->setVelocity(0.0f, 0.0f);
				seedProps->setAccelerationX(0);
				seedProps->setAccelerationY(0);
				seed->setOnTileThisFrame(false);
				seed->setOnTileLastFrame(false);
				seed->affixTightAABBBoundingVolume();

				//create a physics object for the seed
				game->getGSM()->getBoxPhysics()->getPhysicsFactory()->createEnemyObject(game,seed,false);

				float difX = botX - pX;
				float difY = botY - pY;
				// Set the velocity of the seed
				float length = std::sqrt( (difX * difX) + (difY * difY) );

				// Normalize the distances
				difX /= length;
				difY /= length;

				// Scale distances to be x and y velocity
				difX *= PROJECTILE_VELOCITY;
				difY = difY*PROJECTILE_VELOCITY-10;
				seed->getPhysicsBody()->SetLinearVelocity(b2Vec2(-difX, -difY));

				game->getGSM()->getPhysics()->addCollidableObject(seed);
				game->getGSM()->getSpriteManager()->addBot(seed);
			}
		}
	}
	
	
	
	
	
	
	//////////////////////
	///////////////////////
	///////////////////////
	/*
	if(dead) {
		return;
	}
	// If hitpoints are 0, remove it
	if(hitPoints <= 0){
		game->getGSM()->goToLevelWon();
		game->getGSM()->getSpriteManager()->addBotToRemovalList(this, 0);
		dead = true;
		return;
	}

	// Decrement frames since last attack
	cooldownCounter--;
	// If can attack, check if player in range.
	if(cooldownCounter <= 0){
		// If player is next to this bot, do something different
		int botX = getCurrentBodyX() * BOX2D_CONVERSION_FACTOR;
		int pX = game->getGSM()->getSpriteManager()->getPlayer()->getCurrentBodyX() * BOX2D_CONVERSION_FACTOR;

		// If the player is within the bots targeting area, go after the player
		if(isInBounds(pX)) {
			int botY = getCurrentBodyY() * BOX2D_CONVERSION_FACTOR;
			int pY = game->getGSM()->getSpriteManager()->getPlayer()->getCurrentBodyY() * BOX2D_CONVERSION_FACTOR;
			// Make sure the player is in the same y area
			if(std::abs(botY - pY) < 200){
				cooldownCounter = attackCooldown;

				// Seed
				AnimatedSpriteType *seedSpriteType = game->getGSM()->getSpriteManager()->getSpriteType(3);
				Seed *seed = new Seed(PROJECTILE_DESIGNATION, true);
				seed->setHitPoints(1);
				seed->setDamage(SEED_DAMAGE);
				seed->setSpriteType(seedSpriteType);
				seed->setAlpha(255);
				seed->setCurrentState(IDLE_LEFT);
				PhysicalProperties *seedProps = seed->getPhysicalProperties();
				seedProps->setX(botX);
				seedProps->setY(game->getGSM()->getWorld()->getWorldHeight() - botY);
				seedProps->setVelocity(0.0f, 0.0f);
				seedProps->setAccelerationX(0);
				seedProps->setAccelerationY(0);
				seed->setOnTileThisFrame(false);
				seed->setOnTileLastFrame(false);
				seed->affixTightAABBBoundingVolume();

				//create a physics object for the seed
				game->getGSM()->getBoxPhysics()->getPhysicsFactory()->createEnemyObject(game,seed,true);

				// Set the velocity of the seed
				seed->getPhysicsBody()->SetLinearVelocity(b2Vec2(attackSpeed, 0.5));

				game->getGSM()->getPhysics()->addCollidableObject(seed);
				game->getGSM()->getSpriteManager()->addBot(seed);
			}
		}
	}
	*/
}
コード例 #16
0
void tryRight() {if(isInBounds(px, py) && isFree(px + 1, py)) px++;}
コード例 #17
0
ファイル: Maze.cpp プロジェクト: SourKream/MazeSolver
bool Maze::isOpen(Point pt)
{
    checkIndices(pt);
    return isInBounds(pt) && squares[pt.getRow()][pt.getColumn()] == Maze::OPEN;
}
コード例 #18
0
ファイル: Maze.cpp プロジェクト: SourKream/MazeSolver
bool Maze::isVisited(Point pt)
{
    checkIndices(pt);
    return isInBounds(pt) && visited[pt.getRow()][pt.getColumn()];
}
コード例 #19
0
ファイル: Grid.cpp プロジェクト: uttumuttu/niwa
    /**
     * The algorithm used is fast marching reinitialization.
     */
    void Grid::reinitialize() {
        struct Element {
            vec3i position;

            float distance;
            float sign;
            float signedDistance;

            Element(vec3i const& position_, float distance_)
                : position(position_), distance(distance_) {
                sign = distance > 0.0f ? 1.0f : -1.0f;

                signedDistance = std::abs(distance);
            }

            bool operator < (Element const& rhs) const {
                return signedDistance > rhs.signedDistance;
            }
        };

        std::priority_queue<Element> elements;

        for(int z=0; z<dimensions_.z; ++z)
        for(int y=0; y<dimensions_.y; ++y)
        for(int x=0; x<dimensions_[0]; ++x) {
            int i = elementIndex(vec3i(x,y,z));

            if(!isnan(values_[i])) {
                elements.push(
                    Element(vec3i(x,y,z),values_[i]));
            }
        }

        if(elements.empty()) {
            int nVoxels = dimensions_[0] * dimensions_.y * dimensions_.z;

            for(int i=0; i<nVoxels; ++i) {
                values_[i] = std::numeric_limits<float>::infinity();
            }
        }

        while(!elements.empty()) {
            Element element = elements.top();
            elements.pop();

            if(element.distance != values_[elementIndex(element.position)]) {
                // invalidated
                continue;
            }

            for(int dz=-1; dz<=1; ++dz)
            for(int dy=-1; dy<=1; ++dy)
            for(int dx=-1; dx<=1; ++dx) {
                if(dx==0 && dy==0 && dz==0) {
                    continue;
                }

                vec3i position = element.position + vec3i(dx,dy,dz);

                if(!isInBounds(position, vec3i(0,0,0), dimensions_)) {
                    continue;
                }

                vec3f direction(
                    voxelDimensions_[0] * dx,
                    voxelDimensions_.y * dy,
                    voxelDimensions_.z * dz);

                float candidateDistance =
                    element.distance 
                    + element.sign * direction.length();

                int i = elementIndex(position);

                if(isnan(values_[i])
                    || (std::abs(candidateDistance) < std::abs(values_[i])
                    && candidateDistance * values_[i] > 0)) {
                    values_[i] = candidateDistance;

                    elements.push(
                        Element(position,candidateDistance));
                }
            }
        }
    }
コード例 #20
0
ReturnType SendCouplingMDCommand::executeProcessing()
{
	logger->debug() << "starting SendCouplingMDCommand::executeProcessing" << std::endl;
	CouplingInformationType* couplingInfo = (CouplingInformationType*) this->getData(0);
	Simulation* theSim = (Simulation*) this->getData(1);
	ParticleContainer* moleculeContainer = theSim->getMolecules();

	if (transferContainer == NULL)
	{
		transferContainer = new std::vector<Molecule>[couplingInfo->numberOfBoundaries];
	}

/*	int dim = borderToLook / 2;
	int dir = borderToLook % 2;*/
	int dim, dir;
	outmin = 0;
	outmax = 0;
	double rmin =  moleculeContainer->getBoundingBoxMin(dim);
	double rmax =  moleculeContainer->getBoundingBoxMax(dim);

	logger->debug() << "dim is " << dim << ", dir is " << dir << std::endl;
	logger->debug() << "halo is " << moleculeContainer->get_halo_L(dim) << std::endl;
	Molecule* currentMolecule;

	double low_limit = rmin; // particles below this limit have to be copied or moved to the lower process
	double high_limit = rmax; // particles above(or equal) this limit have to be copied or moved to the higher process

	currentMolecule = moleculeContainer->begin();

	logger->debug() << "low_limit: " << low_limit << " / high_limit: " << high_limit << std::endl;
	while(currentMolecule!=moleculeContainer->end()){
		for (int i = 0; i < couplingInfo->numberOfBoundaries; i++)
		{
			CouplingBoundary currentBoundary = couplingInfo->boundaries[i];
			//const double& rd=currentMolecule->r(dim);
			const double& rd = currentMolecule->r(currentBoundary.outFlowDirection);
			const double& ro1 = currentMolecule->r(currentBoundary.otherDirection[0]);
			const double& ro2 = currentMolecule->r(currentBoundary.otherDirection[1]);
			if ((currentBoundary.lowerHigher == 1) && (rd > high_limit) && isInBounds(ro1,ro2, &currentBoundary))
			{
				outmax++;
				transferContainer[i].push_back(*currentMolecule);
				currentMolecule = moleculeContainer->deleteCurrent ();
				break;
			}
			else if ((currentBoundary.lowerHigher == 0) && (rd < low_limit) && isInBounds(ro1,ro2, &currentBoundary))
			{
				transferContainer[i].push_back(*currentMolecule);
				currentMolecule = moleculeContainer->deleteCurrent();
				outmin++;
				break;
			}
			else
			{
				currentMolecule = moleculeContainer->next();
			}
		}
	}
	logger->debug() << "outmin["<< dim << "] = " << outmin << std::endl;
	logger->debug() << "outmax["<< dim << "] = " << outmax << std::endl;
	//logger->debug() << "there are now " << transferContainer.size() << " molecules to transfer " << std::endl;
	if (getStepInterval() > 0)
	{
		return REPETITION_REQUESTED;
	}
	else
	{
		return EXECUTED;
	}

}
コード例 #21
0
void tryUp()    {if(isInBounds(px, py) && isFree(px, py - 1)) py--;}
コード例 #22
0
ファイル: Maze.cpp プロジェクト: SourKream/MazeSolver
bool Maze::isWall(Point pt)
{
    checkIndices(pt);
    return isInBounds(pt) && squares[pt.getRow()][pt.getColumn()] == Maze::WALL;
}
コード例 #23
0
ファイル: CThreatMap.cpp プロジェクト: Error323/E323AI
void CThreatMap::update(int frame) {
	static const unitCategory catsCanShootGround = ASSAULT|SNIPER|ARTILLERY|SCOUTER/*|PARALYZER*/;

	if ((frame - lastUpdateFrame) < MULTIPLEXER)
		return;

	const bool isWaterMap = !ai->gamemap->IsWaterFreeMap();
	std::list<ThreatMapType> activeTypes;
	std::list<ThreatMapType>::const_iterator itMapType;

	reset();

	int numUnits = ai->cbc->GetEnemyUnits(&ai->unitIDs[0], MAX_UNITS_AI);

	/* Add enemy threats */
	for (int i = 0; i < numUnits; i++) {
		const int uid = ai->unitIDs[i];
		const UnitDef* ud = ai->cbc->GetUnitDef(uid);

		if (ud == NULL)
			continue;

		const UnitType* ut = UT(ud->id);
		const unitCategory ecats = ut->cats;

		if ((ecats&ATTACKER).none() || ai->cbc->IsUnitParalyzed(uid)
		|| ai->cbc->UnitBeingBuilt(uid))
			continue; // ignore unamred, paralyzed & being built units

		if ((ecats&AIR).any() && (ecats&ASSAULT).none())
			continue; // ignore air fighters & bombers

		// FIXME: using maxWeaponRange below (twice) is WRONG; we need
		// to calculate different max. ranges per each threatmap layer

		// FIXME: think smth cleverer
		if (ud->maxWeaponRange > MAX_WEAPON_RANGE_FOR_TM)
			continue; // ignore units with extra large range

		const float3 upos = ai->cbc->GetUnitPos(uid);

		activeTypes.clear();

		if ((ecats&ANTIAIR).any() && upos.y >= 0.0f) {
			activeTypes.push_back(TMT_AIR);
		}

		if (((ecats&SEA).any() || upos.y >= 0.0f)
		&&  ((ecats&ANTIAIR).none() || (catsCanShootGround&ecats).any())) {
			activeTypes.push_back(TMT_SURFACE);
		}

		if (isWaterMap && (ecats&TORPEDO).any()) {
			activeTypes.push_back(TMT_UNDERWATER);
		}

		if (activeTypes.empty())
			continue;

		const float uRealX = upos.x / PATH2REAL;
		const float uRealZ = upos.z / PATH2REAL;
		const float  range = (ud->maxWeaponRange + 100.0f) / PATH2REAL;
		float       powerT = ai->cbc->GetUnitPower(uid);
		const float  power = (ecats&COMMANDER).any() ? powerT/20.0f : powerT;
		float3 pos(0.0f, 0.0f, 0.0f);

		const int R = (int) ceil(range);
		for (int z = -R; z <= R; z++) {
			for (int x = -R; x <= R; x++) {
				pos.x = x;
				pos.z = z;
				if (pos.Length2D() <= range) {
					pos.x += uRealX;
					pos.z += uRealZ;
					const int mx = int(round(pos.x));
					const int mz = int(round(pos.z));
					if (isInBounds(mx, mz)) {
						for (itMapType = activeTypes.begin(); itMapType != activeTypes.end(); ++itMapType) {
							int id = ID(mx, mz);
							maps[*itMapType][id] += power;
							maxPower[*itMapType] = std::max(maps[*itMapType][id], maxPower[*itMapType]);
						}
					}
				}
			}
		}

		/*
		for (itMapType = activeTypes.begin(); itMapType != activeTypes.end(); ++itMapType) {
			maxPower[*itMapType] = std::max<float>(power, maxPower[*itMapType]);
		}
		*/
	}

#if !defined(BUILDING_AI_FOR_SPRING_0_81_2)
	if (ai->cb->IsDebugDrawerEnabled()) {
		std::map<ThreatMapType, int>::iterator i;
		for (i = handles.begin(); i != handles.end(); ++i) {
			float power = maxPower[i->first];
			// normalize the data...
			for (int j = 0, N = X*Z; j < N; j++)
				maps[i->first][j] /= power;
			// update texturemap
			ai->cb->DebugDrawerUpdateOverlayTexture(i->second, maps[i->first], 0, 0, X, Z);
			// restore the original data...
			for (int j = 0, N = X*Z; j < N; j++)
				maps[i->first][j] *= power;
		}
	}
#endif

	if (drawMap != TMT_NONE)
		visualizeMap(drawMap);

	lastUpdateFrame = frame;
}
コード例 #24
0
void tryDown()  {if(isInBounds(px, py) && isFree(px, py + 1)) py++;}
コード例 #25
0
ファイル: gfx2d.c プロジェクト: zx96/xt3ds
void drawPixelSafe(screen scr, u16 x, u16 y, color clr)
{
	if (!isInBounds(scr, x, y)) return;

	drawPixel(scr, x, y, clr);
}
コード例 #26
0
void tryLeft()  {if(isInBounds(px, py) && isFree(px - 1, py)) px--;}