Exemplo n.º 1
0
bool UnloadArmament::doOrder(IGObject::Ptr ob){
  Fleet* fleet = dynamic_cast<Fleet*>(ob->getObjectBehaviour());
  ObjectManager* obman = Game::getGame()->getObjectManager();
  ObjectTypeManager* otman = Game::getGame()->getObjectTypeManager();
  ResourceManager::Ptr resman = Game::getGame()->getResourceManager();
  std::set<uint32_t>objs = obman->getObjectsByPos(fleet->getPosition(), 10000);
  IGObject::Ptr planetObj;
  Planet* planet;

  for (std::set<uint32_t>::const_iterator itcurr = objs.begin(); itcurr != objs.end(); ++itcurr) {
    if (obman->getObject(*itcurr)->getType() == otman->getObjectTypeByName("Planet")) {

      planetObj = obman->getObject(*itcurr);
      planet = dynamic_cast<Planet*>(planetObj->getObjectBehaviour());
      Logger::getLogger()->debug("UnloadArmaments::doOrder Found Planet %s for Unload Armaments Order", planetObj->getName().c_str());
      const uint32_t factoryType = resman->getResourceDescription("Factories")->getResourceType();

    IdMap weapontype = weaponlist->getList();
    for(IdMap::iterator weaponit = weapontype.begin(); weaponit != weapontype.end(); ++weaponit) {
      if (planet->removeResource(factoryType, 1)) {
        if (fleet->removeResource(weaponit->first, weaponit->second)) {
          Logger::getLogger()->debug("UnloadArmaments::doOrder success, adding to resource %d: #:%d", weaponit->first, weaponit->second);
          planet->addResource(weaponit->first, weaponit->second);
          planetObj->touchModTime();
          return true;
          }
        } else {
          turns = 1;
          return true;
        }
      }
    }
  }
  return false;
}
Exemplo n.º 2
0
void DumpWorldToSyncLog( char *_filename )
{
    FILE *file = fopen( _filename, "a" );
    if( !file ) return;

    fprintf( file, "\n\nBegin Final Object Positions\n" );

    for( int i = 0; i < g_app->GetWorld()->m_teams.Size(); ++i )
    {
        Team *team = g_app->GetWorld()->m_teams[i];
        for( int j = 0; j < team->m_fleets.Size(); ++j )
        {
            Fleet *fleet = team->m_fleets[j];
            char *state = fleet->LogState();
            fprintf( file, "%s\n", state );
        }
    }

    for( int i = 0; i < g_app->GetWorld()->m_objects.Size(); ++i )
    {
        if( g_app->GetWorld()->m_objects.ValidIndex(i) )
        {
            WorldObject *obj = g_app->GetWorld()->m_objects[i];
            char *state = obj->LogState();
            fprintf( file, "%s\n", state );
        }
    }

    fclose(file);
}
Exemplo n.º 3
0
//Sends a fleet back to it's home planet
void TaeTurn::sendHome(uint32_t fleet) {
    Game* game = Game::getGame();
    ObjectManager* obm = game->getObjectManager();
    ObjectTypeManager* obtm = game->getObjectTypeManager();
    PlayerManager::Ptr pm = game->getPlayerManager();

    IGObject::Ptr fleetobj = obm->getObject(fleet);
    //Check to make sure it is really a fleet
    if(fleetobj->getType() != obtm->getObjectTypeByName("Fleet")) {
        return;
    }

    //Get all the required objects
    Fleet* f = (Fleet*) fleetobj->getObjectBehaviour();
    Player::Ptr p = pm->getPlayer(f->getOwner());
    IGObject::Ptr sys = obm->getObject(fleetobj->getParent());
    StarSystem* sysData = (StarSystem*) sys->getObjectBehaviour();

    //Remove fleet from system
    sysData->setRegion(0);
    fleetobj->removeFromParent();

    //Find it's home planet
    std::set<uint32_t> objects = obm->getAllIds();
    std::set<uint32_t>::iterator itcurr;
    for(itcurr = objects.begin(); itcurr != objects.end(); ++itcurr) {
        IGObject::Ptr ob = obm->getObject(*itcurr);
        if(ob->getName().compare(string(p->getName() + "'s Home Planet")) == 0) {
            Planet* p = (Planet*) ob->getObjectBehaviour();
            f->setPosition(p->getPosition());
            fleetobj->addToParent(ob->getID());
        }
    }
}
Exemplo n.º 4
0
std::map<uint32_t, std::pair<std::string, uint32_t> > LoadArmament::generateListOptions(){
  Logger::getLogger()->debug("Entering LoadArmament::generateListOptions");
  std::map<uint32_t, std::pair<std::string, uint32_t> > options;

  Game* game = Game::getGame();
  IGObject::Ptr selectedObj = game->getObjectManager()->getObject(
            game->getOrderManager()->getOrderQueue(orderqueueid)->getObjectId());

  Fleet* fleet = dynamic_cast<Fleet*>(selectedObj->getObjectBehaviour());

  ObjectManager* obman = Game::getGame()->getObjectManager();
  ObjectTypeManager* otman = Game::getGame()->getObjectTypeManager();
  ResourceManager::Ptr resman = Game::getGame()->getResourceManager();
  std::set<uint32_t>objs = obman->getObjectsByPos(fleet->getPosition(), 10000);

  for (std::set<uint32_t>::iterator itcurr = objs.begin(); itcurr != objs.end(); ++itcurr) {
    if (obman->getObject(*itcurr)->getType() == otman->getObjectTypeByName("Planet")) {
      IGObject::Ptr planetObj = obman->getObject(*itcurr);
      Planet* planet = dynamic_cast<Planet*>(planetObj->getObjectBehaviour());
      Logger::getLogger()->debug("Found Planet %s for Load Armaments Order", planetObj->getName().c_str());
      std::map<uint32_t, std::pair<uint32_t, uint32_t> > reslist = planet->getResources();
      for (std::map<uint32_t, std::pair<uint32_t, uint32_t> >::iterator it = reslist.begin(); it != reslist.end(); ++it) {
        if (resman->getResourceDescription(it->first)->getUnitSingular() == "weapon") {
          options[it->first] = std::pair<std::string, uint32_t>(resman->getResourceDescription(it->first)->getNamePlural(),
            planet->getResourceSurfaceValue(it->first));
        }
      }

    }
  }

  Logger::getLogger()->debug("Exiting LoadArmament::generateListOptions");
  return options;
}
Exemplo n.º 5
0
bool Fleet::operator == (const Fleet& fleet) const{
    return (_ownerID==fleet.OwnerID() &&
		   _source_planet_id==fleet.SourcePlanetID() &&
		   _destination_planet_id==fleet.DestinationPlanetID() &&
		   _num_ships==fleet.NumShips() &&
			_turns_remaining==fleet.TurnsRemaining() );
}
Exemplo n.º 6
0
void PlanetWarsGame::advanceGame() {
    //Make planets grow ships.
    const int numPlanets = static_cast<int>(m_planets.size());

    for (int i = 0; i < numPlanets; ++i) {
        m_planets[i]->growFleets();
    }

    //Advance fleets.
    for (FleetList::iterator it = m_fleets.begin(); it != m_fleets.end(); ++it) {
        (*it)->advance();
    }

    //Welcome (or fight) the arrived fleets.
    for (int i = 0; i < numPlanets; ++i) {
        m_planets[i]->welcomeArrivedFleets();
    }

    //Clean up arrived fleets.
    FleetList::iterator itFleet = m_fleets.begin();

    while (itFleet != m_fleets.end()) {
        FleetList::iterator itCurrent = itFleet;
        ++itFleet;

        Fleet* fleet = (*itCurrent);

        if (fleet->getTurnsRemaining() <= 0) {
            delete fleet;
            m_fleets.erase(itCurrent);

        }
    }
}
Exemplo n.º 7
0
int Move::getETA(IGObject *ob) const{
  Fleet* fleet = ((Fleet*)(ob->getObjectBehaviour()));
  unsigned long long distance = coords->getPosition().getDistance(fleet->getPosition());
  unsigned long max_speed = 3000000;
  
  if(distance == 0) 
    return 1;
  return (int)((distance - 1) / max_speed) + 1;
}
Exemplo n.º 8
0
void panel_clicked_fleet(int mx, int my, int mb) {
    Fleet *flt = (Fleet*)cur_object;
    if(mx >= 800 && mb == 4) {
        --panel_offset;
        panel_draw_fleet();
        SDL_Rect screenrec = {800, 12+24*SKIP, 224, 24*23};
        screenrec.h = min(int(screenrec.h), 24*(flt->NumShips()));
        update(&screenrec);
        return;
    }
    if(mx >= 800 && mb == 5) {
        ++panel_offset;
        panel_draw_fleet();
        SDL_Rect screenrec = {800, 12+24*SKIP, 224, 24*23};
        screenrec.h = min(int(screenrec.h), 24*(flt->NumShips()));
        update(&screenrec);
        return;
    }

    int line = my;
    line -= 12+24*SKIP;
    if(line >= 0) line /= 24;
    if(line < 0 || line > 22
            || line >= int(flt->NumShips()) - panel_offset) {
        if(selection >= 0) {
            update(800, 12+24*(SKIP+selection-panel_offset), 224, 24);
            selection = -1;
            panel_draw_fleet();
        }
        return;
    }

    line += panel_offset;

    if(mb == 3) {
    }
    else if(mb == 1) {
        SDL_Rect screenrec = {800, 12+24*SKIP, 224, 24};
        if(selection >= 0) {
            screenrec.y = 12+24*(SKIP+selection);
            update(&screenrec);
        }
        if(selection != line) {
            selection = line;
            screenrec.y = 12+24*(SKIP+selection);
            update(&screenrec);
            panel_draw_fleet();
        }
        else {
            cur_ship = line;
            panel = PANEL_SHIP;
            panel_init();
        }
        audio_play(click2, 8, 8);
    }
}
Exemplo n.º 9
0
Fleet* Fleet::Clone(int empire_id) const {
    Visibility vis = GetUniverse().GetObjectVisibilityByEmpire(this->ID(), empire_id);

    if (!(vis >= VIS_BASIC_VISIBILITY && vis <= VIS_FULL_VISIBILITY))
        return 0;

    Fleet* retval = new Fleet();
    retval->Copy(this, empire_id);
    return retval;
}
Exemplo n.º 10
0
bool Bombard::doOrder(IGObject *fleet) {

   Game *game = Game::getGame();
   ObjectManager *om = game->getObjectManager();
   ObjectTypeManager *odm = game->getObjectTypeManager();
   Random *rand = game->getRandom();

   IGObject *planetObj = om->getObject(planet->getObjectId());

   if(planetObj->getType() != odm->getObjectTypeByName("Planet"))
   {
      Logger::getLogger()->debug("Player tried to bombard something illogical");
      return true;
   }

   Fleet *fleetData = dynamic_cast<Fleet*>(fleet->getObjectBehaviour());
   Planet *planetData = dynamic_cast<Planet*>(planetObj->getObjectBehaviour());
   char planetShipTech = PlayerInfo::getPlayerInfo(planetData->getOwner()).getShipTechLevel();
   double attack = fleetData->getAttack();
   
   planetData->removeResource("Industry", 
                  static_cast<uint32_t>(attack * INDUSTRY_DMG * (1+rand->getInRange(-2,2)/100.) ));

   planetData->removeResource("Social Environment", 
                  static_cast<uint32_t>(attack * SOCIAL_DMG * (1+rand->getInRange(-2,2)/100.) ));

   planetData->removeResource("Planetary Environment", 
                  static_cast<uint32_t>(attack * PLANETARY_DMG * (1+rand->getInRange(-2,2)/100.) ));

   planetData->removeResource(string("PDB") + planetShipTech,
                  static_cast<uint32_t>(attack * PDB_DMG / 10. * (1+rand->getInRange(-2,2)/100.) ));

   PlayerInfo::getPlayerInfo(fleetData->getOwner()).addVictoryPoints(VICTORY_POINTS);


   // PDBs counter-attack at: PDB level * 6 * numPDBs
   fleetData->takeDamage( (planetShipTech - '0') *
                         6 * planetData->getResource(string("PDB") + planetShipTech).first);

   Message *msg = new Message();
   msg->setSubject("Bombard complete");
   string body = "Fleet \"" + fleet->getName() + "\" bombarded " + planetObj->getName();
   msg->setBody(PlayerInfo::appAllVictoryPoints(body));
   msg->addReference(rst_Action_Order, rsorav_Completion);
   msg->addReference(rst_Object, fleet->getID());
   msg->addReference(rst_Object, planetObj->getID());

   game->getPlayerManager()->getPlayer(fleetData->getOwner())->postToBoard(msg);
   game->getPlayerManager()->getPlayer(planetData->getOwner())->postToBoard(msg);

   return true;
}
Exemplo n.º 11
0
void Planet::welcomeArrivedFleets() {
    const int ownerId = m_owner->getId();

    //Tally up the ships for each force.
    const int numArrivedFleets = static_cast<int>(m_landedFleets.size());

    if (numArrivedFleets == 0) {
        return;
    }

    int playerShips[3];
    playerShips[0] = (ownerId == 0) ? m_numShips : 0;
    playerShips[1] = (ownerId == 1) ? m_numShips : 0;
    playerShips[2] = (ownerId == 2) ? m_numShips : 0;

    for (int i = 0; i < numArrivedFleets; ++i) {
        Fleet* fleet = m_landedFleets[i];
        playerShips[fleet->getOwner()->getId()] += fleet->getNumShips();
    }

    m_landedFleets.clear();

    //Check who won.
    //Check whether the owner stays the same.
    if (playerShips[ownerId] >= std::max(playerShips[(ownerId+1)%3], playerShips[(ownerId+2)%3])) {
        this->setNumShips(playerShips[ownerId]
                          - std::max(playerShips[(ownerId+1)%3], playerShips[(ownerId+2)%3]));
        return;
    }

    //Otherwise, find the new owner.
    if (playerShips[1] > playerShips[2]) {
        this->setOwner(m_game->getFirstPlayer());
        const int remainingShips = playerShips[1] - std::max(playerShips[2], playerShips[0]);
        this->setNumShips(remainingShips);

    } else if (playerShips[2] > playerShips[1]) {
        this->setOwner(m_game->getSecondPlayer());
        const int remainingShips = playerShips[2] - std::max(playerShips[1], playerShips[0]);
        this->setNumShips(remainingShips);

    } else if (ownerId == 0 && playerShips[2] == playerShips[1]) {
        //The invading fleets are larger than the neutral planet, but equal in size.
        //Planet stays neutral.
        this->setNumShips(0);
    }

    //There should be no other cases.
}
Exemplo n.º 12
0
void StarSystem::addFleet(Fleet& input_fleet)
{
  fleets.insert(std::pair<int,Fleet>(input_fleet.getID(),input_fleet) );


//  cout << "added fleet with id " << input_fleet.getID() << endl;
}
Exemplo n.º 13
0
void NormalGame::display_stats()
{
	STACKTRACE;
	pause();
	int i;
	for (i = 0; i < num_players; i += 1) {
		Fleet *fleet = player_fleet[i];
		switch (log->type) {
			case Log::log_net1client:
			case Log::log_net1server:
			{
				//				if (log->get_direction(player_control[i]->channel) & Log::direction_write)
				message.print(6000, 15, "%s status: : %d / ?? Ships, %d / ??? points", player_name[i], fleet->getSize(), fleet->getCost());
				//				else
				//					message.print(6000, 15, "%s status: : %d / %d points", buffy, fleet->cost, player_total_fleet[i]);
			}
			break;
			default:
			{
				message.print(6000, 15, "%s status: : %d / ?? Ships, %d / ??? points", player_name[i], fleet->getSize(), fleet->getCost());
			}
			break;
		}
	}
	unpause();
	return;
}
Exemplo n.º 14
0
std::string PlanetWarsGame::toString(Player* pov) const {
    std::stringstream gameState;
    const int numPlanets = static_cast<int>(m_planets.size());

    //Write the planets.
    for (int i = 0; i < numPlanets; ++i) {
        Planet* planet = m_planets[i];
        gameState << "P " << planet->getX()
                << " " << planet->getY()
                << " " << pov->povId(planet->getOwner())
                << " " << planet->getNumShips()
                << " " << planet->getGrowthRate()
                << std::endl;
    }

    //Write the fleets.
    for (FleetList::const_iterator it = m_fleets.begin(); it != m_fleets.end(); ++it) {
        Fleet* fleet = (*it);
        gameState << "F " << pov->povId(fleet->getOwner())
                << " " << fleet->getNumShips()
                << " " << fleet->getSource()->getId()
                << " " << fleet->getDestination()->getId()
                << " " << fleet->getTotalTripLength()
                << " " << fleet->getTurnsRemaining()
                << std::endl;
    }

    gameState << "go" << std::endl;

    return gameState.str();

}
Exemplo n.º 15
0
void CargoHolder::AdjustAmounts(CargoType ct, long amount)
{
	if (amount == 0)
		return;

	if (ct >= 0) {
		mContains[ct] += amount;
	} else if (ct == POPULATION) {
		mPopulation += amount;
	} else if (ct == FUEL) {
		Fleet * f = dynamic_cast<Fleet *>(this);
		if (f == NULL) {
			assert(false);
		} else
			f->AdjustFuel(amount);
	} else {
		assert(false);
	}
}
Exemplo n.º 16
0
int my_list_proc( int msg, DIALOG* d, int c )
{
    STACKTRACE;
    int old_d1 = d->d1;
    Fleet *fleet = (Fleet*)d->dp3;
    int ret = d_list_proc2( msg, d, c );
    if ( d->d1 != old_d1 || msg == MSG_START ) {
        ShipType* type = fleet->getShipType(d->d1);

        ASSERT(type != NULL);

        selectDialog[SELECT_DIALOG_TITLE].flags |= D_DIRTY;
        sprintf(selectTitleString, "%s\n%s\n%d of %d points",
                selectShipPrompt,
                (type != NULL) ? type->name : 0,
                (type != NULL) ? type->cost : 0,
                fleet->getCost());

        BITMAP* panel = NULL;
        TW_DATAFILE* data = tw_load_datafile_object( type->data->file, "SHIP_P00_PCX" );

        if ( data ) {
            BITMAP* bmp = (BITMAP*)data->dat;
            panel = create_bitmap_ex( bitmap_color_depth(screen), bmp->w, bmp->h );
            blit( bmp, panel, 0, 0, 0, 0, bmp->w, bmp->h );
            tw_unload_datafile_object( data );
            data = tw_load_datafile_object( type->data->file, "SHIP_P01_PCX" );
            bmp = (BITMAP*)data->dat;
            blit( bmp, panel, 0, 0, 4, 65, bmp->w, bmp->h );
            tw_unload_datafile_object( data );
            color_correct_bitmap( panel, 0 );
        }

        if ( selectDialog[SELECT_DIALOG_PIC].dp ) destroy_bitmap( (BITMAP*)selectDialog[SELECT_DIALOG_PIC].dp );
        selectDialog[SELECT_DIALOG_PIC].dp = panel;
        scare_mouse();
        SEND_MESSAGE( &selectDialog[SELECT_DIALOG_PIC], MSG_DRAW, 0 );
        unscare_mouse();
    }
    return ret;
}
Exemplo n.º 17
0
std::map<uint32_t, std::pair<std::string, uint32_t> > UnloadArmament::generateListOptions(){
  Logger::getLogger()->debug("Entering UnloadArmament::generateListOptions");
  std::map<uint32_t, std::pair<std::string, uint32_t> > options;

  Game* game = Game::getGame();
  IGObject::Ptr selectedObj = game->getObjectManager()->getObject(
            game->getOrderManager()->getOrderQueue(orderqueueid)->getObjectId());

  Fleet* fleet = dynamic_cast<Fleet*>(selectedObj->getObjectBehaviour());

  ResourceManager::Ptr resman = Game::getGame()->getResourceManager();
  std::map<uint32_t, std::pair<uint32_t, uint32_t> > objs = fleet->getResources();

  for (std::map<uint32_t, std::pair<uint32_t, uint32_t> >::iterator itcurr = objs.begin();
    itcurr != objs.end(); ++itcurr) {
     options[itcurr->first] = std::pair<std::string, uint32_t>(resman->getResourceDescription(itcurr->first)->getNamePlural(),
            itcurr->second.first);
  }

  Logger::getLogger()->debug("Exiting UnloadArmament::generateListOptions");
  return options;
}
Exemplo n.º 18
0
void Planet::advanceState(uint nr_turns, Fleets* arrivingFleets){
	Fleet* tempFleet;
	for(uint i=1;i<=nr_turns;i++){
		uint ships[NUM_PLAYERS];
		ships[PLAYER_NEUTRAL]=ships[PLAYER_1]=ships[PLAYER_2]=0;
		
		if(_ownerID!=PLAYER_NEUTRAL){
			ships_count+=_growth_rate;
		}
		ships[_ownerID]=ships_count;
		
		for(uint j=0;j<arrivingFleets->size();j++){
			tempFleet = arrivingFleets->at(j);
			if(tempFleet->TurnsRemaining()==i){
				ships[tempFleet->OwnerID()]+=tempFleet->NumShips();
			}
		}
		
		//std::cerr << "arriving ships: " << ships[0] << " " << ships[1] << " " << ships[2] << std::endl;
		uint greatest_id = _ownerID;
		uint second_greatest_id=0;
		for(uint j=0;j<NUM_PLAYERS;j++){
			if(ships[j]>ships[greatest_id]) greatest_id=j;
		}
		for(uint j=0;j<NUM_PLAYERS;j++){
			if(j!=greatest_id && ships[j]>ships[second_greatest_id]) second_greatest_id=j;
		}
		
		//std::cerr << "Player " << greatest_id << " has ships: " << ships[greatest_id] << " second: " << second_greatest_id << " " << ships[second_greatest_id] << std::endl;
		
		if(ships[greatest_id]==ships[second_greatest_id]){
			ships_count = 0;
		} else {
			//std::cerr << "setting owner: " << greatest_id << " new ship count: " << ships[greatest_id]-ships[second_greatest_id] << std::endl;
			_ownerID = greatest_id;
			ships_count = ships[greatest_id]-ships[second_greatest_id];
		}
	}
}
Exemplo n.º 19
0
void TempFleet::ChaseeGone(SpaceObject * chasee)
{
	Planet * planet = chasee->InOrbit();
	Message * mess = NCGetOwner()->AddMessage("Chasee has vanished", chasee);
	if (planet == NULL)
		mess->AddItem("Last location", new Location(*chasee), true);
	else
		mess->AddItem("Last location", planet);

	Fleet * f = dynamic_cast<Fleet *>(GetRealCH());
	if (f != NULL) {
		deque<WayOrder *> const & ords = f->GetOrders();
		int i;
		for (i = 0; i < ords.size(); ++i) {
			if (ords[i]->GetLocation() == chasee) {
				if (planet == NULL)
					ords[i]->SetLocation(new Location(*chasee), true);
				else
					ords[i]->SetLocation(planet);
			}
		}
	}
}
Exemplo n.º 20
0
void GameController::onSetFleetShipNumber(int ships)
{
  Fleet* fleet = NULL;

  fleet = fleets.last();

  fleet->getSource()->setShips(fleet->getSource()->getShips() - ships);
  
  fleet->setNumShips(ships);
  fleet->setKillPercent(fleet->getSource()->getKillPercent());
  fleet->setArrivalTurn(currentTurn+2);

  fleet->getSource()->blink();
  fleet->getDestination()->blink();

  fleet = new Fleet();
  fleets.append(fleet);
  
  emit displayControl(QString("<font color=%1>%2</font>:Select source planet").arg(players[currentPlayer]->getColor().name()).arg(players[currentPlayer]->getName()));

}
Exemplo n.º 21
0
void GameController::onSetSelectPlanet(Planet* planet)
{
  Fleet* fleet = NULL;
  
  /* on first selection and since last assumes that the vector is not empty */
  if(fleets.isEmpty())
    {
      fleet = new Fleet();
      fleets.append(fleet);
    }
  
  fleet = fleets.last();
  
  if(fleet->getSource() == NULL) /* selecting source */
    {

      if(planet->getOwner() != players[currentPlayer]) /* if trying to choose a source planet that isn't yours */
	return;

      planet->blink();
      fleet->setSource(planet);
      fleet->setKillPercent(planet->getKillPercent());
      fleet->setOwner(players[currentPlayer]);

      emit displayControl(QString("<font color=%1>%2</font>:Select destination planet").arg(players[currentPlayer]->getColor().name()).arg(players[currentPlayer]->getName()));
    }
  else if(fleet->getDestination() == NULL) /* selecting destination */
    {
      if(fleet->getSource() == planet) /* source and destination are the same */
	return;

      planet->blink();
      fleet->setDestination(planet);
      
      emit displayShipNumber();
      
      emit displayControl(QString("<font color=%1>%2</font>:Number of ships").arg(players[currentPlayer]->getColor().name()).arg(players[currentPlayer]->getName()));
      
    }
  

}
Exemplo n.º 22
0
//The colonize order checks to make sure the system is valid, then adds a resource to the planet, checks for
//external combat, and awards one point to the player with the leader in the region of the new colony.
bool Colonize::doOrder(IGObject::Ptr obj) {
    ObjectManager* obm = Game::getGame()->getObjectManager();
    ObjectTypeManager* obtm = Game::getGame()->getObjectTypeManager();
    Fleet* fleetData = (Fleet*)(obj->getObjectBehaviour());
    Player::Ptr player = Game::getGame()->getPlayerManager()->getPlayer(fleetData->getOwner());

    IGObject::Ptr newStarSys = obm->getObject(starSys->getObjectId());

    //Perform last minute checks to make sure the system can be colonized
    if(newStarSys->getType() != obtm->getObjectTypeByName("Star System")) {
        //Not a star system
        Logger::getLogger()->debug("Trying to colonize to an object which is not a star system");
        Message::Ptr msg( new Message() );
        msg->setSubject("Colonize order failed");
        msg->setBody(string("You're fleet, \"" + obj->getName() + "\" tried to colonize an object which is not a star system!"));
        msg->addReference(rst_Object, obj->getID());
        player->postToBoard(msg);
        return false;
    }
    if(!((StarSystem*)(newStarSys->getObjectBehaviour()))->canBeColonized(isMining)) {
        //Not colonizable
        Logger::getLogger()->debug("Player tried to colonize a system which cannot be colonized.");
        Message::Ptr msg( new Message() );
        msg->setSubject("Colonize order failed");
        msg->setBody(string("You're fleet, \"" + obj->getName() + "\" tried to colonize a fleet which cannot be colonized!"));
        msg->addReference(rst_Object, obj->getID());
        player->postToBoard(msg);
        return false;
    }   

    //Find the star system's planet
    set<uint32_t> children = newStarSys->getContainedObjects();
    uint32_t pid;
    bool planetFound = false;
    for(set<uint32_t>::iterator i=children.begin(); i != children.end(); i++) {
        if(obm->getObject(*i)->getType() == obtm->getObjectTypeByName("Planet")) {
            pid = *i;
            planetFound = true;
        }
    }
    if(!planetFound) {
        Logger::getLogger()->debug("Colonize Order: No planet found in target star system");
        return false;
    }

    //Add resource to planet
    Planet* planet = (Planet*)(obm->getObject(pid)->getObjectBehaviour());
    Design::Ptr ship = Game::getGame()->getDesignStore()->getDesign(fleetData->getShips().begin()->first);
    uint32_t scoreType = 0;
    string leaderName;
    if(ship->getName().compare("MerchantShip") == 0) {
        planet->addResource(4, 1);
        scoreType = 1;
        leaderName = "MerchantLeaderShip";
    } else if(ship->getName().compare("ScientistShip") == 0) {
        planet->addResource(5, 1);
        scoreType = 2;
        leaderName = "ScientistLeaderShip";
    } else if(ship->getName().compare("SettlerShip") == 0) {
        planet->addResource(6, 1);
        scoreType = 3;
        leaderName = "SettlerLeaderShip";
    } else if(ship->getName().compare("MiningShip") == 0) {
        planet->addResource(7, 1);
        scoreType = 4;
        leaderName = "MiningLeaderShip";
    }

    //Get bordering star systems' regions
    StarSystem* starSysData = (StarSystem*)(newStarSys->getObjectBehaviour());
    set<uint32_t> regions = getBorderingRegions();
    
    //Put the newly colonized ship into the proper region
    //If it does not border any regions, then set it to a new one with a unique id
    if(regions.size() == 0) {
        starSysData->setRegion(starSys->getObjectId());
        stringstream out;
        out << starSysData->getRegion();
        Logger::getLogger()->debug(string("System " + newStarSys->getName() + " added to region " + out.str()).c_str());
    } else if(regions.size() == 1) {
        // Add +1 to the resource score of the player with the correct leader 
        // in this region
        
        int leaderID = getLeaderInRegion(*(regions.begin()), leaderName);
        if(leaderID < 0 && leaderName.compare("SettlerLeaderShip") != 0) {
            leaderID = getLeaderInRegion(*(regions.begin()), "SettlerLeaderShip");
        }
        if(leaderID >= 0) {
            Fleet* leader = (Fleet*) ((obm->getObject((uint32_t) leaderID))->getObjectBehaviour());
            Player::Ptr owner = Game::getGame()->getPlayerManager()->getPlayer(leader->getOwner());
            owner->setScore(scoreType, owner->getScore(scoreType) + 1);
        }    

        //Add the newly colonized system to the region
        starSysData->setRegion(*(regions.begin()));
        stringstream out;
        out << starSysData->getRegion();
        Logger::getLogger()->debug(string("System " + newStarSys->getName() + " added to region " + out.str()).c_str());
    } else {
        // This means that 2 regions are being connected. Perform check
        // for external combat
        map<uint32_t, uint32_t> settlers;
        map<uint32_t, uint32_t> scientists;
        map<uint32_t, uint32_t> merchants;
        map<uint32_t, uint32_t> miners;
        for(set<uint32_t>::iterator i = regions.begin(); i != regions.end(); i++) {
            int temp = getLeaderInRegion(*i, "SettlerLeaderShip");
            if(temp != -1) {
                settlers[temp] = *i;
            }
            temp = getLeaderInRegion(*i, "ScientistLeaderShip");
            if(temp != -1) {
                scientists[temp] = *i;
            }
            temp = getLeaderInRegion(*i, "MerchantLeaderShip");
            if(temp != -1) {
                merchants[temp] = *i;
            }
            temp = getLeaderInRegion(*i, "MiningLeaderShip");
            if(temp != -1) {
                miners[temp] = *i;
            }
        }

        TaeTurn* turn = (TaeTurn*) Game::getGame()->getTurnProcess();
        bool conflict = false;
        if(settlers.size() > 1) {
            //Settler Conflict!
            turn->queueCombatTurn(false, settlers);
            conflict = true;
        }
        if(scientists.size() > 1) {
            //Scientist Conflict!
            turn->queueCombatTurn(false, scientists);
            conflict = true;
        }
        if(merchants.size() > 1) {
            //Merchant Conflict!
            turn->queueCombatTurn(false, merchants);
            conflict = true;
        }
        if(miners.size() > 1) {
            //Miner Conflict!
            turn->queueCombatTurn(false, miners);
            conflict = true;
        }
        
        if(!conflict) {
            uint32_t region = *(regions.begin());
            set<uint32_t> objects = obm->getAllIds();
            for(set<uint32_t>::iterator i = objects.begin(); i != objects.end(); i++) {
                IGObject::Ptr ob = obm->getObject(*i);
                if(ob->getType() == obtm->getObjectTypeByName("Star System")) {
                    StarSystem* sys = (StarSystem*) ob->getObjectBehaviour();
                    uint32_t r = sys->getRegion();
                    if(r != region && regions.count(r) > 0) {
                        sys->setRegion(region);
                    }
                }
            }
        }
    }

    obm->doneWithObject(newStarSys->getID());
   
 
    // post completion message
    Message::Ptr msg( new Message() );
    msg->setSubject("Colonize fleet order complete");
    msg->setBody(string("You're fleet, \"" + obj->getName() + "\" has colonized ")
            + newStarSys->getName() + ".");
    msg->addReference(rst_Action_Order, rsorav_Completion);
    msg->addReference(rst_Object, starSys->getObjectId());
    msg->addReference(rst_Object, obj->getID());

    player->postToBoard(msg);

    //Remove fleet
    obj->removeFromParent();
    obm->scheduleRemoveObject(obj->getID());

    return true;
}
Exemplo n.º 23
0
void GameController::onChangeTurn()
{
  currentTurn++;

  /* impose production on owned planets */
  for(int i=0; i<players.size(); i++)
    {
      Player* tempP = players[i];
      for(int j=0; j<players[i]->getPlanets().size(); j++)
	{
	  Planet* tempPl = tempP->getPlanets()[j];
	  tempPl->setShips( tempPl->getShips() +  tempPl->getProduction());
	}
    }

  for(int k=0; k<fleets.size(); k++)
    {
      Fleet* tempF = fleets[k];
      /* fleet has arrived */
      if(fleets[k]->getArrivalTurn() == currentTurn)
	{
	  /* fleet owner same as destination owner, so reinforcing a planet */
	  if(tempF->getOwner() == tempF->getDestination()->getOwner())
	    {
	      tempF->getDestination()->setShips(tempF->getDestination()->getShips() + tempF->getNumShips());
	    }
	  else /* attacking planet */
	    {
	      double attackScore, defenseScore;

	      attackScore = tempF->getNumShips()*tempF->getKillPercent();
	      defenseScore = tempF->getDestination()->getShips()*tempF->getDestination()->getKillPercent();

	      if(attackScore >= defenseScore) /* attackers win */
		{
		  if(tempF->getDestination()->getOwner() != NULL)
		    tempF->getDestination()->getOwner()->removeFromPlanets(tempF->getDestination());

		  tempF->getOwner()->addToPlanets(tempF->getDestination());
		  tempF->getDestination()->setOwner(tempF->getOwner());
		  
		  tempF->getDestination()->setShips((int)attackScore-defenseScore);
		  emit displayInfo(QString("Turn %1: Planet %2 has fallen to %3").arg(currentTurn).arg(tempF->getDestination()->getName()).arg(tempF->getOwner()->getName()));
		  
		}
	      else /* defense wins */
		{
		  tempF->getDestination()->setShips((int)defenseScore-attackScore);
		  emit displayInfo(QString("Turn %1: Planet %2 has held against an attack from %3.").arg(currentTurn).arg(tempF->getDestination()->getName()).arg(tempF->getOwner()->getName()));
		}
	    }
	  /* processed fleet, so remove it */
	  fleets.removeAt(k);
	}
    }
     

  if(currentPlayer < players.size() - 1)
    currentPlayer++;
  else
    currentPlayer = 0;

  emit displayControl(QString("<font color=%1>%2</font>:Select source planet").arg(players[currentPlayer]->getColor().name()).arg(players[currentPlayer]->getName()));
}
Exemplo n.º 24
0
void PlanetWarsGame::reset() {
    this->logMessage("Reloading the game... ");

    //Attempt to read the map from file.
    std::ifstream mapFile(m_mapFileName.c_str());

    if (mapFile.fail()) {
        this->logError("Unable to open the map file.");
        return;
    }

    std::string mapString = std::string(std::istreambuf_iterator<char>(mapFile), std::istreambuf_iterator<char>());

    //Attempt to parse the map.
    bool failed = false;
    std::vector<Planet*> planets;
    std::list<Fleet*> fleets;

    //Lines on which we find fleets.
    std::vector<size_t> fleetLines;

    //Process each line in the map file, reading the fleet and planet information from
    //respective lines.
    std::vector<std::string> lines = Tokenize(mapString, "\n");

    for (size_t i = 0; i < lines.size(); ++i) {
        std::string& line = lines[i];

        //Remove comments.
        size_t commentBegin = line.find('#');

        if (commentBegin != std::string::npos)
            line = line.substr(0, commentBegin);

        if (TrimSpaces(line).size() == 0) continue;

        //Split the line into individual elements.
        std::vector<std::string> tokens = Tokenize(line, " ");

        if (tokens.size() == 0) continue;

        if (tokens[0] == "P") {
            //Record a planet.
            if (tokens.size() != 6) {
                std::stringstream message;
                message <<"Map file error [line " << i
                        << "]: expected 6 tokens on a planet line, have " << tokens.size() <<".";
                this->logError(message.str());
                failed = true;
                break;
            }

            Planet* planet = new Planet(this);
            planet->setX(atof(tokens[1].c_str()));
            planet->setY(atof(tokens[2].c_str()));
            planet->setOwner(this->getPlayer(atoi(tokens[3].c_str())));
            planet->setNumShips(atoi(tokens[4].c_str()));
            planet->setGrowthRate(atoi(tokens[5].c_str()));
            planet->setId(planets.size());
            planet->setGame(this);

            planets.push_back(planet);

        } else if (tokens[0] == "F") {
            //Record a fleet.
            if (tokens.size() != 7) {
                std::stringstream message;
                message <<"Map file error [line " << i
                        << "]: expected 7 tokens on a fleet line, have " << tokens.size() <<".";
                this->logError(message.str());
                failed = true;
                break;
            }

            Fleet* fleet = new Fleet(this);
            fleet->setOwner(this->getPlayer(atoi(tokens[1].c_str())));
            fleet->setNumShips(atoi(tokens[2].c_str()));
            fleet->setSourceId(atoi(tokens[3].c_str()));
            fleet->setDestinationId(atoi(tokens[4].c_str()));
            fleet->setTotalTripLength(atoi(tokens[5].c_str()));
            fleet->setTurnsRemaining(atoi(tokens[6].c_str()));

            fleets.push_back(fleet);
            fleetLines.push_back(i);

        } else {
            std::stringstream message;
            message << "Map file error [line " << i
                    << "]: a non-empty line that does not contain a planet or a fleet.";
            this->logError(message.str());
            failed = true;
            break;
        }
    }

    const int numPlanets = static_cast<int>(planets.size());

    //Resolve planet references inside fleets.
    int fleetIndex = 0;

    if (!failed) {
        for (FleetList::iterator it = fleets.begin(); it != fleets.end(); ++it) {
            Fleet* fleet = *it;

            //Attempt to resolve the source planet.
            const int sourceId = fleet->getSourceId();

            if (sourceId < 0 || sourceId >= numPlanets) {
                std::stringstream message;
                message << "Map file error [line " << fleetLines[fleetIndex]
                        << "]: fleet refers to an invalid planet with id=" << sourceId << ".";
                this->logError(message.str());
                failed = true;
                break;

            } else {
                fleet->setSource(planets[sourceId]);
            }

            //Attempt to resolve the destination planet.
            const int destinationId = fleet->getDestinationId();

            if (destinationId < 0 || destinationId >= numPlanets) {
                std::stringstream message;
                message << "Map file error [line " << fleetLines[fleetIndex]
                        << "]: fleet refers to an invalid planet with id=" << destinationId << ".";
                this->logError(message.str());
                failed = true;
                break;

            } else {
                fleet->setDestination(planets[destinationId]);
            }

            //This will force recalculation of the current position.
            fleet->setTurnsRemaining(fleet->getTurnsRemaining());

            ++fleetIndex;
        }
    }

    if (failed) {
        //Clean up.
        for (int i = 0; i < numPlanets; ++i) delete planets[i];
        for (FleetList::iterator it = fleets.begin(); it != fleets.end(); ++it) delete *it;

        return;
    }

    //Parsed the map successfully. Reset the game.
    //Stop any running processes.
    this->stop();
    this->stopPlayers();

    //If didn't fail, replace the old planets and fleets with the new.
    const int numOldPlanets = static_cast<int>(m_planets.size());
    for (int i = 0; i < numOldPlanets; ++i) delete m_planets[i];
    for (FleetList::iterator it = m_fleets.begin(); it != m_fleets.end(); ++it) delete (*it);

    m_planets = planets;
    m_fleets = fleets;
    m_newFleets.insert(m_newFleets.end(), fleets.begin(), fleets.end());

    //Reset all flags and counters.
    m_state = RESET;
    m_turn = 0;

    //Notify everyone of the resetn
    this->logMessage("================= Game reset. ==================");
    emit wasReset();
}
Exemplo n.º 25
0
int main ( int argc, char** argv ){

    if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }
    // make sure SDL cleans up before exit
    atexit(SDL_Quit);
    // create a new window
    screen = SDL_SetVideoMode(900, 600, 8, SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen ) {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }


    Fleet f;
    Bullet b3;
    f.asignBullet(&b3);



    Barrier bar1(000,98,1);
   	/* Barrier bar2(000,200,1);
    Barrier bar3(000,300,1);
	Barrier bar4(000,400,0);
	Barrier bar5(000,500,0);
	Barrier bar6(000,599,0);*/


    Ship s2;
    s2.position(  (GAME_W /2)  + 100 ,GAME_H-30);
	//s2.setMode(2);
   	Bullet b2;
    b2.setDownOrientation();
    s2.asignBullet(&b2);


    Ship s1;
	//s1.setMode(1);
    s1.position( (GAME_W / 2)- 100 , GAME_H-30);
    Bullet b1;
    s1.asignBullet(&b1);


    SideBar sb;



    actors.push_back(&b1);
    actors.push_back(&b2);
   // actors.push_back(&b3);
   // actors.push_back(&f);

    actors.push_back(&bar1);


    Bonus bonus;
    actors.push_back(&bonus);
    actors.push_back(&sb);

    Stairs stairs(160,98,1);
    actors.push_back(&stairs);   

    actors.push_back(&s1);
    actors.push_back(&s2);

    Uint8 * keystate;
    bool done = false;

    while (!done)
    {
        //Start the frame timer
        fps.start();

        keystate = SDL_GetKeyState(NULL);
        if(keystate[SDLK_LEFT]) {
        	//if(!s1.climbing){
            	s1.moveLeft();
        	//}
        }
        if(keystate[SDLK_RIGHT]) {
            s1.moveRight();
        }

        if(keystate[SDLK_UP]) {
        	int collided = 0;
        	if(s1.onGround){
	        	for (int i=0; i<Stairs::SHIPS_QTY; i++) {
	                if (check_collision(s1.rect,stairs.rect[i])) {
	                	s1.climbing = true;
	                	s1.moveUp();
	                	collided = 1;
	                	//std::cout << "Climbing en true??" << s1.climbing << "\n";
	                }
	            }
				if(!collided){
					std::cout << "ELSEClimbing en true??" << s1.climbing << "\n";

	                s1.climbing= false;
	                s1.onGround = false;

	        		/*std::cout << "stairs width " << stairs.rect[1].w << "\n";
	        		std::cout << "stairs height " << stairs.rect[1].h << "\n";*/
				}
			}

        }

        if(keystate[SDLK_DOWN]) {
        	for (int i=0; i<Stairs::SHIPS_QTY; i++) {
                if (check_collision(s1.rect,stairs.rect[i])) {
                	SDL_Rect * r;
                	r = bar1.getNextBaseFloor(stairs.rect[i].y+stairs.rect[i].h);
                	std::cout << "Recta a chequear <<<<<<< " << r->y << " \n";
                	if(s1.rect.y+s1.rect.h >= r->y){
                		std::cout << "Entra al if " << "  \n"; 
                		s1.onGround = false;
                		s1.climbing = false;
                	} else{
                	s1.climbing = true;
                	//S1.climbingDown = true;
                	s1.moveDown();

					}
                	//std::cout << "Climbing en true??" << s1.climbing << "\n";
       
                }else{
                	//std::cout << "Entra al else Climbing en true??" << s1.climbing << "\n";
                	//s1.climbing= false;
                	//s1.onGround = false;
                }
            }            	
        }

        if(keystate[SDLK_a]) {
            s2.moveLeft();
        }
        if(keystate[SDLK_d]) {
            s2.moveRight();
        }

        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
                case SDL_QUIT:
                    done = true;
                    break;
                // check for keypresses
                case SDL_KEYDOWN:
                        // exit if ESCAPE is pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE) {
                       done = true;
                    }

                    if (event.key.keysym.sym == SDLK_w) {
                        s2.jump();
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        s1.jump();
                    }
                break;
            } // end switch
        }

	    // clear screen
	    SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));



		
	    for(std::vector<IActor*>::iterator it = actors.begin(); it != actors.end(); ++it) {
	        (*it)->blit();
	    }

	    if(!s1.climbing  && !s1.onGround){

	    	for (int i=0; i<Barrier::SHIPS_QTY; i++) {
                if (check_collision(s1.rect,bar1.rect[i])) {
                	//s1.climbing = true;
                	//S1.climbingDown = true;
                	//std::cout << "Climbing en true??" << s1.climbing << "\n";
                	//s1.moveDown();
	               /* std::cout << "entra en collision con bar" << i << " \n";
			    	std::cout << "climb" << s1.climbing << "\n";
			    	std::cout << "onGround" << s1.onGround << "\n";
			    	std::cout << "end col" << "\n";*/
			    	s1.rect.y = bar1.rect[i].y-28;
		        	s1.speedY = 0.0;
		        	s1.onGround = true;
	        	}
            }
	    	    
		}

		if(s1.climbing){
			int collided = 0;
        	for (int i=0; i<Stairs::SHIPS_QTY; i++) {
                if (check_collision(s1.rect,stairs.rect[i])) {
                	//s1.climbing = true;
                	//s1.moveUp();
                	collided = 1;
                	//std::cout << "Climbing en true??" << s1.climbing << "\n";
                }
            }
			if(!collided){
				//std::cout << "ELSEClimbing en true??" << s1.climbing << "\n";
                s1.climbing= false;
                s1.onGround = false;
        		//std::cout << "stairs width " << stairs.rect[1].w << "\n";
        		//std::cout << "stairs height " << stairs.rect[1].h << "\n";
			}
		}




    	for (int i=0; i<Stairs::SHIPS_QTY; i++) {
            if (check_collision(bonus.rect,stairs.rect[i])) {
            	SDL_Rect * r;
            	r = bar1.getNextBaseFloor(stairs.rect[i].y+stairs.rect[i].h);
            	//std::cout << "Recta a chequear <<<<<<< " << r->y << " \n";
            	if(bonus.rect.y+bonus.rect.h > r->y){
            		//std::cout << "Entra al if " << "  \n"; 
            		//s1.onGround = false;
            		bonus.climbing = false;
            	} else{
            	bonus.climbing = true;
            	//S1.climbingDown = true;
            	//s1.moveDown();

				}
            	//std::cout << "Climbing en true??" << s1.climbing << "\n";
   
            }else{
            	//std::cout << "Entra al else Climbing en true??" << s1.climbing << "\n";
            	//s1.climbing= false;
            	//s1.onGround = false;
            }
        }


	        
	    SDL_Flip(screen);

	    //Cap the frame rate
	    if (fps.get_ticks() < 1000 / FRAMES_PER_SECOND) {
	        SDL_Delay( (1000 / FRAMES_PER_SECOND) - fps.get_ticks() );
	    }

	}//end game loop




    for(std::vector<IActor*>::iterator it = actors.begin(); it != actors.end(); ++it) {
        (*it)->free();
    }

    printf("Exited cleanly\n");
    return 0;
}
Exemplo n.º 26
0
bool Build::doOrder(IGObject::Ptr ob)
{
  
  Planet* planet = static_cast<Planet*>(ob->getObjectBehaviour());

  uint32_t usedshipres = resources[1];
  
  if(usedshipres == 0)
    return true;

  int ownerid = planet->getOwner();
  if(ownerid == 0){
      //currently not owned by anyone, just forget about it
      return true;
  }
  
  planet->addResource(1, 1);
    
  if(planet->removeResource(1, usedshipres)){
    //create fleet
    
    Game* game = Game::getGame();
    
    
    IGObject::Ptr fleet = game->getObjectManager()->createNewObject();
    game->getObjectTypeManager()->setupObject(fleet, game->getObjectTypeManager()->getObjectTypeByName("Fleet"));
    
    //add fleet to container
    fleet->addToParent(ob->getID());
    
    fleet->setName(fleetname->getString().c_str());
    
    Fleet * thefleet = ((Fleet*)(fleet->getObjectBehaviour()));
    
    thefleet->setSize(2);
    thefleet->setOwner(ownerid); // set ownerid
    thefleet->setPosition(planet->getPosition());
    thefleet->setVelocity(Vector3d(0LL, 0ll, 0ll));
    
    uint32_t queueid = Game::getGame()->getOrderManager()->addOrderQueue(fleet->getID(), ownerid);
    OrderQueueObjectParam* oqop = static_cast<OrderQueueObjectParam*>(fleet->getParameterByType(obpT_Order_Queue));
    oqop->setQueueId(queueid);
    thefleet->setDefaultOrderTypes();
    thefleet->setIcon("common/object-icons/ship");
    thefleet->setMedia("common-2d/foreign/vegastrike/ship-small/" + ((MiniSec*)(game->getRuleset()))->getFleetMediaNames()->getName());
    
    //set ship type
    IdMap fleettype = fleetlist->getList();
    for(IdMap::iterator itcurr = fleettype.begin(); itcurr != fleettype.end(); ++itcurr){
      thefleet->addShips(itcurr->first, itcurr->second);
      Design::Ptr design = Game::getGame()->getDesignStore()->getDesign(itcurr->first);
        design->addComplete(itcurr->second);
        Game::getGame()->getDesignStore()->designCountsUpdated(design);
    }
    //add fleet to universe
    Game::getGame()->getObjectManager()->addObject(fleet);
    Game::getGame()->getPlayerManager()->getPlayer(ownerid)->getPlayerView()->addOwnedObject(fleet->getID());

    Message::Ptr msg( new Message() );
    msg->setSubject("Build Fleet order complete");
    msg->setBody(std::string("The construction of your new fleet \"") + fleetname->getString() + "\" is complete.");
    msg->addReference(rst_Action_Order, rsorav_Completion);
    msg->addReference(rst_Object, fleet->getID());
    msg->addReference(rst_Object, ob->getID());
 
    Game::getGame()->getPlayerManager()->getPlayer(ownerid)->postToBoard(msg);

    return true;
  }
  return false;
}
Exemplo n.º 27
0
bool PlanetWarsGame::processOrders(const std::string &allOrders, Player *player) {
    std::vector<std::string> lines = Tokenize(allOrders, "\r\n");
    const int numLines = static_cast<int>(lines.size());

    //Indicator whether "go" message was encountered.
    bool foundGo = false;


    for (int i = 0; i < numLines; ++i) {
        std::string& line = lines[i];

        if (line.size() == 0) {
            //Skip empty lines.
            continue;

        } else if (line.compare("go") == 0) {
            foundGo = true;
            break;
        }
        else if (line[0] == '#') {
            if (line.size() < 2 || line[1] != '-')
                continue;
            std::vector<std::string> tokens = Tokenize(line, " ");
            tokens.erase(tokens.begin());
            if (tokens.size() == 4 && tokens[0] == "planet") {
                int planetId = atoi(tokens[1].c_str());
                const std::string& name = tokens[2];
                const std::string& value = tokens[3];

                Planet* planet = m_planets[planetId];
                planet->setProperty(name, value);
            }
            continue;
        }


        std::vector<std::string> tokens = Tokenize(line, " ");

        //Check whether the player bot output a bad thing.
        if (3 != tokens.size()) {
            std::stringstream message;
            message << "Error on line " << i << " of stdout output; expected 3 tokens on a move order line, have "
                    << tokens.size() << ".";
            player->logError(message.str());
            return false;
        }

        const int sourcePlanetId = atoi(tokens[0].c_str());
        const int destinationPlanetId = atoi(tokens[1].c_str());
        const int numShips = atoi(tokens[2].c_str());

        //Check whether the player has made any illegal moves.
        const int numPlanets = static_cast<int>(m_planets.size());

        if (sourcePlanetId < 0 || sourcePlanetId >= numPlanets) {
            std::stringstream message;
            message << "Error on line " << i << " of stdout output.  Source planet "
                    << sourcePlanetId << " does not exist.";
            player->logError(message.str());
            return false;
        }

        if (destinationPlanetId < 0 || destinationPlanetId >= numPlanets) {
            std::stringstream message;
            message << "Error on line " << i << " of stdout output.  Destination planet "
                    << destinationPlanetId << " does not exist.";
            player->logError(message.str());
            return false;
        }

        if (sourcePlanetId == destinationPlanetId) {
            std::stringstream message;
            message << "Error on line " << i
                    << " of stdout output.  Source planet and destination planet are the same. ";
            player->logError(message.str());
            return false;
        }

        Planet* sourcePlanet = m_planets[sourcePlanetId];
        Planet* destinationPlanet = m_planets[destinationPlanetId];

        if (sourcePlanet->getOwner()->getId() != player->getId()) {
            std::stringstream message;
            message << "Error on line " << i << " of stdout output.  Source planet "
                    << destinationPlanetId << " does not belong to this player.";
            player->logError(message.str());
            return false;
        }

        if (numShips > sourcePlanet->getNumShips() || numShips < 0) {
            std::stringstream message;
            message << "Error on line " << i << " of stdout output.  Cannot send " << numShips
                    << " ships from planet " << sourcePlanetId
                    << ".  Planet has " << sourcePlanet->getNumShips() << " ships.";
            player->logError(message.str());
            return false;
        }

        sourcePlanet->setNumShips(sourcePlanet->getNumShips() - numShips);

        //Create a new fleet.
        Fleet* fleet = new Fleet(this);
        fleet->setOwner(player);
        fleet->setSource(sourcePlanet);
        fleet->setDestination(destinationPlanet);
        fleet->setNumShips(numShips);
        const int distance = sourcePlanet->getDistanceTo(destinationPlanet);
        fleet->setTotalTripLength(distance);
        fleet->setTurnsRemaining(distance);

        m_newFleets.push_back(fleet);
        m_fleets.push_back(fleet);
    }

    if (!foundGo) {
        std::stringstream message;
        message << "Error: player did not send \"go\" within allotted time.";
        player->logError(message.str());
        return false;
    }

    return true;
}
Exemplo n.º 28
0
void PlanetWarsGame::completeStep() {
    //Proceed only if there's an unfinished step.
    if (STEPPING != m_state) {
        return;
    }

    m_state = PROCESSING;

    //Clear the old new fleets.
    m_newFleets.clear();

    //Read and process the the responses from each of the players.
    std::string firstPlayerOutput(m_firstPlayer->readCommands());
    std::string secondPlayerOutput(m_secondPlayer->readCommands());

    bool isFirstPlayerRunning = this->processOrders(firstPlayerOutput, m_firstPlayer);
    bool isSecondPlayerRunning = this->processOrders(secondPlayerOutput, m_secondPlayer);

    //Check whether the players are still alive.
    if (!isFirstPlayerRunning || !isSecondPlayerRunning) {
        this->stop();
        return;
    }

    this->advanceGame();

    //Check each player's position.
    int firstPlayerShips = 0;
    int secondPlayerShips = 0;

    const int numPlanets = static_cast<int>(m_planets.size());

    for (int i = 0; i < numPlanets; ++i) {
        Planet* planet = m_planets[i];
        const int ownerId = planet->getOwner()->getId();

        if (1 == ownerId) {
            firstPlayerShips += planet->getNumShips();

        } else if (2 == ownerId) {
            secondPlayerShips += planet->getNumShips();
        }
    }

    for (FleetList::iterator it = m_fleets.begin(); it != m_fleets.end(); ++it) {
        Fleet* fleet = *it;

        if (1 == fleet->getOwner()->getId()) {
            firstPlayerShips += fleet->getNumShips();

        } else {
            secondPlayerShips += fleet->getNumShips();
        }
    }

    emit turnEnded();

    //Check for game end conditions.
    bool isGameOver = false;

    if (firstPlayerShips == 0 && secondPlayerShips == 0) {
        this->logMessage("Draw.");
        isGameOver = true;

    } else if (firstPlayerShips == 0) {
        this->logMessage("Player 2 wins.");
        isGameOver = true;

    } else if (secondPlayerShips == 0) {
        this->logMessage("Player 1 wins.");
        isGameOver = true;

    } else if (m_turn >= m_maxTurns) {
        if (firstPlayerShips > secondPlayerShips) {
            this->logMessage("Player 1 wins.");
            isGameOver = true;

        } else if (firstPlayerShips < secondPlayerShips) {
            this->logMessage("Player 2 wins.");
            isGameOver = true;

        } else {
            this->logMessage("Draw.");
            isGameOver = true;
        }
    }

    if (isGameOver) {
        this->stop();
        return;
    }

    //Game is not over.
    m_state = READY;
    this->continueRunning();
}
Exemplo n.º 29
0
void CargoHolder::ProcessLoad(CargoHolder * dest, CargoType ct, TransferType tt, long value, bool dunnage)	// value usage depends on TransferType
{
	assert(dest->IsWith(*this));
	assert(dest != this);

	if (value < 0) {
		Message * mess = NCGetOwner()->AddMessage("Error: Transfer order is negative", this);
		mess->AddLong("Amount transferred", value);
		return;
	}

	if (value > Rules::GetConstant("MaxTransfer")) {
		Message * mess = NCGetOwner()->AddMessage("Error: Transfer order is over max", this);
		mess->AddLong("Amount transferred", value);
		return;
	}

	long destAmt = dest->GetContain(ct);
	if (GetOwner() != dest->GetOwner() && (ct == POPULATION || !dest->CanLoadBy(GetOwner())))
		destAmt = 0;

	long amount = 0;	// actual amount moved;
	switch (tt) {
	case TRANSFER_DROPNLOAD:
	case TRANSFER_LOADALL:
		if (dunnage) break;
		amount = TransferAmount(ct, dest, this, destAmt);
		break;

	case TRANSFER_UNLOADALL:
		break;

	case TRANSFER_LOADAMT:
		if (dunnage) break;
		amount = TransferAmount(ct, dest, this, value);
		break;

	case TRANSFER_UNLOADAMT:
		break;

	case TRANSFER_FILLPER:
	case TRANSFER_WAITPER:	// affects movement too
		if (dunnage) break;
		if (value > 100) {
			Message * mess = NCGetOwner()->AddMessage("Error: Transfer percent over 100%", this);
			mess->AddLong("Amount transferred", value);
			return;
		}
		amount = TransferAmount(ct, dest, this, GetCargoCapacity() * value / 100);
		break;

	case TRANSFER_LOADDUNN:
		if (!dunnage) break;
		// order of loading is different, but this is basicly a loadall -- execpt fuel
		if (ct == FUEL) {
			Fleet * f = dynamic_cast<Fleet *>(this);
			int Need = f->GetFuelNeeded() - f->GetFuel();
			if (Need > 0)
				amount = TransferAmount(ct, dest, this, Need);
			else
				amount = -TransferAmount(ct, this, dest, -Need);
		} else {
			amount = TransferAmount(ct, dest, this, destAmt);
		}
		break;

	case TRANSFER_SETTOPER:
		if (value > 100) {
			Message * mess = NCGetOwner()->AddMessage("Error: Transfer percent over 100%", this);
			mess->AddLong("Amount transferred", value);
			return;
			
			
		}
		value = GetCargoCapacity() * value / 100;
		// drop to a regualr transfer amount
	case TRANSFER_AMOUNTTO:
		if (dunnage) break;
		if (GetContain(ct) < value)
			amount = TransferAmount(ct, dest, this, value - GetContain(ct));
		break;

	case TRANSFER_DESTTO:
		if (dunnage) break;
		if (destAmt > value)
			amount = TransferAmount(ct, dest, this, destAmt - value);
		break;

	default:
		Message * mess = NCGetOwner()->AddMessage("Error: Invalid transfer order", this);
		mess->AddLong("Transfer code", tt);
		return;
	}

	assert(amount >= 0 || tt == TRANSFER_LOADDUNN && ct == FUEL);

	if (amount > 0 && dest->GetOwner() != GetOwner()) {
		if (!dest->CanLoadBy(GetOwner())) {
			Message * mess = NCGetOwner()->AddMessage("Warning: No theiving component at location", this);
			mess->AddItem("", dest);
			return;
		} else if (!Rules::Stealable(ct)) {
			Message * mess = NCGetOwner()->AddMessage("Warning: Cargo cannot be stolen", this);
			mess->AddItem("", dest);
			mess->AddLong("Cargo type", ct);
			return;
		}
	}

	dest->AdjustAmounts(ct, -amount);	// remove cargo from destination
	AdjustAmounts(ct, amount);		// add it to the source
}
Exemplo n.º 30
0
void CargoHolder::TransferCargo(CargoHolder * dest, CargoType ct, long * amount, Player * player)
{
	if (*amount == 0)
		return;
	assert(*amount > 0);

	if (GetContain(ct) < *amount) {
		Message * mess = player->AddMessage("Warning: Transfer more then carried", this);
		mess->AddLong("Attempted amount", *amount);
		*amount = GetContain(ct);
		mess->AddLong("Actual amount", *amount);
	}

	if (ct == POPULATION) {
		*amount -= *amount % Rules::PopEQ1kT;	// only transfer full groups
		if (dest->GetCargoCapacity() >= 0 && dest->GetCargoCapacity() < dest->GetCargoMass() + (*amount / Rules::PopEQ1kT)) {
			Message * mess = player->AddMessage("Warning: Transfer more then capacity", this);
			mess->AddItem("", dest);
			mess->AddLong("Attempted amount", *amount);
			*amount = (dest->GetCargoCapacity() - dest->GetCargoMass()) * Rules::PopEQ1kT;
			mess->AddLong("Actual amount", *amount);
		}
	} else if (ct == FUEL) {
		Fleet * destf = dynamic_cast<Fleet *>(dest);
		if (destf->GetFuelCapacity() >= 0 && destf->GetFuelCapacity() < destf->GetFuel() + *amount) {
			Message * mess = player->AddMessage("Warning: Transfer more then capacity", this);
			mess->AddItem("", dest);
			mess->AddLong("Attempted amount", *amount);
			*amount = destf->GetFuelCapacity() - destf->GetFuel();
			mess->AddLong("Actual amount", *amount);
		}
	} else {
		if (dest->GetCargoCapacity() >= 0 && dest->GetCargoCapacity() < dest->GetCargoMass() + *amount) {
			Message * mess = player->AddMessage("Warning: Transfer more then capacity", this);
			mess->AddItem("", dest);
			mess->AddLong("Attempted amount", *amount);
			*amount = dest->GetCargoCapacity() - dest->GetCargoMass();
			mess->AddLong("Actual amount", *amount);
		}
	}

	if (ct == POPULATION && GetOwner() != dest->GetOwner()) {
		assert(false);	// should never get here now
		Planet * destp = dynamic_cast<Planet *>(dest);
		if (destp) {
			if (destp->GetBaseNumber() >= 0) {
				player->AddMessage("Warning: Invading world with base", this);
				return;
			} else {
				AdjustAmounts(ct, -*amount);
				destp->Invade(NCGetOwner(), *amount);
				return;
			}
		} else {
			Message * mess = player->AddMessage("Warning: Transfer pop to unowned fleet", this);
			mess->AddItem("", dest);
			return;
		}
	}

	dest->AdjustAmounts(ct, *amount);
	AdjustAmounts(ct, -*amount);
}