void EnemyShip::updateAI(osg::Vec3f _playerPos, std::list<Projectile>& _missiles, osg::ref_ptr<osg::MatrixTransform> _mSceneTrans, float _dt)
{
	//std::cout << "enemypos = " << getPos().x() << ", " << getPos().y() << ", " << getPos().z() << std::endl;

	osg::Vec3f diffVec = _playerPos - getPos();
	osg::Quat tempQuat = getOrientation();
	tempQuat.makeRotate(getDir(), diffVec);
	setDir(diffVec / diffVec.length());
	
	if (diffVec.length() > 1000.0f)
		translate(getDir()*5.0f);
	else {

	}
	
	rotate(tempQuat);

	tempQuat = getOrientation();
	osg::Quat tempQuat2;
	tempQuat2.makeRotate(tempQuat * osg::Vec3f(0.0, 1.0, 0.0), getDir());
	tempQuat = tempQuat * tempQuat2;
	
	if (attackCooldown <= 0.0) {
		std::cout << "Enemy Laser!" << std::endl;
		_missiles.push_back(Projectile((std::string)("Laser"), getPos() + tempQuat * osg::Vec3f(0.0, 450.0, 0.0), getDir(), tempQuat, (std::string)("models/skottg.ive"), _mSceneTrans, 50, 4000, false));
		attackCooldown = 8.0;
	}
	else
		attackCooldown -= _dt;
}
Esempio n. 2
0
void Player::updateProjectiles(sf::Time elapsedTime)
{
    timeSinceLastShot += elapsedTime;

    int i = 0;
    for (auto &projectile : projectiles)
    {
        if (projectile.valid)
        {
            projectile.update(elapsedTime);
            i++;
        }
        else
        {
            projectiles.erase(projectiles.begin() + i);
        }
    }

    if (controls & 0x10  && health > 0)
    {
        if(timeSinceLastShot.asMilliseconds() > 200 && ammo > 0)
        {
            timeSinceLastShot = sf::Time::Zero;
            auto pos = this->boundingBox.getPosition() + sf::Vector2f(boundingBox.width /2, boundingBox.height / 2);
            projectiles.push_back(Projectile(pos, 1000, this->rotation, 1000, 0, playerId));
            ammo--;
        }
    }
}
Esempio n. 3
0
void Equipment::use_ammo(int amnt) {
	projectile_amnt -= amnt;
	if (projectile_amnt <= 0) {
		projectile = Projectile(-1);
		projectile_amnt = 0;
	}
}
Esempio n. 4
0
AstralEntity::AstralEntity()
{
	position.x = 0.0;
	position.y = -1.5;
	position.z = 0.0;
	direction.x = 1.0;
	direction.y = 1.0;
	direction.z = 1.0;
	acceleration.x = 0.5;
	acceleration.y = 0.5;
	acceleration.z = 0.0;
	velocity.x = 1.0;
	velocity.y = 1.0;
	velocity.z = 0.0;
	friction.x = 1.577;
	friction.y = 1.577;
	segment1.x = position.x + 0.2;
	segment1.y = position.y + 0.2;
	segment1.z = 0.0;
	segment2.x = position.x - 0.2;
	segment2.y = position.y + 0.2;
	segment2.z = 0.0;
	XPos = 0.0;
	YPos = 0.0;
	HDirection = 1.0;
	VDirection = 1.0;
	health = 100;
	shields = 100;
	score = 0;
	ammoIndex = 0;
	maxshots = 10;
	alive = true;
	//velocity = 1;
	velocityX = 1.0;
	velocityY = 1.0;
	accelerationX = 1.75;
	accelerationY = 1.75;
	frictionX = 1.577;
	frictionY = 1.577;
	isStatic = false;
	collideBottom = false;
	collideLeft = false;
	collideRight = false;
	collideTop = false;
	scaleFactor = 1.0;
	for (int i = 0; i < 10; i++) {
		shots.push_back(Projectile());
	}
	//shots[ammoIndex].width = width;
	//shots[ammoIndex].height = height;
	/*shots[ammoIndex].position.y = position.y;
	shots[ammoIndex].position.x = position.x;*/
	shots[ammoIndex].direction.x = direction.x;
	shots[ammoIndex].direction.y = 1.0;
	//width = 1.0;
	//height = 1.0;
	wins = 0;
}
Esempio n. 5
0
void testApp::fire(int player) {
	Player& me = players[player];
	//cout << "players (0: " << players[0].life << "," << players[0].lastId << "," << players[0].position << ")" << endl;
	//cout << "players (1: " << players[1].life << "," << players[1].lastId << "," << players[1].position << ")" << endl;
	if(me.life > 0) {
		Player& you = players[otherPlayer(player)];
		ofVec2f position = me.position;
		ofVec2f velocity = you.position - me.position;
		projectiles.push_back(Projectile(player, position, velocity));
	}
}
Esempio n. 6
0
void Character::Shoot()
{
	for (int i = 0; i < ARRAY_SIZE(assocProjectiles); i++)
	{
		if (assocProjectiles[i].alive != true)
		{
			assocProjectiles[i] = Projectile(pos, direction, objName);
			assocProjectiles[i].LoadSprite();
			return;
		}
	}
}
Esempio n. 7
0
Projectile * Player::CreateBullets(int a_iArraySize)
{
	Bullets = new Projectile[a_iArraySize];

	for(int i = 0; i < a_iArraySize; i++)
	{
		Bullets[i] = Projectile();
		Bullets[i].Create("./images/Projectile.png");
	}

	return Bullets;
}
Esempio n. 8
0
Projectile spawnProjectile(Vec3Df direction)
{
	Vec3Df spawnPos = character.getAngleRefPos();
	direction.normalize();
	spawnPos += direction * character.getArmRadius();

    Projectile projectile = Projectile(spawnPos, direction);
	projectile.movementSpeed = 3.0;
	projectile.width = 0.5;
	projectile.height = 0.5;

	projectiles.push_back(projectile);
	return projectile;
}
Esempio n. 9
0
void SSProjectiles::CreateProjectile( Entity shooter, Entity target )
{
    Projectile* projectile = nullptr;

    for ( auto& it : m_Projectiles )
        if ( it.Active == false )
            projectile = &it;

    if ( projectile == nullptr )
    {
        //create new projectile
        m_Projectiles.push_back( Projectile( ) );
        projectile = &m_Projectiles.back( );
        projectile->Light = gfx::Light();
        projectile->Light.Position = glm::vec3( FLT_MIN );
    }
    else
    {
        //reuse projectile
        projectile->Light = gfx::Light();
        projectile->Light.Position = glm::vec3( FLT_MIN );
    }

    projectile->Effect = nullptr;

    SetWeaponPropertiesToProjectile( GetDenseComponent<WeaponComponent>( shooter ), projectile );

    projectile->Position = GetDenseComponent<PlacementComponent>( shooter )->Position;
    projectile->Scale		= glm::vec3( 1.0f );
    projectile->Color = GetDenseComponent<ColourComponent>( shooter )->Colour * 3.0f; // TODODP: Find another way of intensifying the color

    projectile->Origin		= projectile->Position;
    projectile->Destination = GetDenseComponent<PlacementComponent>( target )->Position;

    glm::vec3 distance		= projectile->Destination - projectile->Position;

    projectile->Velocity	= glm::normalize( distance ) * projectile->Speed;

    projectile->TimeLeft	= glm::length( distance ) / projectile->Speed;
    projectile->TimeToLive	= projectile->TimeLeft;

    projectile->Active		= true;
    projectile->Target		= target;
    projectile->OwnerID		= GetDenseComponent<OwnerComponent>( GetDenseComponent<ChildComponent>( shooter )->Parent )->OwnerID;

    SetSpecificProjectileProperties( projectile, distance );
}
Esempio n. 10
0
void SwampMonster::attack()
{
	Vec3d playerPos = game->getPlayer()->getPosition() - mPosition;

	//Vec2d angle(atan2(playerPos.X-mPosition.X, playerPos.Z-mPosition.Z));

	playerPos.normalize();

	playerPos /= 8;

	//range.setLength(1.0);

	game->getEntityManager()->add(New Projectile(mPosition,playerPos,game->getAnimationManager()->get("fireball"),Vec2d(5,10),ENTITY_ATTACK_ENEMY));

	speak(getAttackSound());
	game->getSoundEngine()->play3DSound(game->getResourceManager()->get("flame_attack"),mPosition);
}
Esempio n. 11
0
Ak47::Ak47()
	: Weapon(10,1.2,30,30,90)
{
	lastReload = 0;
	lastShoot = 0;

	bullet = Projectile("resource/sprites/bullet2.bmp", 350,18,10);

	sprite = al_load_bitmap("resource/weapons/ak47.bmp");
	if(!sprite)
	{
		std::cout<<"Erro no sprite da Ak47"<<std::endl;
		return;
	}

	width = al_get_bitmap_width(sprite);
	height = al_get_bitmap_height(sprite);

	al_convert_mask_to_alpha(sprite,al_map_rgb(255,0,255));

	aShootSound = al_load_sample("resource/sounds/ak47.wav");
	if(!aShootSound)
	{
		std::cout<<"Erro no audio de shoot"<<std::endl;
		return;
	}

	aReloadSound = al_load_sample("resource/sounds/reload.wav");
	if(!aReloadSound)
	{
		std::cout<<"Erro no audio reload"<<std::endl;
		return;
	}


}
Esempio n. 12
0
void Simulation::updatePlayers() {
  /*NOTE: The Simulation behaves as if events during a turn happen simultaneous.
   * That way the simulation is deterministic, even though (partial) events may
   * occur in an arbitrary order. This is archived by applying types of event in
   * a particular order. E.g. player movements never influence each other.
   * Collisions never influence each other. But movement influences Collision.
   * Therefor if movement and collision were interleaved, the order of events
   * would matter. By splitting movement and collision, the order of events does
   * not matter.
   * If an event can influence events of its type, this system won’t work. One
   * solution to this problem is to split the event in parts, that influence
   * each other but not themselves.
   */

  // set vision for all players
  for (auto &player : players) {
    check_scan(player.second);
  }

  // Player Actions(Movement)
  for (auto &player : players) {
    player.second.update();
  }

  // resolve Player Actions(Shooting)
  for (auto &player : players) {
    // see if any player wants to shoot
    if (player.second.shooting) {
      // reset the shooting flag
      player.second.shooting = false;
      // calculate the direction in which the Robot shoots
      double direction =
          player.second.getRotation() + player.second.getTurretAngle();
      Vector_d porjectilePosition = player.second.getPosition();
      // make sure we create the Projectile outside the player
      porjectilePosition += Vector_d::polar(
          direction,
          Vector_d(rules.robot_size.x, rules.projectile_size.x).magnitude());
      // create the Projectile
      projectiles.push_back(
          Projectile(rules, porjectilePosition, direction, player.first));
    }
  }

  // resolve Player collision
  for (auto &player : players) {
    // check collision between playeres
    // NOTE: currently we check each pair of players twice, once for
    // Collision(A,B) and once for Collision(B,A).
    for (auto const &player2 : players) {
      if (&player == &player2) {
        // don't check collision with self.
        continue;
      }
      if (Collision(player.second, player2.second)) {
        collisionSignal(player.first, player2.first);
        player.second.takeDamage(rules.collision_damage);
      }
    }
  }

  // resolve out-of-Bound events
  for (auto &player : players) {
    // check if any player is outside the arena
    Vector_d pos = player.second.getPosition();
    if (pos.x > rules.arena_size.x || pos.y > rules.arena_size.y || pos.x < 0 ||
        pos.y < 0) {
      outOfBoundsSignal(player.first);
      player.second.takeDamage(rules.collision_damage);
    }
  }

  // resolve collision between players and projectiles
  for (auto &player : players) {
    // check collision between player and projectile
    for (auto projectile = projectiles.begin();
         projectile != projectiles.end();) {
      Collision collision(player.second, *projectile);
      if (collision) {
        // deal damage to the player
        player.second.takeDamage(rules.projectile_damage);
        hitSignal(player.first, projectile->owner);
        // remove projectile, and advance the iterator
        projectile = projectiles.erase(projectile);
      } else {
        // advance the iterator
        ++projectile;
      }
    }
  }
}
Esempio n. 13
0
void ProjectileList::add(float energy, float x, float y, float xSpeed, float ySpeed, int type, char origin){
    pVector.push_back(Projectile(energy,window,x,y,xSpeed,ySpeed,type,time,currentID,&projTexture,origin));
    currentID++;
}
Esempio n. 14
0
//Main function
int main(int argc, char* argv[])
{
  /*
    -----
    // INITIALIZATION
    -----
  */

  //Seed RNG
  srand(time(NULL));
  
  //Initialize all SDL subsystems
  if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
      return 1;
    }

  //Initialize SDL_TTF
  TTF_Init();
  TTF_Font * planetFont = TTF_OpenFont("corbel.ttf", 20);

  //Set up the screen
  SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);

  //Make sure screen set up
  if (screen == NULL)
    {
      return false;
    }

  //Set the window caption
  SDL_WM_SetCaption("GAEM", NULL);

  //Create an event manager
  SDL_Event event;

  //Store keystates
  Uint8* keystates;

  //Set up camera
  SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
  float camerax = 0;
  float cameray = 0;

  /*
    -----
    GAME SETUP
    -----
  */

  //Set up ship stats
  std::vector<ShipStats> shipstats(10);
  for (int i = 0; i < 10; i++)
    {
      shipstats[i].attack = i+1;
      shipstats[i].defense = i+1;
      shipstats[i].speed = DEFAULT_FLEET_SPEED;
      shipstats[i].interceptRange = 200;
      shipstats[i].interceptDamage = 0.1;
      shipstats[i].interceptCD = 250;
    }

  //Set up ship type 1: Heavy ship
  shipstats[1].attack = 3;
  shipstats[1].defense = 2;
  shipstats[1].speed = DEFAULT_FLEET_SPEED/2;

  //Set up ship type 2: Fiery attack ship
  shipstats[2].attack = 2;
  shipstats[2].defense = 1;
  shipstats[2].speed = DEFAULT_FLEET_SPEED*1.25;

  //Set up buildings and building rules
  std::list<Building> buildings;
  std::vector<std::list<Building*> > buildRules;
  buildRules.resize(2);
  SDL_Surface* b01 = loadImage("b01.png");
  SDL_Surface* bc01 = loadImage("bc01.png");
  SDL_Surface* b02 = loadImage("b02.png");
  SDL_Surface* bc02 = loadImage("bc02.png");
  buildings.push_back(Building(b01, bc01, "build 0 2")); //0
  buildings.push_back(Building(b02, bc02, "fire damage 2 1")); //1
  buildings.push_back(Building(b01, bc01, "build 1 4")); //2
  buildings.push_back(Building(b01, bc01, "build 2 2")); //3
  buildings.push_back(Building(b02, bc02, "aura damage 1 total")); //4

  //0
  std::list<Building>::iterator bi = buildings.begin();
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //1
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(10000);
  bi->setRange(250);
  bi++;

  //2
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //3
  buildRules[1].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //4
  buildRules[1].push_back(&(*bi));
  bi->setBuildTime(10000);
  bi->setRange(200);
  bi->setCD(1000);

  //Building images are now in rotation caches
  SDL_FreeSurface(b01);
  SDL_FreeSurface(bc01);
  SDL_FreeSurface(b02);
  SDL_FreeSurface(bc02);

  //Create a list of planets
  std::list<Planet> planets;

  //The standard rate of production of basic ship 0
  float ship0rate = 1.0;

  //The array of indicators
  SDL_Surface* indicator[3];
  indicator[1] = loadImage("selectorb.png");
  indicator[2] = loadImage("selectorr.png");
  
  SDL_Surface* planet0img = loadImage("planet0.png");
  SDL_Surface* planet1img = loadImage("planet1.png");
  SDL_Surface* planet1_1img = loadImage("planet1-1.png");

  //Create the planets at random
  //First, create two home planets
  std::vector<int> homestart;
  homestart.resize(1,3);
  planets.push_back(Planet(planet0img, 1.0,
			   Vec2f(rand()%100, 100 + rand()%(LEVEL_HEIGHT-200)), 0));
  planets.back().setOwner(1, indicator);
  planets.back().setShipRate(0, ship0rate);
  planets.back().setRotSpeed(M_PI/20);
  planets.back().addShips(3, 0);
  planets.push_back(Planet(planet0img, 1.0,
			   Vec2f(LEVEL_WIDTH-(2*UNSCALED_PLANET_RADIUS)-(rand()%100),
				 100 + rand()%(LEVEL_HEIGHT-200)), 0));
  planets.back().setOwner(2, indicator);
  planets.back().setShipRate(0, ship0rate);
  planets.back().setRotSpeed(M_PI/20);
  planets.back().addShips(3, 0);

  //Now repeatedly create planets until either a target density is reached
  //or we go too many tries without finding a spot for a new planet.
  char tries = 0;
  char maxTries = 10;
  double density = 0.13;
  double totalSize = LEVEL_WIDTH*LEVEL_HEIGHT;
  double currentSize = M_PI*UNSCALED_PLANET_RADIUS*UNSCALED_PLANET_RADIUS*2;
  double spacing = 23;
  
  while (currentSize/totalSize < density && tries < maxTries)
    {
      //Create a new planet at a completely random location with a random size
      //For now, make half normal and half volcanic
      float psize = (double(rand())/double(RAND_MAX))*0.7 + 0.5;
      Planet p(planet0img, psize,
               Vec2f(rand()%(LEVEL_WIDTH-int(2*UNSCALED_PLANET_RADIUS*psize)),
                     rand()%(LEVEL_HEIGHT-int(2*UNSCALED_PLANET_RADIUS*psize))), 0);;
      if (rand()%2 == 0)
        {
          p.setType(0);
          p.setImage(planet0img);
        }
      else
        {
          p.setType(1);
          p.setImage(planet1img);
        }

      //Make sure it doesn't collide with any other planets
      bool skip = false;
      for (planetIter pi = planets.begin(); pi != planets.end(); pi++)
	{
	  Vec2f ppos = p.pos()+Vec2f(UNSCALED_PLANET_RADIUS*p.size(),UNSCALED_PLANET_RADIUS*p.size());
	  Vec2f pipos = pi->pos()+Vec2f(UNSCALED_PLANET_RADIUS*pi->size(),UNSCALED_PLANET_RADIUS*pi->size());
	  if ((pipos-ppos).length() <
	      p.size()*UNSCALED_PLANET_RADIUS +
	      pi->size()*UNSCALED_PLANET_RADIUS + spacing)
	    {
	      //There's a collision. Increment tries and try again
	      tries++;
	      skip = true;
	      break;
	    }
	}
      if (skip) continue;

      //At this point, we know there's no collision. Reset tries
      tries = 0;

      //Add a few more random attributes
      p.setOwner(0, indicator);
      p.setShipRate(0, ship0rate);
      p.setRotSpeed((fmod(rand(),M_PI)/5) - M_PI/10);
      p.setDifficulty(p.size()*20 + rand()%15 - 9);

      //Add this planet to the current size
      currentSize += M_PI*(UNSCALED_PLANET_RADIUS*p.size())*(UNSCALED_PLANET_RADIUS*p.size());

      //Add it to the list
      planets.push_back(p);
    }
  
  //Set up fleet list
  std::list<Fleet> fleets;

  //Set up projectile list
  std::list<Projectile> projectiles;

  //Filler to act as NULL
  planetIter planNull;

  //The currently selected planet
  planetIter selectPlanet = planNull;

  //Set up AI
  std::list<GalconAI> ai;

  //For now, AI controls player 2
  GalconAISettings aiSet;
  aiSet.attackFraction = .8;
  aiSet.surplusDefecitThreshold = .25;
  aiSet.attackExtraNeutral = .2;
  aiSet.attackExtraEnemy = .7;
  aiSet.perPlanetAttackStrength = .5;
  aiSet.delay = 200;
  aiSet.maximumBuildingFraction = .8;
  aiSet.minimumDefenseForBuilding = 10;
  aiSet.distancePower = 1.15;
  ai.push_back(GalconAI(2, aiSet));
  ai.begin()->init(planets, shipstats);
  ai.begin()->activate();

  //The number of the locally playing player
  char localPlayer = 1;

  //The type of ship that will currently be sent
  int shipSendType = 0;

  //A line drawer for the main surface
  LineDrawer linedraw(screen);
  
  /*
    -----
    MAIN LOOP
    -----
  */

  int time = SDL_GetTicks();
  uint8_t quit = 0;
  while (quit == 0)
    {
      //Update time and dt
      //Cap FPS
      int dt = SDL_GetTicks() - time;
      float minms = 1000.0/float(FPS_CAP);
      if (dt < minms) SDL_Delay(minms-dt);
      time = SDL_GetTicks();

      //Update keystates
      keystates = SDL_GetKeyState(NULL);

      //Check for arrow keys/wasd
      if (keystates[SDLK_UP] || keystates[SDLK_w])
	{
	  cameray -= CAMERA_SPEED * (dt/1000.0);
	  if (cameray < 0) cameray = 0;
	}
      
      if (keystates[SDLK_RIGHT] || keystates[SDLK_d])
	{
	  camerax += CAMERA_SPEED * (dt/1000.0);
	  if (camerax > LEVEL_WIDTH - SCREEN_WIDTH) camerax = LEVEL_WIDTH - SCREEN_WIDTH;
	}
      
      if (keystates[SDLK_DOWN] || keystates[SDLK_s])
	{
	  cameray += CAMERA_SPEED * (dt/1000.0);
	  if (cameray > LEVEL_HEIGHT - SCREEN_HEIGHT) cameray = LEVEL_HEIGHT - SCREEN_HEIGHT;
	}
      
      if (keystates[SDLK_LEFT] || keystates[SDLK_a])
	{
	  camerax -= CAMERA_SPEED * (dt/1000.0);
	  if (camerax < 0) camerax = 0;
	}

      //Update camera from camerax and cameray to struct
      camera.x = camerax;
      camera.y = cameray;
      
      //Handle events
      while (SDL_PollEvent(&event))
	{
	  //Quit if requested
	  if (event.type == SDL_QUIT)
	    {
	      quit = 1;
	    }

	  //Check for escape key, QWERTY to construct buildings, or numbers to select
	  //ship type.
	  //BUILDING CONSTRUCTION AND TYPE SELECTION THIS WAY IS TEMPORARY
	  if (event.type == SDL_KEYDOWN)
	    {
	      switch (event.key.keysym.sym)
		{
		case SDLK_ESCAPE:
		  quit = 1;
		  break;
		case SDLK_q:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 1) break;
                      
                      selectPlanet->build(*(buildRules[selectPlanet->type()].begin()),
                                          buildRules);
                    }
		  break;
		case SDLK_w:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 2) break;
                      
                      selectPlanet->build(*(++buildRules[selectPlanet->type()].begin()),
                                          buildRules);
                    }
		  break;
		case SDLK_e:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 3) break;
                      
                      std::list<Building*>::iterator i;
                      i = buildRules[selectPlanet->type()].begin();
                      i++; i++;
                      selectPlanet->build(*i, buildRules);
                    }
                  break;
		case SDLK_1:
		  shipSendType = 0;
		  break;
		case SDLK_2:
		  shipSendType = 1;
		  break;
		case SDLK_3:
		  shipSendType = 2;
		  break;
		case SDLK_4:
		  shipSendType = 3;
		  break;
		case SDLK_5:
		  shipSendType = 4;
		  break;
		default:
		  break;
		}
	    }

	  //Check for mouse clicks
	  if (event.type == SDL_MOUSEBUTTONDOWN)
	    {
	      //Left click
	      if (event.button.button == SDL_BUTTON_LEFT)
		{
		  //Used to select a planet
		  //Check if any are being clicked on
		  selectPlanet = planNull;

		  //Adjust mouse coordinates based on camera
		  Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
		  
		  for (planetIter i = planets.begin(); i != planets.end(); i++)
		    {
		      //See if distance from center is less than planet radius
		      Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
				   i->y() + (UNSCALED_PLANET_RADIUS * i->size()));

		      if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
			{
			  //Ensure the planet belongs to this person
			  if ((*i).owner() == localPlayer)
			    {
			      selectPlanet = i;
			      break;
			    }
			}
		    }
		}

	      //Right click
	      if (event.button.button == SDL_BUTTON_RIGHT)
		{
		  //Used to choose the destination for a fleet
		  //See if we have a selected planet
		  if (selectPlanet != planNull)
		    {

		      //Adjust mouse coordinates based on camera
		      Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
		      
		      //Check to see if any are being clicked on
		      for (planetIter i = planets.begin(); i != planets.end(); i++)
			{
			  Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
				       i->y() + (UNSCALED_PLANET_RADIUS * i->size()));
			  
			  //See if distance from center is less than planet radius
			  if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
			    {
			      //Split ships from the source planet
			      int transfer = (*selectPlanet).splitShips(0.5, shipSendType);
			      //Make sure we actually have a ship in the fleet
			      if (transfer > 0)
				{
				  //Add the new fleet
				  fleets.push_back(Fleet(transfer, shipSendType, shipstats[shipSendType], &(*selectPlanet), &(*i)));
				  break;
				}
			    }
			}
		    }
		}
	    }
	}

      //Draw a white background
      SDL_Rect back = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
      SDL_FillRect(screen, &back, 0xFFFFFF);

      //Update and display fleets
      for (fleetIter i = fleets.begin(); i != fleets.end(); i++)
	{
	  (*i).update();

	  //Check for arrival at destination
	  //See if distance from center is less than planet radius
	  Vec2f tar((*i).dest()->x() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()),
		    (*i).dest()->y() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()));
	  
	  if ((tar-i->pos()).length() < UNSCALED_PLANET_RADIUS * (i->dest())->size())
	    {
	      //Check if friendly or hostile
	      if ((*i).dest()->owner() == (*i).owner())
		{
		  //Add the fleet to the new planet
		  (*((*i).dest())).addShips(i->ships(), i->type());
		}
	      else //Hostile
		{
		  //Attack!
		  //Get ship counts before the attack
		  std::vector<int> ships1 = i->dest()->shipcount();
		  int oldowner = i->dest()->owner();

		  //Actually do the attack
		  (*((*i).dest())).takeAttack(i->ships(), i->type(), i->owner(), shipstats, indicator);

		  //If the attack changed ownership of the selected planet,
		  //deselect it
		  if (oldowner != i->dest()->owner() && i->dest() == &(*selectPlanet)) selectPlanet = planNull;

		  //Get ship counts after the attack
		  std::vector<int> ships2 = i->dest()->shipcount();

		  //Notify the defending AI about the losses
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (oldowner != j->player()) continue;
		      float newdefense = 0;
		      for (unsigned int k = 0; k < ships1.size(); k++)
			{
			  int diff;
			  //If ownership has changed
			  if (oldowner != i->dest()->owner())
			    {
			      diff = ships1[k];
			      j->notifyPlanetLoss(i->dest());
			    }
			  else
			    {
			      diff = ships1[k] - ships2[k];
			    }
			  
			  newdefense += diff * shipstats[k].defense;
			}
		      j->notifyDefendLoss(newdefense);
		    }

		  //Notify the attacking AI about the losses
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (i->owner() != j->player()) continue;
		      float lost;
		      
		      //If the attack failed
		      if (i->dest()->owner() != i->owner())
			{
			  //Lost everything
			  lost = i->ships();
			}
		      else //Successful attack
			{
			  //Lose the difference
			  lost = i->ships() - i->dest()->totalDefense(shipstats);
			  j->notifyPlanetGain(i->dest());
			}
		      
		      j->notifyAttackLoss(lost);
		    }
		}

	      //Delete all projectiles with this fleet as its target
	      for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
		{
		  if (pi->target() == &(*(i)))
		    {
		      pi = projectiles.erase(pi);
		      pi--;
		    }
		}

	      //Delete the fleet
	      i = fleets.erase(i);
	      i--;
	      continue;
	    }

	  //Check for interception
	  //Compare against every other fleet
	  for (fleetIter j = fleets.begin(); j != fleets.end(); j++)
	    {
	      //Atempt interception
	      char status = i->intercept(&(*j), shipstats);

	      //Greater than 0: Draw line
	      if (status <= 0) continue;
	      SDL_Color red = {255, 0, 0};
	      SDL_Color orange = {255, 255, 0};
	      linedraw.line(i->pos(), j->pos(), orange, red);

	      //Equal to 2: Dealt damage, but didn't notify
	      if (status == 2)
		{
		  //Notify the AI before we go around deleting things
		  for (std::list<GalconAI>::iterator k = ai.begin(); k != ai.end(); k++)
		    {
		      if (k->player() == j->owner())
			{
			  k->notifyFleetDamage(std::min(double(shipstats[i->type()].interceptDamage),
							double(j->totalDefense(shipstats))));
			}
		    }
		}

	      //Equal to 3: Destroy target
	      if (status != 3) break;

	      //We can have the projectile code handle the cleanup later
	      //Create a fake projectile right on top of it to deal the final blow
	      std::stringstream convertnum;
	      convertnum << "damage ";
	      convertnum << shipstats[i->type()].interceptDamage*i->ships()*2;
	      projectiles.push_back(Projectile(j->pos(), &(*j),
					       convertnum.str(),
					       shipstats[j->type()].speed*2));

	      //Don't attack more than one ship
	      break;
	    }
	  
	  (*i).display(screen, camera);
	}

      //Update and display planets
      for (planetIter i = planets.begin(); i != planets.end(); i++)
	{
	  //Get ship counts before the update
	  std::vector<int> ships1 = i->shipcount();

	  //Update the planet
	  (*i).update();

	  //Get ship counts after the update
	  std::vector<int> ships2 = i->shipcount();

	  //Notify a controlling AI about the construction
	  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
	    {
	      if (i->owner() != j->player()) continue;
	      float newattack = 0;
	      float newdefense = 0;
	      for (unsigned int k = 0; k < ships1.size(); k++)
		{
		  int diff = ships2[k] - ships1[k];
		  newattack += diff * shipstats[k].attack;
		  newdefense += diff * shipstats[k].defense;
		}
	      j->notifyConstruction(newattack, newdefense);
	    }

	  //If this planet is selected, add an indicator
	  if (i == selectPlanet)
	    {
	      SDL_Rect temprect = {Sint16((*i).x()-10 - camera.x), Sint16((*i).y()-10 - camera.y), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20)};
	      SDL_FillRect(screen, &temprect, SDL_MapRGB(screen->format, 100, 100, 100));
	    }

          //If this is a lava planet and it is depleted, replace the image
          if (i->typeInfo() < 0 && i->type() == 1)
            {
              i->setImage(planet1_1img);
              i->setTypeInfo(0);
              i->setRotSpeed(0);
              i->setShipRate(0, ship0rate * PLANET1_DEPLETION_PENALTY);
            }

	  //Iterate over all buildings to handle effects from buildings to other objects

	  for (unsigned int j = 0; j < i->buildcount(); j++)
	    {
	      //Get the building
	      BuildingInstance* b = i->building(j);
	      
	      //Skip over nonexistant and incomplete buildings
	      if (!(b->exists()) || j == Uint32(i->buildIndex())) continue;

	      //Try to make it fire, remember result
	      bool fire = b->fire();
	      
	      //Create a string stream and vector for tokens
	      std::stringstream ss(b->effect());
	      std::string item;
	      std::vector<std::string> tokens;
	      while (std::getline(ss, item, ' '))
		{
		  tokens.push_back(item);
		}
	      
	      //Ensure the size is at least two
	      if (tokens.size() < 3) continue;
	      
	      //Parse it and apply effects that involve multiple objects
	      //Fire projectile: fire <effect> <effectvars> <speed as multiplier>
	      if (tokens[0] == "fire")
		{
		  //Ensure size of four
		  if (tokens.size() != 4) continue;
		  
		  //Loop over all potential target fleets, find closest
		  Fleet* closest = NULL;
		  float closestDist = -1;
		  Vec2f coords = i->buildcoords(j);
		  for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
		    {
		      //Only check further if it's an enemy fleet
		      if (k->owner() == i->owner()) continue;
		      //Compute the distance between them
		      double dist = (coords-k->pos()).length();
		      
		      //Continue if the fleet is out of range
		      if (dist > b->range()) continue;
		      
		      //Compare with previous best
		      if (dist < closestDist || closestDist < -0.5)
			{
			  closestDist = dist;
			  closest = &(*k);
			}
		    }
		  
		  //Fire a projectile from the building to the fleet
		  if (closest != NULL)
		    {
		      if (fire)
			{
			  //Create a proper string for the projectile
			  std::string projstr;
			  for (unsigned int word = 1; word < tokens.size()-1; word++)
			    { projstr += tokens[word] + " "; }
			  projectiles.push_back(Projectile(coords, closest, projstr, std::atof(tokens[tokens.size()-1].c_str())));
			}
		    }
		}

              //Aura: aura <effect> <effectvars>
              if (tokens[0] == "aura")
                {
                  //Find number of ships in range
                  int shipcount = 0;
                  for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
		    {
		      //Only check further if it's an enemy fleet
		      if (k->owner() == i->owner()) continue;
		      //Compute the distance between them
		      double dist = (i->buildcoords(j)-k->pos()).length();
                      if (dist <= b->range()) shipcount += k->ships();
                    }

                  //Deal damage with a fake projectile
                  if (fire)
                    {
                      bool hit = false;
                      for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
                        {
                          //Only check further if it's an enemy fleet
                          if (k->owner() == i->owner()) continue;
                          //Compute the distance between them
                          double dist = (i->buildcoords(j)-k->pos()).length();
                          if (dist > b->range()) continue;
                          hit = true;
                          
                          std::string projstr;
                          //Divide appropriately if needed
                          if (tokens[tokens.size()-1] == "total")
                            {
                              std::stringstream toa;
                              toa << atof(tokens[tokens.size()-2].c_str())*float(k->ships())/float(shipcount);
                              tokens[tokens.size()-1] = toa.str();
                            }
                          //Depleted volcanic planets don't do as much
                          if (i->type() == 1 && i->typeInfo() <= 0)
                            {
                              std::stringstream toa;
                              toa << atof(tokens[tokens.size()-2].c_str())*PLANET1_DEPLETION_PENALTY;
                              tokens[tokens.size()-1] = toa.str();
                            }
                          //Create the projectile
                          for (unsigned int word = 1; word < tokens.size()-1; word++)
                            {
                              projstr += tokens[word] + " ";
                            }
                          projectiles.push_back(Projectile(k->pos(), &(*k), projstr, 1));
                        }

                      //Volcanic planets will lost some fuel
                      if (i->type() == 1 && hit && i->typeInfo() != 0)
                        {
                          i->setTypeInfo(i->typeInfo()-PLANET1_DEPLETION_RATE);
                          if (i->typeInfo() == 0) i->setTypeInfo(-1);
                        }
                      
                    }
                }
                      
	    } //for each building

	  (*i).display(screen, planetFont, camera);
	}

      //Update and display projectiles
      for (projectileIter i = projectiles.begin(); i != projectiles.end(); i++)
	{
	  (*i).update();

	  //Check if the projectile has hit its target fleet
	  if ((i->pos() - i->target()->pos()).length() < 12.345) //MAGIC NUMBER >:(
	    {
	      //Tokenize string to determine effect
	      std::stringstream ss(i->effect());
	      std::string item;
	      std::vector<std::string> tokens;
	      while (std::getline(ss, item, ' '))
		{
		  tokens.push_back(item);
		}

	      //Damage: damage <amount>
	      if (tokens[0] == "damage")
		{
		  //Ensure size of two
		  if (tokens.size() != 2) continue;

		  //Deliver the damage

		  //Notify the AI before we go around deleting things
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (j->player() == i->target()->owner())
			{
			  j->notifyFleetDamage(std::min(std::atof(tokens[1].c_str()), double(i->target()->totalDefense(shipstats))));
			}
		    }
		  
		  //Check to see if the fleet is destroyed by this
		  if (!(i->target()->takeHit(std::atof(tokens[1].c_str()), shipstats)))
		    {
		      //Delete the fleet
		      for (fleetIter fi = fleets.begin(); fi != fleets.end(); fi++)
			{
			  if (&(*fi) == &(*(i->target())))
			    {
			      fleets.erase(fi);
			      break;
			    }
			}

		      //Delete all projectiles with this fleet as the target
		      for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
			{
			  if (pi->target() == i->target())
			    {
			      if (pi == i) continue;
			      pi = projectiles.erase(pi);
			      pi--;
			    }
			}

		    }

		  //Either way, destroy this projectile
		  i = projectiles.erase(i);
		  i--;
		  continue;
		}
	    }

	  (*i).display(screen, camera);
	}

      //Perform AI calculations
      for (std::list<GalconAI>::iterator i = ai.begin(); i != ai.end(); i++)
	{
	  //Get the command list
	  commandList com = i->update(planets, fleets, shipstats, buildRules);

	  //Execute each command
	  for (commandList::iterator j = com.begin(); j != com.end(); j++)
	    {
	      //Extract the info from the command
	      Planet* source = j->first;
	      int amount = j->second.first;
	      Planet* dest = j->second.second;

	      //Handle building construction
	      if (source == dest)
		{
		  std::list<Building*>::iterator build = buildRules[source->type()].begin();
		  while (amount > 0)
		    {
		      amount--;
		      build++;
		    }

		  //Build it!
		  source->build((*build), buildRules);
		  continue;
		}

	      //Get the number of ships from the source
	      std::vector<int> ships = source->shipcount();

	      //Send out a fleet for each ship type used
	      std::vector<int> newfleet;
	      newfleet.resize(ships.size());
	      int total = 0;
	      for (unsigned int k = 0; k < ships.size(); k++)
		{
		  //Handle it differently for attack or defense
		  float typeTotal;
		  if (dest->owner() == source->owner())
		    {
		      //Check the total defense of this ship type
		      typeTotal = ships[k] * shipstats[k].defense;
		    }
		  else
		    {
		      //Check the total attack of this ship type
		      typeTotal = ships[k] * shipstats[k].attack;
		    }
		  
		  //If there's more ships requested than there are of this type
		  if (total + typeTotal <= amount)
		    {
		      //Add them all
		      newfleet[k] += ships[k];
		      total += typeTotal;
		    }
		  else //More ships than space in the requested fleet
		    {
		      //Find the proper amount
		      //# of ships to send = defense requested / def per ship
		      float properAmount = (amount - total) / (typeTotal / ships[k]);
		      newfleet[k] += properAmount;
		      break;
		    }
		}
	      
	      //Fleet is built, send each type that has some ships
	      for (unsigned int k = 0; k < newfleet.size(); k++)
		{
		  if (newfleet[k] == 0) continue;
		  fleets.push_back(Fleet(newfleet[k], k, shipstats[k], source, dest));

		  //Also subtract the fleet from the original planet
		  newfleet[k] *= -1;
		  source->addShips(newfleet[k], k);
		}
	    }
	}

      //Flipoo
      if (SDL_Flip(screen) == -1)
	{
	  return 1;
	}
    }

  //Free surfaces
  SDL_FreeSurface(indicator[1]);
  SDL_FreeSurface(indicator[2]);
  SDL_FreeSurface(planet0img);
  SDL_FreeSurface(planet1img);
  SDL_FreeSurface(planet1_1img);

  //Clean up TTF
  TTF_CloseFont(planetFont);
  TTF_Quit();

  SDL_Quit();
}
Esempio n. 15
0
void Game::PlayerShoot()
{
	Mix_PlayChannel(-1, this->playerShoot, 0);
	this->projectiles.push_back(Projectile(&this->g_Texture, &this->projectileSrcRect, true, this->player.getX() + this->player.getWidth() / 2, this->playerViewport.y));
}
Esempio n. 16
0
void Bird::shoot() {
	sf::Vector2f birdPos = birds[animationSpriteFrame].getPosition();
	projectiles.push_back(Projectile(*textures, birdPos));
}
Esempio n. 17
0
void Game::InvaderShoot(Invader *shooter)
{
	Mix_PlayChannel(-1, this->invaderShoot, 0);
	this->projectiles.push_back(Projectile(&this->g_Texture, &this->projectileSrcRect, false, shooter->getX() + shooter->getWidth() / 2 + this->invadersViewport.x, this->invadersViewport.y + shooter->getY()));
}