Exemple #1
0
bool DesignStore::addDesign(Design::Ptr d){
  d->setDesignId(next_designid++);

  //check components all come from this category
  IdMap cl = d->getComponents();
  Player::Ptr player = Game::getGame()->getPlayerManager()->getPlayer(d->getOwner());
  PlayerView::Ptr playerview = player->getPlayerView();
  for(IdMap::iterator itcurr = cl.begin(); 
      itcurr != cl.end(); ++itcurr){
    if(!(playerview->isUsableComponent(itcurr->first)))
      return false;
    std::map<uint32_t, Component::Ptr>::iterator itcomp = components.find(itcurr->first);
    if(itcomp == components.end())
      return false;
    getComponent(itcurr->first)->setInUse();
  }
  d->eval();
  designs[d->getId()] = d;
  getCategory(d->getCategoryId())->doAddDesign(d);

  if(d->isValid()){
    playerview->addUsableDesign(d->getId());
  }else{
    playerview->addVisibleDesign( DesignView::Ptr( new DesignView( d->getId(), true )) );
  }

  Game::getGame()->getPlayerManager()->updatePlayer(player->getID());
  Game::getGame()->getPersistence()->saveDesign(d);
  return true;
}
Exemple #2
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;
}
Exemple #3
0
ValueMap valmap_bind(IdMap &id, unsigned int code) {
    ValueMap valmap;
    unsigned int mask = 1;
    for (auto it = id.begin(); it != id.end(); ++it, mask <<= 1) {
        valmap[it->first] = (code & mask) == mask;
    }
    return valmap;
}
//
// CalcMetrics
// - Loop through the history and pre-calculate metrics used in the training 
// - Also re-number the customer id's to fit in a fixed array
//
void Engine::CalcMetrics()
{
    int i, cid;
    IdItr itr;

    wprintf(L"\nCalculating intermediate metrics\n");

    // Process each row in the training set
    for (i=0; i<m_nRatingCount; i++)
    {
        Data* rating = m_aRatings + i;

        // Increment movie stats
        m_aMovies[rating->MovieId].RatingCount++;
        m_aMovies[rating->MovieId].RatingSum += rating->Rating;
        
        // Add customers (using a map to re-number id's to array indexes) 
        itr = m_mCustIds.find(rating->CustId); 
        if (itr == m_mCustIds.end())
        {
            cid = 1 + (int)m_mCustIds.size();

            // Reserve new id and add lookup
            m_mCustIds[rating->CustId] = cid;

            // Store off old sparse id for later
            m_aCustomers[cid].CustomerId = rating->CustId;

            // Init vars to zero
            m_aCustomers[cid].RatingCount = 0;
            m_aCustomers[cid].RatingSum = 0;
        }
        else
        {
            cid = itr->second;
        }

        // Swap sparse id for compact one
        rating->CustId = cid;

        m_aCustomers[cid].RatingCount++;
        m_aCustomers[cid].RatingSum += rating->Rating;
    }

    // Do a follow-up loop to calc movie averages
    for (i=0; i<MAX_MOVIES; i++)
    {
        Movie* movie = m_aMovies+i;
        movie->RatingAvg = movie->RatingSum / (1.0 * movie->RatingCount);
        movie->PseudoAvg = (3.23 * 25 + movie->RatingSum) / (25.0 + movie->RatingCount);
    }
}
Exemple #5
0
void addEntityListToMapBasedOnBitSet( EntityList *listener, const IdMap &indices, map<size_t,vector<EntityList*>> &vmap )
{
	for (size_t i = 0; i < indices.size(); i++) {

		size_t id = indices.getId(i);
		auto iterator = vmap.find( id );

		if (iterator == vmap.end()) {
			vmap.insert({id, {listener}});
		} else {
			iterator.second.push_back(listener);
		}
	}
}
Exemple #6
0
void notifyListsInMap( Entity *e, const IdMap& indices, map<size_t,vector<EntityList*>> &vmap )
{
	for (size_t i = 0; i < indices.size(); i++) {

		size_t id = indices.getId(i);
		auto iterator = vmap.find( id );

		if (iterator != vmap.end()) {
			for (auto &listener : iterator.second) {
				listener.add( e );
			}
		}
	}
}
Exemple #7
0
void InitActorNumsFromMapinfo()
{
	DoomEdMap.Clear();
	IdMap::Iterator it(DoomEdFromMapinfo);
	IdMap::Pair *pair;
	int error = 0;

	while (it.NextPair(pair))
	{
		PClassActor *cls = NULL;
		if (pair->Value.classname != NAME_None)
		{
			cls = PClass::FindActor(pair->Value.classname);
			if (cls == NULL)
			{
				Printf(TEXTCOLOR_RED "Script error, \"%s\" line %d:\nUnknown actor class %s\n",
					pair->Value.filename.GetChars(), pair->Value.linenum, pair->Value.classname.GetChars());
				error++;
			}
		}
		FDoomEdEntry ent;
		ent.Type = cls;
		ent.Special = pair->Value.special;
		ent.ArgsDefined = pair->Value.argsdefined;
		ent.NoSkillFlags = pair->Value.noskillflags;
		memcpy(ent.Args, pair->Value.args, sizeof(ent.Args));
		DoomEdMap.Insert(pair->Key, ent);
	}
	if (error > 0)
	{
		I_Error("%d unknown actor classes found", error);
	}
	DoomEdFromMapinfo.Clear();	// we do not need this any longer
}
void 
FunctionDefinitionRecursion::determineCycles(const Model& m)
{
  IdIter it;
  IdRange range;
  IdList variables;
  IdMap logged;
  std::string id;
  variables.clear();

  /* create a list of variables that are cycles ie (x, x) */
  for (it = mIdMap.begin(); it != mIdMap.end(); it++)
  {
    if ((*it).first == (*it).second)
    {
      id = (*it).first;
      if (!variables.contains(id))
      {
        variables.append(id);
      }
    }
  }

  /* loop thru other dependencies for each; if the dependent is also
   * in the list then this is the cycle
   * keep a record of logged dependencies to avoid logging twice
   */
   
  for (unsigned int n = 0; n < variables.size(); n++)
  {
    id = variables.at((int)n);
    range = mIdMap.equal_range(id);
    for (it = range.first; it != range.second; it++)
    {
      if (((*it).second != id)
        && (variables.contains((*it).second))
        && !alreadyExistsInMap(logged, 
                   pair<const std::string, std::string>(id, (*it).second))
        && !alreadyExistsInMap(logged, 
                   pair<const std::string, std::string>((*it).second, id)))
      {
        logCycle(m.getFunctionDefinition(id), m.getFunctionDefinition((*it).second));
        logged.insert(pair<const std::string, std::string>(id, (*it).second));
      }
    }
  }
}
bool 
FunctionDefinitionRecursion::alreadyExistsInMap(IdMap map, 
                                     pair<const std::string, std::string> dependency)
{
  bool exists = false;

  IdIter it;
  
  for (it = map.begin(); it != map.end(); it++)
  {
    if (((*it).first == dependency.first)
      && ((*it).second == dependency.second))
      exists = true;
  }

  return exists;
}
bool 
ExtModelReferenceCycles::alreadyExistsInMap(IdMap map, 
                                     pair<const std::string, std::string> dependency)
{
  bool exists = false;

  IdIter it;
  
  for (it = map.begin(); it != map.end(); it++)
  {
    if (((*it).first == dependency.first)
      && ((*it).second == dependency.second))
      exists = true;
  }

  return exists;
}
Exemple #11
0
void Build::inputFrame(InputFrame::Ptr f, uint32_t playerid)
{
  Order::inputFrame(f, playerid);
  
  Player::Ptr player = Game::getGame()->getPlayerManager()->getPlayer(playerid);
  DesignStore::Ptr ds = Game::getGame()->getDesignStore();
  
  uint32_t bldTmPropID = ds->getPropertyByName( "BuildTime");
  
  IdMap fleettype = fleetlist->getList();
  uint32_t usedshipres = 0;
  
  for(IdMap::iterator itcurr = fleettype.begin();
     itcurr != fleettype.end(); ++itcurr) {
    uint32_t type = itcurr->first;
    uint32_t number = itcurr->second; // number to build
    
    if(player->getPlayerView()->isUsableDesign(type) && number >= 0){
      
      Design::Ptr design = ds->getDesign(type);
      usedshipres += (int)(ceil(number * design->getPropertyValue(bldTmPropID)));
        design->addUnderConstruction(number);
        ds->designCountsUpdated(design);

    }else{
      throw FrameException( fec_FrameError, "The requested design was not valid.");
    }
  }
  if(usedshipres == 0 && !fleettype.empty()){
    throw FrameException( fec_FrameError, "To build was empty...");
  }
  
  resources[1] = usedshipres;
  
  if(fleetname->getString().length() == 0){
    fleetname->setString("A Fleet");
  }
}
Exemple #12
0
bool DesignStore::modifyDesign(Design::Ptr d){
  Design::Ptr current = designs[d->getId()];
  if(!current || current->getOwner() != d->getOwner() || current->getNumExist() != 0 || current->getInUse() != 0)
    return false;
  Player::Ptr player = Game::getGame()->getPlayerManager()->getPlayer(d->getOwner());
  PlayerView::Ptr playerview = player->getPlayerView();
  playerview->removeUsableDesign(d->getId());

  IdMap cl = current->getComponents();
  for(IdMap::iterator itcurr = cl.begin(); itcurr != cl.end(); ++itcurr){
    components[itcurr->first]->setInUse(false);
  }
  for(IdMap::iterator itcurr = cl.begin(); itcurr != cl.end(); ++itcurr){
    if(!(playerview->isUsableComponent(itcurr->first)))
      return false;
    std::map<uint32_t, Component::Ptr>::iterator itcomp = components.find(itcurr->first);
    if(itcomp == components.end())
      return false;
    itcomp->second->setInUse();
  }

  d->eval();
  bool rtv;
  if(getCategory(d->getCategoryId())->doModifyDesign(d)){
    designs[d->getId()] = d;
    rtv = true;
  }else{
    d = current;
    rtv = false;
  }
  if(d->isValid()){
    playerview->addUsableDesign(d->getId());
  }
  Game::getGame()->getPlayerManager()->updatePlayer(player->getID());
  Game::getGame()->getPersistence()->updateDesign(d);
  return rtv;
}
Exemple #13
0
std::ostream& operator<<(std::ostream &out, Entity &e)
{
  const size_t type = e.type->getId();

  out << "{";

  if (type == EntityType::CUSTOM) {
    out << "type:custom, "; 
  } else {
    out << "type:" << type << ", ";
  }
  
  out << "expired:" << (e.expired ? "true" : "false") << ", ";
  out << "visible:" << (e.visible ? "true" : "false") << ", ";
  out << "enabled:" << (e.enabled ? "true" : "false") << ", ";

  IdMap components = e.type->getComponents();

  for (size_t i = 0; i < components.size(); i++) {
    size_t componentId = components.getId(i);
    size_t offset = components.getIndex(componentId);

    ComponentBase *componentBase = e.type->getCore()->getComponent(componentId);
    AnyMemory value = e.components.sub(offset, componentBase->defaultValue.getSize());

    out << componentBase->name << ":" << value << ", ";
  }

  out << "controllers:{";

  IdMap controllers = e.type->getControllers();

  for (size_t i = 0; i < controllers.size(); i++) {
    if (i > 0) {
      out << ",";
    }
    out << controllers.getId(i);
  }

  out << "}}";

  return out;
}
Exemple #14
0
int main(int argc, char **argv)
{
    IdMap idmap;
    ValueMap valmap;
    int permutations_size = 0;

    // Call the parser
    yyparse();
    if (root == NULL) {
        return 1;
    }

    // Find and print some information about identifiers
    std::cout << root->prettyPrint() << std::endl;
    find_identifiers(*root, idmap);
    std::cout << "Found " << idmap.size() << " unique identifiers" << std::endl;
    for (auto it = idmap.begin(); it != idmap.end(); ++it) {
        std::cout << it->first << ": " << it->second.size() << " occurrences" << std::endl;
    }

    // Check how many boolean permutations we need to generate
    if (idmap.size() <= 2) {
        permutations_size = 2;
    } else if (idmap.size() <= 4) {
        permutations_size = 4;
    } else {
        std::cout << "More than 4 identifiers not supported yet." << std::endl;
        return 2;
    }
    std::cout << "Generating a lut" << permutations_size << "." << std::endl;

    // Bind each possible permutation and evaluate the function
    std::cout << "0";
    for(unsigned int i = 0; i < permutations_size * permutations_size; ++i) {
        valmap = valmap_bind(idmap, i);
        std::cout << evaluate(*root, valmap);
    }
    std::cout << std::endl;

    return 0;
}
Exemple #15
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;
}
Exemple #16
0
bool Colonise::doOrder(IGObject::Ptr ob){
  //if not close, move
  IGObject::Ptr target = Game::getGame()->getObjectManager()->getObject(ob->getParent());
  if(target == NULL || target->getType() != Game::getGame()->getObjectTypeManager()->getObjectTypeByName("Planet")){
    
    Logger::getLogger()->debug("Object(%d)->Colonise->doOrder(): Target was not valid.", ob->getID());
    Game::getGame()->getObjectManager()->doneWithObject(ob->getParent());
    Message::Ptr msg( new Message() );
    msg->setSubject("Colonise order canceled");
    msg->setBody("Not at a planet, colonisation canceled");
    msg->addReference(rst_Action_Order, rsorav_Canceled);
    msg->addReference(rst_Object, ob->getID());
    Game::getGame()->getPlayerManager()->getPlayer(((Fleet*)(ob->getObjectBehaviour()))->getOwner())->postToBoard(msg);

    return true;
  }
  
  Fleet* fleet = (Fleet*)(ob->getObjectBehaviour());
  Planet* planet = (Planet*)(target->getObjectBehaviour());
  
    Message::Ptr msg( new Message() );
  msg->addReference(rst_Object, ob->getID());
  msg->addReference(rst_Object, target->getID());

  if(planet->getOwner() != fleet->getOwner()){

    if(planet->getOwner() != 0){
      Logger::getLogger()->debug("Object(%d)->Colonise->doOrder(): Planet already owned.", 
        ob->getID());
    
      msg->setSubject("Colonisation failed");
      msg->setBody("The planet you tried to colonise, is already owned by someone else.");
      msg->addReference(rst_Action_Order, rsorav_Canceled);
    }else{

      DesignStore::Ptr ds = Game::getGame()->getDesignStore();
      int shiptype = 0;
      int shiphp = 2000000;
      IdMap ships = fleet->getShips();
      uint32_t colonisePropID = ds->getPropertyByName( "Colonise");
      uint32_t armorPropID = ds->getPropertyByName( "Armour");
      for(IdMap::iterator itcurr = ships.begin();
	  itcurr != ships.end(); ++itcurr){
        Design::Ptr design = ds->getDesign(itcurr->first);
	if(design->getPropertyValue(colonisePropID) != 0.0 && shiphp > (int)design->getPropertyValue(armorPropID)){
	  shiptype = itcurr->first;
	  shiphp = (int)design->getPropertyValue(armorPropID);
	}
      }

      Logger::getLogger()->debug("Object(%d)->Colonise->doOrder(): shiptype %d", 
          ob->getID(), shiptype);
      if(shiptype != 0){
        uint32_t oldowner = planet->getOwner();
        planet->setOwner(fleet->getOwner());
        Game::getGame()->getPlayerManager()->getPlayer(fleet->getOwner())->getPlayerView()->addOwnedObject(target->getID());
        uint32_t queueid = static_cast<OrderQueueObjectParam*>(target->getParameterByType(obpT_Order_Queue))->getQueueId();
        OrderQueue::Ptr queue = Game::getGame()->getOrderManager()->getOrderQueue(queueid);
        queue->removeOwner(oldowner);
        queue->addOwner(fleet->getOwner());

        fleet->removeShips(shiptype, 1);

        msg->setSubject("Colonised planet");
        msg->setBody("You have colonised a planet!");
        msg->addReference(rst_Action_Order, rsorav_Completion);

      }else{
        msg->setSubject("Colonisation failed");
        msg->setBody("Your fleet did not have a frigate to colonise the planet");
        msg->addReference(rst_Action_Order, rsorav_Invalid);
      }

      if(fleet->totalShips() == 0){
        Game::getGame()->getObjectManager()->scheduleRemoveObject(ob->getID());
        Game::getGame()->getPlayerManager()->getPlayer(fleet->getOwner())->getPlayerView()->removeOwnedObject(ob->getID());
      }
      
    }
  }else{
    Logger::getLogger()->debug("Object(%d)->Colonise->doOrder(): Was already owned by the player!", 
      ob->getID());

    msg->setSubject("Colonisation failed");
    msg->setBody("You already own the planet you tried to colonise");
    msg->addReference(rst_Action_Order, rsorav_Canceled);
  }
  
  Game::getGame()->getPlayerManager()->getPlayer(fleet->getOwner())->postToBoard(msg);
  Game::getGame()->getObjectManager()->doneWithObject(target->getID());
  return true;
  
}
Exemple #17
0
bool MergeFleet::doOrder(IGObject::Ptr ob){
  IGObject::Ptr parent = Game::getGame()->getObjectManager()->getObject(ob->getParent());
  
  Fleet *myfleet = (Fleet*)(ob->getObjectBehaviour());
  //find fleet to merge with
  
  uint32_t targetid = 0;
  
  std::set<uint32_t> oblist = parent->getContainedObjects();
  for(std::set<uint32_t>::iterator itcurr = oblist.begin(); itcurr != oblist.end(); ++itcurr){
    if(*itcurr == ob->getID())
      continue;
    IGObject::Ptr ptarget = Game::getGame()->getObjectManager()->getObject(*itcurr);
    if(ptarget->getType() == ob->getType()){
      Fleet* pfleet = (Fleet*)(ptarget->getObjectBehaviour());
      if(pfleet->getOwner() == myfleet->getOwner()){
        if(pfleet->getSize() + myfleet->getSize() > pfleet->getPosition().getDistance(myfleet->getPosition())){
          targetid = *itcurr;
          Game::getGame()->getObjectManager()->doneWithObject(*itcurr);
          break;
        }
      }
    }
    Game::getGame()->getObjectManager()->doneWithObject(*itcurr);
  }

  if(targetid == 0){
    Message::Ptr msg( new Message() );
    msg->setSubject("Merge Fleet order canceled");
    msg->setBody("No target fleet at this location");
    msg->addReference(rst_Action_Order, rsorav_Canceled);
    msg->addReference(rst_Object, ob->getID());
    Game::getGame()->getPlayerManager()->getPlayer(((Fleet*)(ob->getObjectBehaviour()))->getOwner())->postToBoard(msg);
  }else{
  
    IGObject::Ptr target = Game::getGame()->getObjectManager()->getObject(targetid);

    Message::Ptr msg( new Message() );
    msg->setSubject("Merge Fleet order complete");
    msg->setBody("The two fleets have been merged");
    msg->addReference(rst_Action_Order, rsorav_Completion);
    msg->addReference(rst_Object, ob->getID());
    msg->addReference(rst_Object, target->getID());

    
    Fleet *tfleet = (Fleet*)(target->getObjectBehaviour());
      

    IdMap ships = myfleet->getShips();
    for(IdMap::iterator itcurr = ships.begin();
        itcurr != ships.end(); ++itcurr){
      tfleet->addShips(itcurr->first, itcurr->second);
    }

    //remove the fleet from the physical universe
    ob->removeFromParent();
    
    Game::getGame()->getObjectManager()->scheduleRemoveObject(ob->getID());
    Game::getGame()->getPlayerManager()->getPlayer(myfleet->getOwner())->getPlayerView()->removeOwnedObject(ob->getID());
	
    Game::getGame()->getObjectManager()->doneWithObject(target->getID());

    Game::getGame()->getPlayerManager()->getPlayer(myfleet->getOwner())->postToBoard(msg);
  }
  return true;
}
Exemple #18
0
void TpMzScheme::evalDesign(Design::Ptr d){

  DesignStore::Ptr ds = Game::getGame()->getDesignStore();
  
  if (scheme_setjmp(scheme_error_buf)) {
    Logger::getLogger()->warning("MzScheme Error");
  } else {
    Scheme_Object* temp;

    std::ostringstream formater;
   
    formater.str("");
    formater << "(define-values (struct:designType make-designType designType? designType-ref designType-set!)(make-design-type "
	     << ds->getMaxPropertyId() << "))";
    temp = scheme_eval_string(formater.str().c_str(), env);
    
    temp = scheme_eval_string("(define property-designType-set! (lambda (design id val) (designType-set! design (- id 1) val)))", env);

    std::set<uint32_t> propids = ds->getPropertyIds();
    for(std::set<uint32_t>::iterator propit = propids.begin();
	propit != propids.end(); ++propit){
      // for each property type
      Property::Ptr p = ds->getProperty(*propit);
      if(p){
	formater.str("");
	formater << "(define designType." << p->getName() 
		 << " (make-property-accessor designType-ref "
		 << p->getPropertyId() << " \"" << p->getName() 
		 << "\" ))";
	temp = scheme_eval_string(formater.str().c_str(), env);
	
      }
    }
    propids.clear();

        IdMap complist = d->getComponents();

    temp = scheme_eval_string("(define design (make-designType))", env);
    
    for(std::set<uint32_t>::iterator propit = propids.begin();
            propit != propids.end(); ++propit){
        formater.str("");
        formater << "(property-designType-set! design " 
                 << *propit << " 0.0)";
        temp = scheme_eval_string(formater.str().c_str(), env);
    }

        std::map<uint32_t, std::map<uint32_t, std::list<std::string> > > propranking;
        for(IdMap::iterator compit = complist.begin();
                compit != complist.end(); ++compit){
            Component::Ptr c = ds->getComponent(compit->first);
            std::map<uint32_t, std::string> pilist = c->getPropertyList();
            for(std::map<uint32_t, std::string>::iterator piit = pilist.begin();
                    piit != pilist.end(); ++piit){
                Property::Ptr p = ds->getProperty(piit->first);
                for(uint32_t i = 0; i < compit->second; i++){
                    propranking[p->getRank()][p->getPropertyId()].push_back(piit->second);
                }
      }

    }

    std::map<uint32_t, PropertyValue> propertyvalues;

    for(std::map<uint32_t, std::map<uint32_t, std::list<std::string> > >::iterator rpiit = propranking.begin();
	rpiit != propranking.end(); ++rpiit){
      std::map<uint32_t, std::list<std::string> > pilist = rpiit->second;
      std::set<PropertyValue> localvalues;
      for(std::map<uint32_t, std::list<std::string> >::iterator piit = pilist.begin();
	  piit != pilist.end(); ++piit){
	PropertyValue propval(piit->first,0.0);
	std::list<double> listvals;
	std::list<std::string> lambdas = piit->second;
	for(std::list<std::string>::iterator itlamb = lambdas.begin();
	    itlamb != lambdas.end(); ++itlamb){
	  temp = scheme_eval_string((std::string("(") + (*itlamb) + " design)").c_str(), env);
	  if(!SCHEME_NUMBERP(temp)){
	    Logger::getLogger()->warning("MzScheme: Return not a number");
	  }else{
	    listvals.push_back(scheme_real_to_double(temp));
	  }
	}
	Property::Ptr p = ds->getProperty(piit->first);
	formater.str("");
	formater << "(" <<  p->getTpclDisplayFunction() << " design '(";
	for(std::list<double>::iterator itvals = listvals.begin();
	    itvals != listvals.end(); ++itvals){
	  formater << *itvals << " ";
	}
	formater << "))";
	temp = scheme_eval_string(formater.str().c_str(), env);
#ifdef HAVE_MZSCHEME20X
	if(!SCHEME_PAIRP(temp) || !SCHEME_NUMBERP(SCHEME_CAR(temp)) || !SCHEME_STRINGP(SCHEME_CDR(temp))){
#else
	if(!SCHEME_PAIRP(temp) || !SCHEME_NUMBERP(SCHEME_CAR(temp)) || !SCHEME_CHAR_STRINGP(SCHEME_CDR(temp))){
#endif
	  Logger::getLogger()->warning("MzScheme: Return not a pair, or the wrong time in the pair");
	}else{
	  propval.setValue(scheme_real_to_double(SCHEME_CAR(temp)));
#ifdef HAVE_MZSCHEME20X
	  propval.setDisplayString(std::string(SCHEME_STR_VAL(SCHEME_CDR(temp)))); 
#else
	  propval.setDisplayString(std::string((char*)SCHEME_CHAR_STR_VAL(SCHEME_CDR(temp)))); 
#endif
	  localvalues.insert(propval);
	}
      }
      for(std::set<PropertyValue>::iterator pvit = localvalues.begin();
	  pvit != localvalues.end(); ++pvit){
	PropertyValue pv = *pvit;
	formater.str("");
	formater << "(property-designType-set! design " 
		 << pv.getPropertyId() << " " << pv.getValue()
		 << ")";
	temp = scheme_eval_string(formater.str().c_str(), env);
	propertyvalues[pv.getPropertyId()] = pv;
      }
    }

    d->setPropertyValues(propertyvalues);

    // now check if the design is valid
    
    bool valid = true;
    std::string feedback = "";
        Logger::getLogger()->debug("About to process requirement functions");

        for(IdMap::iterator compit = complist.begin();
                compit != complist.end();
                ++compit){
            uint32_t curval = compit->first;
      
      //for each component in the design
      temp = scheme_eval_string((std::string("(") + ds->getComponent(curval)->getTpclRequirementsFunction() + " design)").c_str(), env);
#ifdef HAVE_MZSCHEME20X
      if(!SCHEME_PAIRP(temp) || !SCHEME_STRINGP(SCHEME_CDR(temp))){
#else
      if(!SCHEME_PAIRP(temp) || !SCHEME_CHAR_STRINGP(SCHEME_CDR(temp))){
#endif
	Logger::getLogger()->warning("MzScheme: (a) Return not a pair, or the wrong time in the pair");
      }else{
	valid &= SCHEME_TRUEP(SCHEME_CAR(temp));
#ifdef HAVE_MZSCHEME20X
	std::string strtemp = SCHEME_STR_VAL(SCHEME_CDR(temp));
#else
	std::string strtemp = (char*)SCHEME_CHAR_STR_VAL(SCHEME_CDR(temp));
#endif
	if(strtemp.length() > 0)
	  feedback += strtemp + " ";
      }
    }

        for(std::map<uint32_t, std::map<uint32_t, std::list<std::string> > >::iterator rpiit = propranking.begin();
                rpiit != propranking.end(); ++rpiit){
            std::map<uint32_t, std::list<std::string> > pilist = rpiit->second;
            for(std::map<uint32_t, std::list<std::string> >::iterator piit = pilist.begin();
                    piit != pilist.end(); ++piit){
                temp = scheme_eval_string((std::string("(") + ds->getProperty(piit->first)->getTpclRequirementsFunction() + " design)").c_str(), env);
#ifdef HAVE_MZSCHEME20X
                if(!SCHEME_PAIRP(temp) || !SCHEME_STRINGP(SCHEME_CDR(temp))){
#else
                if(!SCHEME_PAIRP(temp) || !SCHEME_CHAR_STRINGP(SCHEME_CDR(temp))){
#endif
                    Logger::getLogger()->warning("MzScheme: (a) Return not a pair, or the wrong time in the pair");
                }else{
                    valid &= SCHEME_TRUEP(SCHEME_CAR(temp));
#ifdef HAVE_MZSCHEME20X
                    std::string strtemp = SCHEME_STR_VAL(SCHEME_CDR(temp));
#else
                    std::string strtemp = (char*)SCHEME_CHAR_STR_VAL(SCHEME_CDR(temp));
#endif
                    if(strtemp.length() > 0)
                        feedback += strtemp + " ";
                }
            }
        }

        propranking.clear();

    d->setValid(valid, feedback);
    

    Logger::getLogger()->debug("Eval'ed design");
    if(!valid){
        Logger::getLogger()->debug("Design %s is not valid, reason: %s", d->getName().c_str(), feedback.c_str());
    }
  }
  
}

TpMzScheme::TpMzScheme(){
    //scheme_set_stack_base(NULL, 1); /* required for OS X, only. WILL NOT WORK HERE */
    bool loaded = false;
  env = scheme_basic_env();
  if (scheme_setjmp(scheme_error_buf)) {
    Logger::getLogger()->warning("MzScheme warning: could not load local file, trying installed file");
  } else {
      scheme_eval_string("(load \"../modules/tpcl/mzscheme/designstruct.scm\")",env);
        loaded = true;
  }
    if(loaded == false){
        if (scheme_setjmp(scheme_error_buf)) {
            Logger::getLogger()->warning("MzScheme warning: could not load installed file");
        } else {
            scheme_eval_string("(load \"" DATADIR "/tpserver/tpscheme/mzscheme/designstruct.scm\")", env);
            loaded = true;
        }
    }
    if(loaded == false){
        Logger::getLogger()->error("MzScheme Error: failed to load designstruct.scm file");
        //throw exception?
    }
}
Exemple #19
0
void RSPCombat::doCombat(std::map<uint32_t, IdSet> sides) {
    Game* game = Game::getGame();
    PlayerManager::Ptr playermanager = game->getPlayerManager();
    ObjectManager* objectmanager = game->getObjectManager();
    DesignStore::Ptr ds = game->getDesignStore();

    const char * const rsp[] = {"rock", "scissors", "paper"};

    IdSet listallobids;
    IdSet listallplayerids;

    std::map<uint32_t, std::vector<Combatant*> > fleetcache;

    battlelogger.reset(new BattleXML::BattleLogger());
    msgstrings.clear();

    for(std::map<uint32_t, IdSet>::iterator itmap = sides.begin(); itmap != sides.end(); ++itmap) {
        std::vector<Combatant*> pcombatant;
        Player::Ptr player = playermanager->getPlayer(itmap->first);
        battlelogger->startSide(player->getName());
        IdSet theset = itmap->second;
        for(IdSet::iterator itset = theset.begin(); itset != theset.end(); ++itset) {
            listallobids.insert(*itset);
            IGObject::Ptr obj = objectmanager->getObject (*itset);
            objectcache[*itset] = obj;
            if(obj->getType() == obT_Fleet) {
                Fleet* f2 = (Fleet*)(obj->getObjectBehaviour());
                IdMap shiplist = f2->getShips();
                uint32_t damage = f2->getDamage();
                for(IdMap::reverse_iterator itship = shiplist.rbegin(); itship != shiplist.rend(); ++itship) {
                    for(uint32_t i = 0; i < itship->second; i++) {
                        Combatant* f1 = new Combatant();
                        f1->setOwner(itmap->first);
                        f1->setObject(obj->getID());
                        f1->setShipType(itship->first);
                        uint32_t mydamage = damage / std::max(1U, (unsigned int)(shiplist.size() - i));
                        f1->setDamage(mydamage);
                        damage -= mydamage;
                        std::string type = ds->getDesign(itship->first)->getName();
                        f1->setBattleXmlType(type);
                        f1->setBattleXmlId(str(boost::format("%1%-%2%-%3%") % type % obj->getID() % i));
                        f1->setBattleXmlName(str(boost::format("%1%'s %2%, %3% %4%") % player->getName() % obj->getName() % type % i));
                        battlelogger->addCombatant(f1);
                        pcombatant.push_back(f1);
                    }
                }
            } else {
                int shipcount = 2;
                int homeplanetid = game->getResourceManager()->getResourceDescription("Home Planet")->getResourceType();
                if(((Planet*)(obj->getObjectBehaviour()))->getResource(homeplanetid) == 1) {
                    //three more for home planets
                    shipcount += 3;
                }
                for(int i = 0; i < shipcount; i++) {
                    Combatant* f1 = new Combatant();
                    f1->setOwner(itmap->first);
                    f1->setObject(obj->getID());
                    f1->setShipType(0);
                    f1->setBattleXmlType("planet");
                    f1->setBattleXmlId(str(boost::format("planet-%1%-%2%") % obj->getID() % i));
                    f1->setBattleXmlName(str(boost::format("%1%'s colony on %2%, Defense battery %3%") % player->getName() % obj->getName() % i));
                    battlelogger->addCombatant(f1);
                    pcombatant.push_back(f1);
                }
            }
        }
        listallplayerids.insert(itmap->first);
        battlelogger->endSide();
        //sort combatant list by ship type, descending
        sort(pcombatant.begin(), pcombatant.end(), CombatantSorter());
        fleetcache[itmap->first] = pcombatant;
    }

    for(std::set<uint32_t>::iterator itplayer = listallplayerids.begin(); itplayer != listallplayerids.end(); ++itplayer) {
        msgstrings[*itplayer] = "";
    }



    Random* random = Game::getGame()->getRandom();

    Logger::getLogger()->debug("Combat start");

    while(fleetcache.size() >= 2) {
        battlelogger->startRound();
        uint32_t pos1, pos2;
        if(fleetcache.size() == 2) {
            pos1 = 0;
            pos2 = 1;
        } else {
            pos1 = pos2 = random->getInRange(0U, ((uint32_t)(fleetcache.size() - 1)));
            while(pos2 == pos1) {
                pos2 = random->getInRange(0U, ((uint32_t)(fleetcache.size() - 1)));
            }
        }

        std::map<uint32_t, std::vector<Combatant*> >::iterator itpa = fleetcache.begin();
        advance(itpa, pos1);
        std::map<uint32_t, std::vector<Combatant*> >::iterator itpb = fleetcache.begin();
        advance(itpb, pos2);

        std::vector<Combatant*> f1 = itpa->second;
        std::vector<Combatant*> f2 = itpb->second;

        uint32_t ownerid1 = f1[0]->getOwner();
        uint32_t ownerid2 = f2[0]->getOwner();

        std::string p1name = playermanager->getPlayer(ownerid1)->getName();
        std::string p2name = playermanager->getPlayer(ownerid2)->getName();

        int32_t r1 = random->getInRange((int32_t)0, (int32_t)2);
        int32_t r2 = random->getInRange((int32_t)0, (int32_t)2);

        std::map<Combatant*, uint32_t> d1, d2;

        battlelogger->log(str(boost::format("%1%'s fleet chooses %2%.") % p1name % rsp[r2]));
        battlelogger->log(str(boost::format("%1%'s fleet chooses %2%.") % p2name % rsp[(r2 + r1) % 3]));

        if(r1 == 0) {
            //draw
            battlelogger->log("It's a draw");
            d1 = buildShotList(f1, true);
            d2 = buildShotList(f2, true);

            if(d1.size() != 0)
                doDamage(d1, f2);
            if(d2.size() != 0)
                doDamage(d2, f1);
        } else {

            if(r1 == 1) {
                //pa win
                battlelogger->log(str(boost::format("%1% wins.") % p1name));

                d1 = buildShotList(f1);
                if(d1.size() == 0) {
                    battlelogger->log(str(boost::format("%1%'s forces escape") % p1name));
                    msgstrings[ownerid1] += "Your Fleet escaped. ";
                    for(std::map<uint32_t, std::string>::iterator msgit = msgstrings.begin();
                            msgit != msgstrings.end(); ++msgit) {
                        if(msgit->first == ownerid1)
                            continue;
                        msgit->second += str(boost::format("%1%'s fleet of escaped. ") % p1name);
                    }
                    resolveCombatantsToObjects(f1);
                    for(std::vector<Combatant*>::iterator itcombatant = f1.begin(); itcombatant != f1.end();
                            ++itcombatant) {
                        delete *itcombatant;
                    }
                    fleetcache.erase(itpa);
                    battlelogger->endRound();
                    continue;
                }
                doDamage(d1, f2);
            } else {
                //pb win
                battlelogger->log(str(boost::format("%1% wins.") % p2name));
                d2 = buildShotList(f2);
                if(d2.size() == 0) {
                    battlelogger->log(str(boost::format("%1%'s forces escape") % p2name));
                    msgstrings[ownerid2] += "Your Fleet escaped. ";
                    for(std::map<uint32_t, std::string>::iterator msgit = msgstrings.begin();
                            msgit != msgstrings.end(); ++msgit) {
                        if(msgit->first == ownerid2)
                            continue;
                        msgit->second += str(boost::format("%1%'s fleet of escaped. ") % p2name);
                    }
                    resolveCombatantsToObjects(f2);
                    for(std::vector<Combatant*>::iterator itcombatant = f2.begin(); itcombatant != f2.end();
                            ++itcombatant) {
                        delete *itcombatant;
                    }
                    fleetcache.erase(itpb);
                    battlelogger->endRound();
                    continue;
                }
                doDamage(d2, f1);
            }

        }

        if(isAllDead(f1)) {
            msgstrings[ownerid1] += str(boost::format("Your fleet was destroyed by %1%'s fleet. ") % p2name);
            msgstrings[ownerid2] += str(boost::format("You destroyed %1%'s fleet. ") % p1name);
            std::string deathmsg = str(boost::format("%1%'s fleet destroyed %2%'s fleet. ") % p1name % p2name);
            for(std::map<uint32_t, std::string>::iterator msgit = msgstrings.begin();
                    msgit != msgstrings.end(); ++msgit) {
                if(msgit->first == ownerid1 || msgit->first == ownerid2)
                    continue;
                msgit->second += deathmsg;
            }
            resolveCombatantsToObjects(f1);
            for(std::vector<Combatant*>::iterator itcombatant = f1.begin(); itcombatant != f1.end();
                    ++itcombatant) {
                delete *itcombatant;
            }
            fleetcache.erase(itpa);
        }
        if(isAllDead(f2)) {
            msgstrings[ownerid2] += str(boost::format("Your fleet was destroyed by %1%'s fleet. ") % p1name);
            msgstrings[ownerid1] += str(boost::format("You destroyed %1%'s fleet. ") % p2name);
            std::string deathmsg = str(boost::format("%1%'s fleet destroyed %2%'s fleet. ") % p2name % p1name);
            for(std::map<uint32_t, std::string>::iterator msgit = msgstrings.begin();
                    msgit != msgstrings.end(); ++msgit) {
                if(msgit->first == ownerid1 || msgit->first == ownerid2)
                    continue;
                msgit->second += deathmsg;
            }
            resolveCombatantsToObjects(f2);
            for(std::vector<Combatant*>::iterator itcombatant = f2.begin(); itcombatant != f2.end();
                    ++itcombatant) {
                delete *itcombatant;
            }
            fleetcache.erase(itpb);
        }

        battlelogger->endRound();

    }

    std::string file = battlelogger->save();

    if(!fleetcache.empty()) {
        std::vector<Combatant*> flast = fleetcache.begin()->second;
        resolveCombatantsToObjects(flast);
        msgstrings[flast[0]->getOwner()] += "Your Fleet survived combat.";
        for(std::vector<Combatant*>::iterator itcombatant = flast.begin(); itcombatant != flast.end();
                ++itcombatant) {
            delete *itcombatant;
        }
        fleetcache.erase(fleetcache.begin());
        if(!fleetcache.empty()) {
            Logger::getLogger()->warning("fleetcache not empty at end of combat");
        }
    }
    for(std::map<uint32_t, std::string>::iterator msgit = msgstrings.begin();
            msgit != msgstrings.end(); ++msgit) {
        Message::Ptr msg( new Message() );
        msg->setSubject("Combat");
        for(std::set<uint32_t>::iterator itob = listallobids.begin(); itob != listallobids.end();
                ++itob) {
            msg->addReference(rst_Object, *itob);
        }
        for(std::set<uint32_t>::iterator itpl = listallplayerids.begin();
                itpl != listallplayerids.end(); ++itpl) {
            msg->addReference(rst_Player, *itpl);
        }

        msg->setBody(msgit->second);

        Game::getGame()->getPlayerManager()->getPlayer(msgit->first)->postToBoard(msg);
    }

    for(std::map<uint32_t, IGObject::Ptr>::iterator itob = objectcache.begin();
            itob != objectcache.end(); ++itob) {
        Game::getGame()->getObjectManager()->doneWithObject(itob->first);
    }
    objectcache.clear();

}
Exemple #20
0
bool BuildFleet::doOrder(IGObject::Ptr ob)
{
  Logger::getLogger()->debug("Entering BuildFleet::doOrder");

  Planet* planet = static_cast<Planet*>(ob->getObjectBehaviour());

  Game* game = Game::getGame();
  ResourceManager::Ptr resman = game->getResourceManager();
  const uint32_t resType = resman->getResourceDescription("Factories")->getResourceType();
  const uint32_t resValue = planet->getResourceSurfaceValue(resType);

  int ownerid = planet->getOwner();
  if(ownerid == 0){
      Logger::getLogger()->debug("Exiting BuildFleet::doOrder ownerid == 0");
      //currently not owned by anyone, just forget about it
      return true;
  }

  uint32_t runningTotal = resources[1];
  if (resValue == 0) {
    Message::Ptr msg(new Message());
    msg->setSubject("Build Fleet order error");
    msg->setBody(std::string("The construction of your  new fleet \"") + fleetname->getString() + "\" has been delayed, you do not have any production points this turn.");
    Game::getGame()->getPlayerManager()->getPlayer(ownerid)->postToBoard(msg);
    return false;
  } else if(runningTotal > resValue) {
    if (planet->removeResource(resType, resValue)) {
      removeResource(1, resValue);
      runningTotal = resources[1];
      uint32_t planetFactories = planet->getFactoriesPerTurn();
      turns = static_cast<uint32_t>(ceil(runningTotal / planetFactories));
      Message::Ptr msg(new Message());
      msg->setSubject("Build Fleet order slowed");
      msg->setBody(std::string("The construction of your new fleet \"") + fleetname->getString() + "\" has been delayed.");
      Game::getGame()->getPlayerManager()->getPlayer(ownerid)->postToBoard(msg);
      return false;
    }
  } else if(runningTotal <= resValue && planet->removeResource(resType, runningTotal)){
    //create fleet

    //this is probably unnecessary
    resources[1] = 0;
    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 = dynamic_cast<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();

    //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);
    Logger::getLogger()->debug("Exiting BuildFleet::doOrder on Success");

    return true;
  }
  Logger::getLogger()->debug("Exiting BuildFleet::doOrder on failure");

  return false;
}
Exemple #21
0
bool Colonize::doOrder(IGObject::Ptr obj) {
   bool result = true;
   --turns;

   Planet* origin = dynamic_cast<Planet*>(obj->getObjectBehaviour());
   assert(origin);
   Logger::getLogger()->debug("Starting a Colonize::doOrder on %s.",origin->getName().c_str());
   
   //Get the list of objects and the # of units to colonize
   IdMap list = targetPlanet->getList();
   
   //Collect all of the players bids and restrain them to 1 less than the current units
   map<IGObject::Ptr ,uint32_t> bids;
   for(IdMap::iterator i = list.begin(); i != list.end(); ++i) {
      uint32_t planetID = i->first;
      uint32_t numUnits = i->second;
      IGObject::Ptr target = Game::getGame()->getObjectManager()->getObject(planetID);     
      
      //Restrain the number of units moved off of origin
      uint32_t maxUnits = origin->getResource("Army").first;
      numUnits = numUnits + bids[target];             //Add current bid on target to requests units (no tricksy bidding!)
      if ( numUnits >= maxUnits && maxUnits > 0) {
         if ( maxUnits > 0)
            numUnits = maxUnits - 1;
         else
            numUnits = 0;
      }
      
      bids[target] = numUnits;
   }
   
   //for each seperate planet bid on run the bid routine
   for(map<IGObject::Ptr ,uint32_t>::iterator i = bids.begin(); i != bids.end(); ++i) {
      Logger::getLogger()->debug("\tStarting to iterate over all players bids");
      
      Planet* biddedPlanet = dynamic_cast<Planet*>(i->first->getObjectBehaviour());
      assert(biddedPlanet);
      
      //Ensure the object IS a planet and the object is unowned
      //The object MAY be owned if a bid has occured and a winner was chosen
      //then all other bids on that planet will simply be ignored
      if ( biddedPlanet != NULL && biddedPlanet->getOwner() == 0) {
         Logger::getLogger()->debug("\tGetting the top player and bid for planet %s",biddedPlanet->getName().c_str());
        
        //Get pair <owner's planet,bid> of top bidder
         pair<IGObject::Ptr ,uint32_t> topBidder = getTopPlayerAndBid(i->first);

         //Check if players bid is bigger than top bidder elsewhere - only did this because I wasn't sure
         //BUG: this code would force the reset of bid restriction
         // if ( i->second > topBidder.second ) {
         //    topBidder.second = i->second;
         //    topBidder.first = obj;
         // }
        
         Planet* ownerPlanet = dynamic_cast<Planet*>(topBidder.first->getObjectBehaviour());
         assert(ownerPlanet);
         
         uint32_t player = ownerPlanet->getOwner(); 
         
         biddedPlanet->setOwner(player);
         biddedPlanet->addResource("Army",topBidder.second);
         ownerPlanet->removeResource("Army",topBidder.second);
         
         //Inform colonize winner, and obj owner
      }
      else //Bidded planet is now owned
      {
         Logger::getLogger()->debug("\tNot getting top bidders, planet is already owned");
         //inform player bid failed, obj is now owned by _person_, won bid with _#units_
      }
   }
   
   return result;
}
Exemple #22
0
void FMapInfoParser::ParseDoomEdNums()
{
	TMap<int, bool> defined;
	int error = 0;

	MapinfoEdMapItem editem;

	editem.filename = sc.ScriptName;

	ParseOpenBrace();
	while (true)
	{
		if (sc.CheckString("}")) return;
		else if (sc.CheckNumber())
		{
			int ednum = sc.Number;
			sc.MustGetStringName("=");
			sc.MustGetString();

			bool *def = defined.CheckKey(ednum);
			if (def != NULL)
			{
				sc.ScriptMessage("Editor Number %d defined more than once", ednum);
				error++;
			}
			defined[ednum] = true;
			if (sc.String[0] == '$')
			{
				// add special stuff like playerstarts and sound sequence overrides here, too.
				editem.classname = NAME_None;
				editem.special = sc.MustMatchString(SpecialMapthingNames) + 1; // todo: assign proper constants
			}
			else
			{
				editem.classname = sc.String;
				editem.special = -1;
			}
			memset(editem.args, 0, sizeof(editem.args));
			editem.argsdefined = 0;
			editem.noskillflags = false;

			int minargs = 0;
			int maxargs = 5;
			FString specialname;
			if (sc.CheckString(","))
			{
				if (sc.CheckString("noskillflags"))
				{
					editem.noskillflags = true;
					if (!sc.CheckString(",")) goto noargs;
				}
				editem.argsdefined = 5; // mark args as used - if this is done we need to prevent assignment of map args in P_SpawnMapThing.
				if (editem.special < 0) editem.special = 0;
				if (!sc.CheckNumber())
				{
					sc.MustGetString();
					specialname = sc.String;	// save for later error reporting.
					editem.special = P_FindLineSpecial(sc.String, &minargs, &maxargs);
					if (editem.special == 0 || minargs == -1)
					{
						sc.ScriptMessage("Invalid special %s for Editor Number %d", sc.String, ednum);
						error++;
						minargs = 0;
						maxargs = 5;
					}
					if (!sc.CheckString(","))
					{
						// special case: Special without arguments
						if (minargs != 0)
						{
							sc.ScriptMessage("Incorrect number of args for special %s, min = %d, max = %d, found = 0", specialname.GetChars(), minargs, maxargs);
							error++;
						}
						DoomEdFromMapinfo.Insert(ednum, editem);
						continue;
					}
					sc.MustGetNumber();
				}
				int i = 0;
				while (i < 5)
				{
					editem.args[i] = sc.Number;
					i++;
					if (!sc.CheckString(",")) break;
					// special check for the ambient sounds which combine the arg being set here with the ones on the mapthing.
					if (sc.CheckString("+"))
					{
						editem.argsdefined = i;
						break;
					}
					sc.MustGetNumber();

				}
				if (specialname.IsNotEmpty() && (i < minargs || i > maxargs))
				{
					sc.ScriptMessage("Incorrect number of args for special %s, min = %d, max = %d, found = %d", specialname.GetChars(), minargs, maxargs, i);
					error++;
				}
			}
		noargs:
			DoomEdFromMapinfo.Insert(ednum, editem);
		}
		else
		{
			sc.ScriptError("Number expected");
		}
	}
	if (error > 0)
	{
		sc.ScriptError("%d errors encountered in DoomEdNum definition", error);
	}
}
Exemple #23
0
//This function gets the top bid for the given object
pair<IGObject::Ptr ,uint32_t> Colonize::getTopPlayerAndBid(IGObject::Ptr obj) {
   pair<IGObject::Ptr ,uint32_t> result;
   result.second = 0;
   
   Planet* origin = dynamic_cast<Planet*>(obj->getObjectBehaviour());
   assert(origin);

   Logger::getLogger()->debug("\tCollecting all bids on object %s",origin->getName().c_str());

   Game* game = Game::getGame();
   OrderManager* ordM = game->getOrderManager();
   ObjectManager* objM = game->getObjectManager();
   
   //Construct the map to be used, the identifier is the planet, the value is the bid
   map<IGObject::Ptr ,uint32_t> bids;
      
   //Get all objects from object manager
   set<uint32_t> objectsIds = objM->getAllIds();
   
   //Iterate over every object
   for(set<uint32_t>::iterator i = objectsIds.begin(); i != objectsIds.end(); ++i)
   {
      //Get current object
      IGObject::Ptr currObj = objM->getObject(*i);
      
      //Print out current planet
      Planet* bidder = dynamic_cast<Planet*>(currObj->getObjectBehaviour());
      if (bidder != NULL) {
         Logger::getLogger()->debug("\t\tLooking at orders on object %s",bidder->getName().c_str());
      }
      
      //Get order queue from object
      OrderQueueObjectParam* oqop = dynamic_cast<OrderQueueObjectParam*>(currObj->getParameterByType(obpT_Order_Queue));
      OrderQueue::Ptr oq;

      //Validate that the oq exists
      if(oqop != NULL && (oq = ordM->getOrderQueue(oqop->getQueueId())) != NULL)
      {
         //Iterate over all orders
         for (uint32_t j = 0; j < oq->getNumberOrders(); j++)
         {
            OwnedObject *orderedObj = dynamic_cast<OwnedObject*>(currObj->getObjectBehaviour());
            Order* order = NULL;
            if ( orderedObj != NULL ) {
               order = oq->getOrder(j, orderedObj->getOwner());
            }
            
            Logger::getLogger()->debug("\t\tThere exists a %s order on %s", order->getName().c_str(), bidder->getName().c_str());
            //if order is a colonize order
            if( order != NULL && order->getName() == "Colonize")
            {
               Colonize* colonize = dynamic_cast<Colonize*>(order);
               assert(colonize);

               //Get the list of planetIDs and the # of units to move
               IdMap list = colonize->getTargetList()->getList();
               
               //Iterate over all suborders
               for(IdMap::iterator i = list.begin(); i != list.end(); ++i) {
                  uint32_t planetID = i->first;
                  uint32_t numUnits = i->second;
                  
                  format debug("\t\t\tEncountered suborder to Colonize %1% with %2% units");
                  debug % planetID; debug % numUnits; 
                  Logger::getLogger()->debug(debug.str().c_str());
                  
                  IGObject::Ptr target = Game::getGame()->getObjectManager()->getObject(planetID);
                  if ( target == obj ) {
                     bids[currObj] += numUnits;                     
                  }
               }
            }
            else if ( order->getName() != "Colonize")
            {
               j = oq->getNumberOrders() + 1;   //force the loop to exit, we have "left" the frontal Colonize orders
            }
         }
         currObj->touchModTime();
      }
      objM->doneWithObject(currObj->getID());
   }
   

   //Iterate over all bids and restrict them to the maximum armies availible on that planet
   for(map<IGObject::Ptr ,uint32_t>::iterator i = bids.begin(); i != bids.end(); ++i) {
      Logger::getLogger()->debug("Iterating over all bids to pick the highest legal bid.");
      //FIXME: Somewhere in this "for" the server crashes when a single bid is created for 1 unit when planet only has 1 unit left

      //Restrict players bid to 1 less than their current reinforcements
      Planet* planet = dynamic_cast<Planet*>(i->first->getObjectBehaviour());
      assert(planet);

      result.first = i->first;      
      uint32_t numUnits = i->second;
      uint32_t maxUnits = planet->getResource("Army").first;
      
      //If there is overflow of numUnits, check for maxUnits over 0 insures we don't set unsigned to < 0
      if ( numUnits >= maxUnits && maxUnits > 0) {
         if ( maxUnits > 0)
            numUnits = maxUnits - 1;
         else
            numUnits = 0;
      }
      i->second = numUnits;
      result.second = i->second;
   }

   sendPlayerMessages(obj, bids,result);
   
   if (result.first == NULL)
   {
   }
   format debugMsg("Found highest bidder to be from planet #%1% with %2% units");
   debugMsg % result.first->getName(); debugMsg % result.second;
   Logger::getLogger()->debug(debugMsg.str().c_str());
   
   return result;
}