Пример #1
0
 skills_bag()
   : m_skills() {
   const std::vector<skill_definition>& skillDefs = skills_manager::get_skill_definitions();
   for( const skill_definition& s : skillDefs ) {
     m_skills.push_back( skill( s ) );
   }
 }
Пример #2
0
//=========================================================
// load the SkillData struct with the proper values based on the skill level.
//=========================================================
void CGameRules::RefreshSkillData ( bool forceUpdate )
{
#ifndef CLIENT_DLL
	if ( !forceUpdate )
	{
		if ( GlobalEntity_IsInTable( "skill.cfg" ) )
			return;
	}
	GlobalEntity_Add( "skill.cfg", STRING(gpGlobals->mapname), GLOBAL_ON );
	char	szExec[256];

	ConVarRef skill( "skill" );

	SetSkillLevel( skill.IsValid() ? skill.GetInt() : 1 );

#ifdef HL2_DLL
	// HL2 current only uses one skill config file that represents MEDIUM skill level and
	// synthesizes EASY and HARD. (sjb)
	Q_snprintf( szExec,sizeof(szExec), "exec skill_manifest.cfg\n" );

	engine->ServerCommand( szExec );
	engine->ServerExecute();
#else
	Q_snprintf( szExec,sizeof(szExec), "exec skill%d.cfg\n", GetSkillLevel() );

	engine->ServerCommand( szExec );
	engine->ServerExecute();
#endif // HL2_DLL
#endif // CLIENT_DLL
}
std::vector<Charm> CharmLoader::load(const std::string& filename) {
	
	rapidxml::xml_document<> doc;
//	std::ifstream file("C:/Users/Rip258 - Team Luna/Desktop/charm.txt");
	std::ifstream file(filename);

	std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
	buffer.push_back('\0');
	//	std::cout << &buffer[0] << std::endl; /*test the buffer */

	doc.parse<0>(&buffer[0]);


	// set ptr to charms[0] in xml
	rapidxml::xml_node<>* ptr = doc.first_node()->first_node();

	int num_charms = countCharms(doc);
	std::vector<Charm> charms;
	charms.reserve(num_charms);

	for (int i = 0; i < num_charms; i++) {

		std::string name = ptr->first_node()->first_attribute()->value();
		int level = std::atoi(ptr->first_node()->first_attribute()->next_attribute()->value());
		int maxlevel = std::atoi(ptr->first_node()->first_attribute()->next_attribute()->next_attribute()->value());
		Skill skill(level, maxlevel, Skill::string_to_skill(name));
		charms.emplace_back(skill);
		
		if (ptr->next_sibling() != nullptr)
			ptr = ptr->next_sibling();
	}

	
	return charms;
}
Пример #4
0
 void RedrawItem(const int & index, s32 dstx, s32 dsty, bool current)
 {
   Skill::Secondary skill(1 + index / 3, 1 + (index % 3));
   AGG::GetICN(ICN::MINISS, skill.GetIndexSprite2()).Blit(dstx + 5, dsty + 3);
   std::string str = skill.GetName();
   Text text(str, (current ? Font::YELLOW_BIG : Font::BIG));
   text.Blit(dstx + 50, dsty + 10);
 };
Пример #5
0
void CSystemTestDlg::OnBnClickedLocateLevel()
{
	if(pScreen)
	{
		CCgxSkillWindow skill(IDB_SKILL_LV, pScreen);
		_locateWindowInfo(&skill, TEXT("Skill Level"));
		
	}
}
Пример #6
0
void Skill::SecSkills::ReadFromMP2(const u8* ptr)
{
    clear();

    for(u8 ii = 0; ii < 8; ++ii)
    {
	Skill::Secondary skill(*(ptr + ii) + 1, *(ptr + ii + 8));
        if(skill.isValid()) push_back(skill);
    }
}
Пример #7
0
void skills(View* view, int lastInd = 0) {
  vector<View::ListElem> options;
  vector<Skill*> s = Skill::getAll();
  for (Skill* skill : s)
    options.push_back(skill->getName());
  auto index = view->chooseFromList("Skills", options, lastInd);
  if (!index)
    return;
  skill(view, s[*index]);
  skills(view, *index);
}
Пример #8
0
void NewGameState::_changeCharacter()
{
    auto dude = _characters.at(_selectedCharacter);
    std::stringstream ss;
    auto msg = ResourceManager::msgFileType("text/english/game/stat.msg");
    ss << msg->message(100)->text() << " " << (dude->stat(0) < 10 ? "0" : "") << dude->stat(0) << "\n"
       << msg->message(101)->text() << " " << (dude->stat(1) < 10 ? "0" : "") << dude->stat(1) << "\n"
       << msg->message(102)->text() << " " << (dude->stat(2) < 10 ? "0" : "") << dude->stat(2) << "\n"
       << msg->message(103)->text() << " " << (dude->stat(3) < 10 ? "0" : "") << dude->stat(3) << "\n"
       << msg->message(104)->text() << " " << (dude->stat(4) < 10 ? "0" : "") << dude->stat(4) << "\n"
       << msg->message(105)->text() << " " << (dude->stat(5) < 10 ? "0" : "") << dude->stat(5) << "\n"
       << msg->message(106)->text() << " " << (dude->stat(6) < 10 ? "0" : "") << dude->stat(6) << "\n";
    getTextArea("stats_1")->setText(ss.str());

    ss.str("");
    ss << _statToString(dude->stat(0)) << "\n"
       << _statToString(dude->stat(1)) << "\n"
       << _statToString(dude->stat(2)) << "\n"
       << _statToString(dude->stat(3)) << "\n"
       << _statToString(dude->stat(4)) << "\n"
       << _statToString(dude->stat(5)) << "\n"
       << _statToString(dude->stat(6)) << "\n";
    getTextArea("stats_2")->setText(ss.str());

    getTextArea("bio")->setText(dude->biography());
    getTextArea("name")->setText(dude->name());
    getImageList("images")->setCurrentImage(_selectedCharacter);

    auto msgMisc = ResourceManager::msgFileType("text/english/game/misc.msg");

    std::string stats3 = msgMisc->message(16)->text() +  "\n"    // Hit Points
                       + msg->message(109)->text()    + "\n"     // Armor Class
                       + msgMisc->message(15)->text() + "\n"     // Action Points
                       + msg->message(111)->text()    + "\n";    // Melee Damage

    std::string stats3_values = std::to_string(dude->hitPointsMax()) + "/" + std::to_string(dude->hitPointsMax()) + "\n"
                              + std::to_string(dude->armorClass())   + "\n"
                              + std::to_string(dude->actionPoints()) + "\n"
                              + std::to_string(dude->meleeDamage())  + "\n";

    for (unsigned int i=0; i != 17; ++i) if (dude->skill(i))
    {
        stats3 += "\n" + ResourceManager::msgFileType("text/english/game/skill.msg")->message(100 + i)->text();
        stats3_values += "\n" + std::to_string(dude->skillValue(i)) + "%";
    }
    for (unsigned int i=0; i != 16; ++i) if (dude->trait(i))
    {
        stats3 += "\n" + ResourceManager::msgFileType("text/english/game/trait.msg")->message(100 + i)->text();
    }
    getTextArea("stats_3")->setText(stats3);
    getTextArea("stats3_values")->setText(stats3_values);
}
Пример #9
0
s8 Skill::GetLuckModifiers(u8 level, std::string* strs = NULL)
{
    Secondary skill(Secondary::LUCK, level);

    if(skill.GetValues() && strs)
    {
        strs->append(skill.GetName());
        StringAppendModifiers(*strs, skill.GetValues());
        strs->append("\n");
    }

    return skill.GetValues();
}
Пример #10
0
skill npc::best_skill()
{
 std::vector<int> best_skills;
 int highest = 0;
 for (int i = sk_unarmed; i <= sk_rifle; i++) {
  if (sklevel[i] > highest && i != sk_gun) {
   highest = sklevel[i];
   best_skills.clear();
  }
  if (sklevel[i] == highest && i != sk_gun)
   best_skills.push_back(i);
 }
 int index = rng(0, best_skills.size() - 1);
 return skill(best_skills[index]);
}
void ActorAnimationSettingDialog::FillAllSkillListBox(void)
{
	// 初始化该动作的event列表
	mListBoxAllSkill->Clear();

	WX::EffectManager::SkillIterator it = 
		WX::EffectManager::getSingleton().getSkillIterator();

	while ( it.hasMoreElements() )
	{
		wxString skill(it.peekNextKey().c_str());

		mListBoxAllSkill->InsertItems( 1, &skill, 0 );

		it.moveNext();
	}
}
Пример #12
0
main()
{
	int i,j,order,wave;
	srand(time(NULL));
	printf("Ready? Go! 30 waves!\n\n");
	ph=50;pa=3;pd=0;wave=30;phealth=200;
	for (i=1;i<=wave;i++)
	{
		printf("\n***********The No.%d wave**********\n",i);
		if (i<=25) learn();
		h=rand()%(30*(1+i/4))+ph+10;
		a=rand()%(5*(1+i/8))+pa+1;
		d=rand()%(3*(1+i/8))+pd;
		m=i;
		ph=h;pa=a;pd=d;win=2;
		preskill();
		do
		{
			for (j=0;j<=4;j++)
			      if (k[j]) k[j]--;
		printf("Your situation:health:%d  attack:%d  defend:%d\n",health,attack,defend);
		printf("The enemy's situation:health:%d  attack:%d  defend:%d\n",h,a,d);
		printf("Your turn   1:attack;2:skills   ");
		scanf("%d",&order);
		switch (order)
		{
			case 1:attacke();break;
			case 2:skill();break;
			default:printf("Order error!Lose one turn!");break;
		}
		if (h>0) reattack();
		printf("\n");
	}   while (health>0&&h>0);
		if (win==1) {printf("You win the wave!\n");money+=m;honor++;} else if (win==0) {printf("You lose the wave!\n");health=phealth;}
		attack++;
		shop();
		health+=i*10+pa;
		(phealth+=i*12);
		attack+=rand()%3;
		defend+=rand()%2;
	}
	printf("You succeeded in %d waves out of %d!",honor,wave);
}
Пример #13
0
bool PlayerCreateState::_skillToggle(unsigned int num)
{
    auto player = Game::getInstance()->player();
    if (player->skill(num))
    {
        player->setSkill(num, 0);
        player->setSkillsPoints(player->skillsPoints() + 1);
        return true;
    }
    else
    {
        if (player->skillsPoints() > 0)
        {
            player->setSkill(num, 1);
            player->setSkillsPoints(player->skillsPoints() - 1);
            return true;
        }
    }
    return false;
}
    virtual double CalcFunction(const char *function, const double *params)
    {
        if (strcmp(function, "Multiply") == 0)
            return params[0]*params[1];

        if (strcmp(function, "GetSkillRank") == 0)
        {
            csString skill(MathScriptEngine::GetString(params[0]));
            if (skill == "Lah'ar")
                return 77;
            if (skill == "Sword")
                return 33;
            return 0;
        }

        if (strcmp(function, "GetSeven") == 0)
        {
            return 7;
        }

        return 0.0;
    }
Пример #15
0
        bool Skill::applySkill(Context *ctx)
        {
            SkillResult sr;
            auto actor = ctx->actorInfo().actor();

            //Получаем текущий уровень умения
            SkillInfo *skillInfo = actor->skill(id());
            std::vector<ActionResult> results = applyToContext(ctx, skillInfo->skillLvl());
            
            //Записываем историю
            sr.SkillId = id();
            sr.Results = results;
            actor->addWishHistory(sr);

            //поднимаем уровень скила
            int roll = d100();
            if (roll <= skillInfo->skillExp())
            {
                skillInfo->skillExpInc();
            }

            return true;
        }
Пример #16
0
void BOT_SoldierAssignSkills(edict_t *ent)
{
	int mval = 10;
	
	skill(STRENGTH, 5);
	skill(HASTE, 2);
	skill(RESISTANCE, 5);
	skill(VITALITY, 5);
	skill(GRAPPLE_HOOK, 1);

	skill(HASTE, 2);
	
	skill(STRENGTH, 5);
	skill(VITALITY, 5);
	skill(RESISTANCE, 5);
	skill(HASTE, 1);
	skill(GRAPPLE_HOOK, 2);

	skill(STRENGTH, 5);
	skill(VITALITY, 5);
	skill(RESISTANCE, 5);
}
Пример #17
0
void PlayerCreateState::think()
{
    State::think();
    auto player = Game::getInstance()->player();
    auto msgEditor = ResourceManager::msgFileType("text/english/game/editor.msg");

    _labels.at("name")->setText(player->name());
    _labels.at("age")->setText(msgEditor->message(104))->appendText(" ")->appendText(std::to_string(player->age()));
    _labels.at("gender")->setText(msgEditor->message(player->gender() == 0 ? 107 : 108)); // 0 - male   1 - female

    _counters.at("statsPoints")->setNumber(player->statsPoints());
    _counters.at("skillsPoints")->setNumber(player->skillsPoints());

    _labels.at("health_1")->setText(msgEditor->message(300))->appendText("  ")->appendText(std::to_string(player->hitPointsMax()))->appendText("/")->appendText(std::to_string(player->hitPointsMax()));
    _labels.at("params_1_value")->setText(player->armorClass());
    _labels.at("params_2_value")->setText(player->actionPoints());
    _labels.at("params_3_value")->setText(player->carryWeightMax());
    _labels.at("params_4_value")->setText(player->meleeDamage());
    _labels.at("params_5_value")->setText(player->damageResistance())->appendText("%");
    _labels.at("params_6_value")->setText(player->poisonResistance())->appendText("%");
    _labels.at("params_7_value")->setText(player->radiationResistance())->appendText("%");
    _labels.at("params_8_value")->setText(player->sequence());
    _labels.at("params_9_value")->setText(player->healingRate());
    _labels.at("params_10_value")->setText(player->criticalChance())->appendText("%");

    // Stats counters and labels
    for (unsigned int i = 0; i < 7; i++)
    {
        std::stringstream ss;
        ss << "stats_" << (i+1);
        unsigned int val = player->statTotal(i);
        _counters.at(ss.str())->setNumber(val);
        _counters.at(ss.str())->setColor(BigCounter::COLOR_WHITE);
        if (val > 10)
        {
            val = 10;
            _counters.at(ss.str())->setColor(BigCounter::COLOR_RED);
        }
        _labels.at(ss.str())->setText(msgEditor->message(199 + (val < 1 ? 1 : val)));
    }

    // Skills values
    for (unsigned int i = 0; i != 18; ++i)
    {
        std::stringstream ss;
        ss << "skills_" << (i + 1) << "_value";
        _labels.at(ss.str())->setText(player->skillValue(i))->appendText("%");
    }

    // Default labels colors
    for(auto it = _labels.begin(); it != _labels.end(); ++it)
    {
        std::string name = it->first;

        auto font1_3ff800ff = ResourceManager::font("font1.aaf", 0x3ff800ff);
        auto font1_a0a0a0ff = ResourceManager::font("font1.aaf", 0xa0a0a0ff);
        auto font1_183018ff = ResourceManager::font("font1.aaf", 0x183018ff);

        if (name.find("stats_") == 0 || name.find("params_") == 0)
        {
            it->second->setFont(font1_3ff800ff);
        }

        if (name.find("traits_") == 0)
        {
            unsigned int number = atoi(name.substr(7).c_str());
            it->second->setFont(player->trait(number - 1) ? font1_a0a0a0ff : font1_3ff800ff);
        }

        if (name.find("skills_") == 0)
        {
            unsigned int number = atoi(name.substr(7).c_str());
            it->second->setFont(player->skill(number - 1) ? font1_a0a0a0ff : font1_3ff800ff);
        }

        if (name.find("health_") == 0)
        {
            it->second->setFont(name.compare("health_1") == 0 ? font1_3ff800ff : font1_183018ff);
        }
    }

    // Selected labels colors
    for(auto it = _labels.begin(); it != _labels.end(); ++it)
    {
        if (_selectedLabel != it->second) continue;

        std::string name = it->first;

        _title->setText(_titles.at(name));
        _description->setText(_descriptions.at(name));
        _selectedImage->setTexture(_images.at(name)->texture());

        auto font1_ffff7fff = ResourceManager::font("font1.aaf", 0xffff7fff);
        auto font1_ffffffff = ResourceManager::font("font1.aaf", 0xffffffff);
        auto font1_707820ff = ResourceManager::font("font1.aaf", 0x707820ff);

        if (name.find("stats_") == 0)
        {
            it->second->setFont(font1_ffff7fff);
        }

        if (name.find("params_") == 0)
        {
            it->second->setFont(font1_ffff7fff);
            _labels.at(name+"_value")->setFont(font1_ffff7fff);
        }

        if (name.find("traits_") == 0)
        {
            unsigned int number = atoi(name.substr(7).c_str());
            it->second->setFont(player->trait(number - 1) ? font1_ffffffff : font1_ffff7fff);
        }

        if (name.find("skills_") == 0)
        {
            unsigned int number = atoi(name.substr(7).c_str());
            it->second->setFont(player->skill(number - 1) ? font1_ffffffff : font1_ffff7fff);
            _labels.at(name+"_value")->setFont(player->skill(number - 1) ? font1_ffffffff : font1_ffff7fff);
        }

        if (name.find("health_") == 0)
        {
            it->second->setFont(name.compare("health_1") == 0 ? font1_ffff7fff : font1_707820ff);
        }
    }

}
Пример #18
0
void thread_search(Pos *pos)
{
  Value bestValue, alpha, beta, delta;
  Move pv[MAX_PLY + 1];
  Move lastBestMove = 0;
  Depth lastBestMoveDepth = DEPTH_ZERO;
  double timeReduction = 1.0;

  Stack *ss = pos->st; // At least the seventh element of the allocated array.
  for (int i = -7; i < 3; i++)
    memset(SStackBegin(ss[i]), 0, SStackSize);
  (ss-1)->endMoves = pos->moveList;

  for (int i = -7; i < 0; i++)
    ss[i].history = &(*pos->counterMoveHistory)[0][0]; // Use as sentinel

  for (int i = 0; i <= MAX_PLY; i++)
    ss[i].ply = i;
  ss->pv = pv;

  bestValue = delta = alpha = -VALUE_INFINITE;
  beta = VALUE_INFINITE;
  pos->completedDepth = DEPTH_ZERO;

  if (pos->threadIdx == 0)
    mainThread.bestMoveChanges = 0;

  int multiPV = option_value(OPT_MULTI_PV);
#if 0
  Skill skill(option_value(OPT_SKILL_LEVEL));

  // When playing with strength handicap enable MultiPV search that we will
  // use behind the scenes to retrieve a set of possible moves.
  if (skill.enabled())
      multiPV = std::max(multiPV, (size_t)4);
#endif

  RootMoves *rm = pos->rootMoves;
  multiPV = min(multiPV, rm->size);

  // Iterative deepening loop until requested to stop or the target depth
  // is reached.
  while (   (pos->rootDepth += ONE_PLY) < DEPTH_MAX
         && !Signals.stop
         && !(   Limits.depth
              && pos->threadIdx == 0
              && pos->rootDepth / ONE_PLY > Limits.depth))
  {
    // Age out PV variability metric
    if (pos->threadIdx == 0)
      mainThread.bestMoveChanges *= 0.517;

    // Save the last iteration's scores before first PV line is searched and
    // all the move scores except the (new) PV are set to -VALUE_INFINITE.
    for (int idx = 0; idx < rm->size; idx++)
      rm->move[idx].previousScore = rm->move[idx].score;

    pos->contempt = pos_stm() == WHITE ?  make_score(base_ct, base_ct / 2)
                                       : -make_score(base_ct, base_ct / 2);

    int pvFirst = 0, pvLast = 0;

    // MultiPV loop. We perform a full root search for each PV line
    for (int pvIdx = 0; pvIdx < multiPV && !Signals.stop; pvIdx++) {
      pos->pvIdx = pvIdx;
      if (pvIdx == pvLast) {
        pvFirst = pvLast;
        for (pvLast++; pvLast < rm->size; pvLast++)
          if (rm->move[pvLast].tbRank != rm->move[pvFirst].tbRank)
            break;
        pos->pvLast = pvLast;
      }

      pos->selDepth = 0;

      // Skip the search if we have a mate value from DTM tables.
      if (abs(rm->move[pvIdx].tbRank) > 1000) {
        bestValue = rm->move[pvIdx].score = rm->move[pvIdx].tbScore;
        alpha = -VALUE_INFINITE;
        beta = VALUE_INFINITE;
        goto skip_search;
      }

      // Reset aspiration window starting size
      if (pos->rootDepth >= 5 * ONE_PLY) {
        Value previousScore = rm->move[pvIdx].previousScore;
        delta = 20;
        alpha = max(previousScore - delta, -VALUE_INFINITE);
        beta  = min(previousScore + delta,  VALUE_INFINITE);

        // Adjust contempt based on root move's previousScore
        int ct = base_ct + 88 * previousScore / (abs(previousScore) + 200);
        pos->contempt = pos_stm() == WHITE ?  make_score(ct, ct / 2)
                                           : -make_score(ct, ct / 2);
      }

      // Start with a small aspiration window and, in the case of a fail
      // high/low, re-search with a bigger window until we're not failing
      // high/low anymore.
      int failedHighCnt = 0;
      while (true) {
        Depth adjustedDepth = max(ONE_PLY, pos->rootDepth - failedHighCnt * ONE_PLY);
        bestValue = search_PV(pos, ss, alpha, beta, adjustedDepth);

        // Bring the best move to the front. It is critical that sorting
        // is done with a stable algorithm because all the values but the
        // first and eventually the new best one are set to -VALUE_INFINITE
        // and we want to keep the same order for all the moves except the
        // new PV that goes to the front. Note that in case of MultiPV
        // search the already searched PV lines are preserved.
        stable_sort(&rm->move[pvIdx], pvLast - pvIdx);

        // If search has been stopped, we break immediately. Sorting and
        // writing PV back to TT is safe because RootMoves is still
        // valid, although it refers to the previous iteration.
        if (Signals.stop)
          break;

        // When failing high/low give some update (without cluttering
        // the UI) before a re-search.
        if (   pos->threadIdx == 0
            && multiPV == 1
            && (bestValue <= alpha || bestValue >= beta)
            && time_elapsed() > 3000)
          uci_print_pv(pos, pos->rootDepth, alpha, beta);

        // In case of failing low/high increase aspiration window and
        // re-search, otherwise exit the loop.
        if (bestValue <= alpha) {
          beta = (alpha + beta) / 2;
          alpha = max(bestValue - delta, -VALUE_INFINITE);

          if (pos->threadIdx == 0) {
            failedHighCnt = 0;
            Signals.stopOnPonderhit = 0;
          }
        } else if (bestValue >= beta) {
          beta = min(bestValue + delta, VALUE_INFINITE);
          if (pos->threadIdx == 0)
            failedHighCnt++;
        } else
          break;

        delta += delta / 4 + 5;

        assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
      }

      // Sort the PV lines searched so far and update the GUI
      stable_sort(&rm->move[pvFirst], pvIdx - pvFirst + 1);

skip_search:
      if (    pos->threadIdx == 0
          && (Signals.stop || pvIdx + 1 == multiPV || time_elapsed() > 3000))
        uci_print_pv(pos, pos->rootDepth, alpha, beta);
    }

    if (!Signals.stop)
      pos->completedDepth = pos->rootDepth;

    if (rm->move[0].pv[0] != lastBestMove) {
      lastBestMove = rm->move[0].pv[0];
      lastBestMoveDepth = pos->rootDepth;
    }

    // Have we found a "mate in x"?
    if (   Limits.mate
        && bestValue >= VALUE_MATE_IN_MAX_PLY
        && VALUE_MATE - bestValue <= 2 * Limits.mate)
      Signals.stop = 1;

    if (pos->threadIdx != 0)
      continue;

#if 0
    // If skill level is enabled and time is up, pick a sub-optimal best move
    if (skill.enabled() && skill.time_to_pick(thread->rootDepth))
      skill.pick_best(multiPV);
#endif

    // Do we have time for the next iteration? Can we stop searching now?
    if (    use_time_management()
        && !Signals.stop
        && !Signals.stopOnPonderhit) {
      // Stop the search if only one legal move is available, or if all
      // of the available time has been used.
      double fallingEval = (306 + 9 * (mainThread.previousScore - bestValue)) / 581.0;
      fallingEval = max(0.5, min(1.5, fallingEval));

      // If the best move is stable over several iterations, reduce time
      // accordingly
      timeReduction =  lastBestMoveDepth + 10 * ONE_PLY < pos->completedDepth
                     ? 1.95 : 1.0;
      double reduction = pow(mainThread.previousTimeReduction, 0.528) / timeReduction;

      // Use part of the gained time from a previous stable move for this move
      double bestMoveInstability = 1.0 + mainThread.bestMoveChanges;

      if (   rm->size == 1
          || time_elapsed() > time_optimum() * fallingEval * reduction * bestMoveInstability)
      {
        // If we are allowed to ponder do not stop the search now but
        // keep pondering until the GUI sends "ponderhit" or "stop".
        if (Limits.ponder)
          Signals.stopOnPonderhit = 1;
        else
          Signals.stop = 1;
      }
    }
  }

  if (pos->threadIdx != 0)
    return;

  mainThread.previousTimeReduction = timeReduction;

#if 0
  // If skill level is enabled, swap best PV line with the sub-optimal one
  if (skill.enabled())
    std::swap(rm[0], *std::find(rm.begin(),
              rm.end(), skill.best_move(multiPV)));
#endif
}
Пример #19
0
	void playfield::useattack(int skillid)
	{
		if (playerchar.attack(skillid))
		{
			if (skillid == 0)
			{
				bool left = playerchar.getleft();

				pair<vector2d, vector2d> attackrange;
				if (left)
				{
					attackrange.first = playerchar.getposition() - vector2d(100, 0);
					attackrange.second = vector2d(50, 50);
				}
				else
				{
					attackrange.first = playerchar.getposition() + vector2d(25, 0);
					attackrange.second = vector2d(50, 50);
				}

				attackinfo attack;
				attack.mastery = playerchar.getstats()->getmastery();
				attack.skill = 0;
				attack.maxattacked = 1;
				attack.display = 50;
				attack.charge = 0;
				attack.speed = 2; //todo: wep speed of char
				attack.direction = (left) ? 1 : 0;
				attack.numdamage = 1;
				attack.stance = 1; //maybe body animation?

				map_objects.getmobs()->sendattack(&attack, playerchar.getstats()->getdamage(), attackrange);
				packet_c.close_attack(attack);
			}
			else
			{
				if (!skillcache.count(skillid))
				{
					skillcache[skillid] = skill(skillid);
				}

				char skill_l = playerchar.getskills()->getlevel(skillid);
				bool left = playerchar.getleft();

				if (skill_l > 0)
				{
					skillinfo skill_i = skillcache[skillid].getlevel(skill_l);

					skillcache[skillid].addeffects(playerchar.geteffects(), !left);
					playerchar.setactions(skillcache[skillid].getactions());

					if (skillcache[skillid].isattack())
					{
						attackinfo attack;
						attack.mastery = playerchar.getstats()->getmastery();
						attack.skill = skillid;
						attack.maxattacked = skill_i.mobs;
						attack.numdamage = skill_i.attacks;
						attack.direction = (left) ? 1 : 0;
						attack.stance = 1;
						attack.speed = 2;
						attack.charge = 0;
						attack.display = 50;

						pair<vector2d, vector2d> attackrange = skill_i.range;
						if (left)
						{
							attackrange.first = playerchar.getposition() + attackrange.first;
							attackrange.second = playerchar.getposition() + attackrange.second;
						}
						else
						{
							attackrange.first = playerchar.getposition() - attackrange.first;
							attackrange.second = playerchar.getposition() - attackrange.second;
						}

						int damage = static_cast<int>(static_cast<float>(playerchar.getstats()->getdamage() * skill_i.damage) / 100);

						map_objects.getmobs()->sendattack(&attack, damage, attackrange);
						packet_c.close_attack(attack);
					}
				}
			}
		}
	}
Пример #20
0
int GameCritterObject::skillValue(unsigned int num)
{
    if (num >= _skills.size()) throw Exception("GameCritterObject::skillValue(num) - num out of range:" + std::to_string(num));
    int value = 0;
    switch(num)
    {
        case SKILLS_SMALL_GUNS:
            value += 5 + 4 * statTotal(STATS_AGILITY);
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_BIG_GUNS:
            value += 2*statTotal(STATS_AGILITY);
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_ENERGY_WEAPONS:
            value += 2*statTotal(STATS_AGILITY);
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_UNARMED:
            value += 30 + 2*(statTotal(STATS_AGILITY) + statTotal(STATS_STRENGTH));
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_MELEE_WEAPONS:
            value += 20 + 2*(statTotal(STATS_AGILITY) + statTotal(STATS_STRENGTH));
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_THROWING:
            value += 4*statTotal(STATS_AGILITY);
            if (trait(TRAITS_GOOD_NATURED)) value -= 10;
            break;
        case SKILLS_FIRST_AID:
            value += 2*(statTotal(STATS_PERCEPTION) + statTotal(STATS_INTELLIGENCE));
            if (trait(TRAITS_GOOD_NATURED)) value += 15;
            break;
        case SKILLS_DOCTOR:
            value += 5 + (statTotal(STATS_PERCEPTION) + statTotal(STATS_INTELLIGENCE));
            if (trait(TRAITS_GOOD_NATURED)) value += 15;
            break;
        case SKILLS_SNEAK:
            value += 5 + 3*statTotal(STATS_AGILITY);
            break;
        case SKILLS_LOCKPICK:
            value += 10 + (statTotal(STATS_PERCEPTION) + statTotal(STATS_AGILITY));
            break;
        case SKILLS_STEAL:
            value += 3*statTotal(STATS_AGILITY);
            break;
        case SKILLS_TRAPS:
            value += 10 + (statTotal(STATS_PERCEPTION) + statTotal(STATS_AGILITY));
            break;
        case SKILLS_SCIENCE:
            value += 4*statTotal(STATS_INTELLIGENCE);
            break;
        case SKILLS_REPAIR:
            value += 3*statTotal(STATS_INTELLIGENCE);
            break;
        case SKILLS_SPEECH:
            value += 5*statTotal(STATS_CHARISMA);
            if (trait(TRAITS_GOOD_NATURED)) value += 15;
            break;
        case SKILLS_BARTER:
            value += 4*statTotal(STATS_CHARISMA);
            if (trait(TRAITS_GOOD_NATURED)) value += 15;
            break;
        case SKILLS_GAMBLING:
            value += 5*statTotal(STATS_LUCK);
            break;
        case SKILLS_OUTDOORSMAN:
            value += 2 * (statTotal(STATS_ENDURANCE) + statTotal(STATS_INTELLIGENCE));
            break;
    }

    if (trait(TRAITS_GIFTED))
    {
        value -= 10;
    }

    if (skill(num))
    {
        value += 20;
    }

    return value;
}
	static inline void Execute885_500(Rucksack& rucksack, Position& pos)
	{
		Flashlight flashlight[g_maxPlyPlus2];
		Ply depth;

		// ベストムーブは何手目かだろうかなんだぜ☆?(^q^)?
		Ply prevBestMovePlyChanges;

		ScoreIndex bestScore = -ScoreInfinite;
		ScoreIndex delta = -ScoreInfinite;
		ScoreIndex alpha = -ScoreInfinite;
		ScoreIndex beta = ScoreInfinite;
		bool bestMoveNeverChanged = true;
		int lastInfoTime = -1; // 将棋所のコンソールが詰まる問題への対処用

		memset(flashlight, 0, 4 * sizeof(Flashlight));
		rucksack.ZeroclearBestMovePlyChanges();
#if defined LEARN
		// 高速化の為に浅い探索は反復深化しないようにする。学習時は浅い探索をひたすら繰り返す為。
		depth = std::max<Ply>(0, rucksack.m_limits.GetDepth() - 1);
#else
		depth = 0;
#endif

		flashlight[0].m_currentMove = g_MOVE_NULL; // skip update gains
		rucksack.m_tt.NewSearch();
		rucksack.m_history.Clear();
		rucksack.m_gains.Clear();

		// マルチPVの数☆?
		rucksack.m_pvSize = rucksack.m_engineOptions["MultiPV"];
		Skill skill(rucksack.m_engineOptions["Skill_Level"], rucksack.m_engineOptions["Max_Random_Score_Diff"]);

		if (rucksack.m_engineOptions["Max_Random_Score_Diff_Ply"] < pos.GetGamePly()) {
			skill.m_maxRandomScoreDiff = ScoreZero;
			rucksack.m_pvSize = 1;
			assert(!skill.enabled()); // level による設定が出来るようになるまでは、これで良い。
		}

		if (skill.enabled() && rucksack.m_pvSize < 3) {
			rucksack.m_pvSize = 3;
		}
		rucksack.m_pvSize = std::min(rucksack.m_pvSize, rucksack.m_rootMoves.size());

		// 指し手が無ければ負け
		if (rucksack.m_rootMoves.empty()) {
			rucksack.m_rootMoves.push_back(RootMove(g_MOVE_NONE));
			SYNCCOUT << "info depth 0 score "
				<< rucksack.scoreToUSI(-ScoreMate0Ply)
				<< SYNCENDL;

			return;
		}

#if defined BISHOP_IN_DANGER
		if ((bishopInDangerFlag == BlackBishopInDangerIn28
			&& std::find_if(std::begin(m_rootMoves), std::IsEnd(m_rootMoves),
				[](const RootMove& rm) { return rm.m_pv_[0].ToCSA() == "0082KA"; }) != std::IsEnd(m_rootMoves))
			|| (bishopInDangerFlag == WhiteBishopInDangerIn28
				&& std::find_if(std::begin(m_rootMoves), std::IsEnd(m_rootMoves),
					[](const RootMove& rm) { return rm.m_pv_[0].ToCSA() == "0028KA"; }) != std::IsEnd(m_rootMoves))
			|| (bishopInDangerFlag == BlackBishopInDangerIn78
				&& std::find_if(std::begin(m_rootMoves), std::IsEnd(m_rootMoves),
					[](const RootMove& rm) { return rm.m_pv_[0].ToCSA() == "0032KA"; }) != std::IsEnd(m_rootMoves))
			|| (bishopInDangerFlag == WhiteBishopInDangerIn78
				&& std::find_if(std::begin(m_rootMoves), std::IsEnd(m_rootMoves),
					[](const RootMove& rm) { return rm.m_pv_[0].ToCSA() == "0078KA"; }) != std::IsEnd(m_rootMoves)))
		{
			if (m_rootMoves.m_size() != 1)
				m_pvSize = std::max<size_t>(m_pvSize, 2);
		}
#endif

		// 反復深化で探索を行う。
		while (++depth <= g_maxPly && !rucksack.m_signals.m_stop && (!rucksack.m_limits.m_depth || depth <= rucksack.m_limits.m_depth)) {

			// 前回の iteration の結果を全てコピー
			for (size_t i = 0; i < rucksack.m_rootMoves.size(); ++i) {
				rucksack.m_rootMoves[i].m_prevScore_ = rucksack.m_rootMoves[i].m_score_;
			}

			prevBestMovePlyChanges = rucksack.GetBestMovePlyChanges();
			rucksack.ZeroclearBestMovePlyChanges(); // 退避したので、ゼロクリアーするぜ☆(^q^)

			// Multi PV loop
			for (rucksack.m_pvIdx = 0; rucksack.m_pvIdx < rucksack.m_pvSize && !rucksack.m_signals.m_stop; ++rucksack.m_pvIdx) {
#if defined LEARN
				alpha = rucksack.m_alpha;
				beta = rucksack.m_beta;
#else
				// aspiration search
				// alpha, beta をある程度絞ることで、探索効率を上げる。
				if (
					// 深さ5以上で
					5 <= depth &&
					abs(rucksack.m_rootMoves[rucksack.m_pvIdx].m_prevScore_) < PieceScore::m_ScoreKnownWin
					) {
					delta = static_cast<ScoreIndex>(16);
					alpha = rucksack.m_rootMoves[rucksack.m_pvIdx].m_prevScore_ - delta;
					beta = rucksack.m_rootMoves[rucksack.m_pvIdx].m_prevScore_ + delta;
				}
				else {
					alpha = -ScoreInfinite;
					beta = ScoreInfinite;
				}
#endif

				// aspiration search の window 幅を、初めは小さい値にして探索し、
				// fail high/low になったなら、今度は window 幅を広げて、再探索を行う。
				while (true) {
					// 探索を行う。
					flashlight->m_staticEvalRaw.m_p[0][0] = (flashlight + 1)->m_staticEvalRaw.m_p[0][0] = ScoreNotEvaluated;

					//────────────────────────────────────────────────────────────────────────────────
					// 探索☆?(^q^) 1回目のぐるんぐるんだぜ~☆ ルート~☆
					//────────────────────────────────────────────────────────────────────────────────
					bestScore = g_NODETYPE_PROGRAMS[NodeType::N00_Root]->GoToTheAdventure_new(rucksack, pos, flashlight + 1, alpha, beta, static_cast<Depth>(depth * OnePly), false);

					// 先頭が最善手になるようにソート
					UtilMove01::InsertionSort(rucksack.m_rootMoves.begin() + rucksack.m_pvIdx, rucksack.m_rootMoves.end());

					for (size_t i = 0; i <= rucksack.m_pvIdx; ++i) {
						flashlight->m_staticEvalRaw.m_p[0][0] = (flashlight + 1)->m_staticEvalRaw.m_p[0][0] = ScoreNotEvaluated;
						rucksack.m_rootMoves[i].InsertPvInTT(pos);
					}

#if 0
					// 詰みを発見したら即指す。
					if (ScoreMateInMaxPly <= abs(rucksack.m_bestScore) && abs(rucksack.m_bestScore) < ScoreInfinite) {
						SYNCCOUT << PvInfoToUSI(GetPos, rucksack.m_ply, rucksack.m_alpha, rucksack.m_beta) << SYNCENDL;
						rucksack.m_signals.m_stop = true;
					}
#endif

#if defined LEARN
					break;
#endif

					if (rucksack.m_signals.m_stop) {
						break;
					}

					if (alpha < bestScore && bestScore < beta) {
						break;
					}


					if (
						// 思考時間が3秒経過するまで、読み筋を出力しないぜ☆!(^q^)
						3000 < rucksack.m_stopwatch.GetElapsed()
						// 将棋所のコンソールが詰まるのを防ぐ。
						&& (depth < 10 || lastInfoTime + 200 < rucksack.m_stopwatch.GetElapsed()))
					{
						lastInfoTime = rucksack.m_stopwatch.GetElapsed();
						SYNCCOUT << rucksack.PvInfoToUSI(pos, depth, alpha, beta) << SYNCENDL;
					}

					// fail high/low のとき、aspiration window を広げる。
					if (PieceScore::m_ScoreKnownWin <= abs(bestScore)) {
						// 勝ち(負け)だと判定したら、最大の幅で探索を試してみる。
						alpha = -ScoreInfinite;
						beta = ScoreInfinite;
					}
					else if (beta <= bestScore) {
						beta += delta;
						delta += delta / 2;
					}
					else {
						rucksack.m_signals.m_failedLowAtRoot = true;
						rucksack.m_signals.m_stopOnPonderHit = false;

						alpha -= delta;
						delta += delta / 2;
					}

					assert(-ScoreInfinite <= alpha && beta <= ScoreInfinite);
				}

				UtilMove01::InsertionSort(rucksack.m_rootMoves.begin(), rucksack.m_rootMoves.begin() + rucksack.m_pvIdx + 1);

				if (
					(
						rucksack.m_pvIdx + 1 == rucksack.m_pvSize ||
						// 思考時間が3秒経過するまで、読み筋を出力しないぜ☆!(^q^)
						3000 < rucksack.m_stopwatch.GetElapsed()
					)
					// 将棋所のコンソールが詰まるのを防ぐ。
					&& (depth < 10 || lastInfoTime + 200 < rucksack.m_stopwatch.GetElapsed()))
				{
					lastInfoTime = rucksack.m_stopwatch.GetElapsed();
					SYNCCOUT << rucksack.PvInfoToUSI(pos, depth, alpha, beta) << SYNCENDL;
				}
			}

			//if (skill.enabled() && skill.timeToPick(depth)) {
			//	skill.pickMove();
			//}

			if (
				rucksack.m_limits.IsBrandnewTimeManagement() // 反復深化探索に潜るために真であることが必要☆
				&&
				!rucksack.m_signals.m_stopOnPonderHit
			) {
				bool stop = false;

				// 深さが 5 ~ 49 で、PVサイズが 1 のとき。
				if (4 < depth && depth < 50 && rucksack.m_pvSize == 1) {
					rucksack.m_timeManager.SetPvInstability_AtIterativeDeepeningStarted(rucksack.GetBestMovePlyChanges(), prevBestMovePlyChanges);
				}

				// 次のイテレーションを回す時間が無いなら、ストップ
				if (
					rucksack.m_timeManager.CanNotNextIteration(rucksack.m_stopwatch.GetElapsed())
					) {
					stop = true;
				}

				if (2 < depth && rucksack.GetBestMovePlyChanges()) {
					bestMoveNeverChanged = false;
				}

				// 最善手が、ある程度の深さまで同じであれば、
				// その手が突出して良い手なのだろう。
				if (
					12 <= depth
					&& !stop
					&& bestMoveNeverChanged
					&& rucksack.m_pvSize == 1
					// ここは確実にバグらせないようにする。
					&& -ScoreInfinite + 2 * PieceScore::m_capturePawn <= bestScore
					&& (
						rucksack.m_rootMoves.size() == 1
						||
						// または、利用可能時間の40%が、思考経過時間未満の場合。
						rucksack.m_timeManager.CanThinking02_TimeOk_ForIterativeDeepingLoop(rucksack.m_stopwatch.GetElapsed())
					)
				) {
					const ScoreIndex rBeta = bestScore - 2 * PieceScore::m_capturePawn;
					(flashlight + 1)->m_staticEvalRaw.m_p[0][0] = ScoreNotEvaluated;
					(flashlight + 1)->m_excludedMove = rucksack.m_rootMoves[0].m_pv_[0];
					(flashlight + 1)->m_skipNullMove = true;

					//────────────────────────────────────────────────────────────────────────────────
					// さあ、探索に潜るぜ~☆!(^q^) 2回目のぐるんぐるんだぜ~☆ ノンPV~☆
					//────────────────────────────────────────────────────────────────────────────────
					const ScoreIndex s = g_NODETYPE_PROGRAMS[NodeType::N02_NonPV]->GoToTheAdventure_new(
						rucksack, pos, flashlight + 1, rBeta - 1, rBeta, (depth - 3) * OnePly, true);

					(flashlight + 1)->m_skipNullMove = false;
					(flashlight + 1)->m_excludedMove = g_MOVE_NONE;

					if (s < rBeta) {
						stop = true;
					}
				}

				if (stop) {
					if (rucksack.m_limits.m_ponder) {
						rucksack.m_signals.m_stopOnPonderHit = true;
					}
					else {
						rucksack.m_signals.m_stop = true;
					}
				}
			}
		}
		skill.swapIfEnabled(&rucksack);
		SYNCCOUT << rucksack.PvInfoToUSI(pos, depth - 1, alpha, beta) << SYNCENDL;
	}
void debugSM(ros::NodeHandle &n)
{
    //PUBLISHER FOR MOTIONCONTROL
    ros::Publisher roboCom = n.advertise<robot_soccer::controldata>("robot2Com", 5);

    //SUBSCRIBER FROM VISION
    ros::Subscriber vision_subscriber = n.subscribe("vision_data", 5, visionCallback);
    (void*)vision_subscriber;

    ros::Rate loop_rate(TICKS_PER_SEC);
    bool dataInitialized = false;
    bool init = true;

    ros::Subscriber debug_subscriber = n.subscribe("debug", 5, debugCallback);
    (void*)debug_subscriber;
    Skills skill(RobotType::ally2);
    Point dest;
    bool kickball = false;
    char kickCounter = 0;
    bool kickCmd = false;
    while(ros::ok()){

        if (visionUpdated) {
            visionUpdated = false;
            dataInitialized = true;
            field.updateStatus(visionStatus_msg);
        }
        if (newDebugCmd || init) {


            init = false;
            newDebugCmd = false;
            cmdRob2.cmdType = debugCmd.cmdType;
            cmdRob2.x_cmd = debugCmd.x_cmd;
            cmdRob2.y_cmd = debugCmd.y_cmd;
            cmdRob2.theta_cmd = debugCmd.theta_cmd;
            if (cmdRob2.cmdType == "moveslow" || cmdRob2.cmdType == "movefast") {
                moveSpeed speed;
                if(cmdRob2.cmdType == "moveslow"){
                    speed = moveSpeed::slow;
                } else
                    speed = moveSpeed::fast;

                dest = Point(cmdRob2.x_cmd,cmdRob2.y_cmd);
                skill.goToPoint(speed, dest, cmdRob2.theta_cmd);
            } else if (cmdRob2.cmdType == "kick") {
                kickball = true;
                skill.kick();
            } else if (cmdRob2.cmdType == "kickinit"){
                skill.init_kick();
                std::cout << "initing kicker" << std::endl;
            } else if (cmdRob2.cmdType == "kickuninit"){
                std::cout << "unit kicker" << std::endl;
                skill.uninit_kick();
            } else{
                skill.idle();
            }
        }

        skill.tick();
        if (sendCmd_Rob2) {
            sendCmd_Rob2 = false;
            checkCmd(cmdRob2);
            roboCom.publish(cmdRob2);

        }
        ros::spinOnce();

        loop_rate.sleep();
    }
}
Пример #23
0
RPG_Player_PlayerXML_XMLTree_Type*
RPG_Player_Common_Tools::playerToPlayerXML(const RPG_Player& player_in)
{
  RPG_TRACE(ACE_TEXT("RPG_Player_Common_Tools::playerToPlayerXML"));

  RPG_Character_Alignment_XMLTree_Type alignment(RPG_Character_AlignmentCivicHelper::RPG_Character_AlignmentCivicToString(player_in.getAlignment().civic),
  RPG_Character_AlignmentEthicHelper::RPG_Character_AlignmentEthicToString(player_in.getAlignment().ethic));

  RPG_Character_Attributes_XMLTree_Type attributes(player_in.getAttribute(ATTRIBUTE_STRENGTH),
                                                   player_in.getAttribute(ATTRIBUTE_DEXTERITY),
                                                   player_in.getAttribute(ATTRIBUTE_CONSTITUTION),
                                                   player_in.getAttribute(ATTRIBUTE_INTELLIGENCE),
                                                   player_in.getAttribute(ATTRIBUTE_WISDOM),
                                                   player_in.getAttribute(ATTRIBUTE_CHARISMA));

  RPG_Player_Conditions_XMLTree_Type conditions;
  RPG_Character_Conditions_t character_condition = player_in.getCondition();
  for (RPG_Character_ConditionsIterator_t iterator = character_condition.begin();
       iterator != character_condition.end();
       iterator++)
    conditions.condition().push_back(RPG_Common_ConditionHelper::RPG_Common_ConditionToString(*iterator));

  RPG_Item_InventoryXML_XMLTree_Type inventory;
  RPG_Player_Inventory character_inventory = player_in.getInventory();
  RPG_Item_Base* item_base = NULL;
  for (RPG_Item_ListIterator_t iterator = character_inventory.myItems.begin();
       iterator != character_inventory.myItems.end();
       iterator++)
  {
    // retrieve item details
    RPG_ITEM_INSTANCE_MANAGER_SINGLETON::instance()->get(*iterator,
                                                         item_base);
    ACE_ASSERT(item_base);
    RPG_Item_BaseXML_XMLTree_Type item(RPG_Item_TypeHelper::RPG_Item_TypeToString(item_base->getType()));
    switch (item_base->getType())
    {
      case ITEM_ARMOR:
      {
        RPG_Item_Armor* armor = dynamic_cast<RPG_Item_Armor*>(item_base);
        ACE_ASSERT(armor);

        RPG_Item_ArmorProperties armor_properties =
            RPG_ITEM_DICTIONARY_SINGLETON::instance()->getArmorProperties(armor->getArmorType());

        RPG_Item_StorePrice_XMLTree_Type store_price;
        if (armor_properties.baseStorePrice.numGoldPieces)
          store_price.numGoldPieces(armor_properties.baseStorePrice.numGoldPieces);
        if (armor_properties.baseStorePrice.numSilverPieces)
          store_price.numSilverPieces(armor_properties.baseStorePrice.numSilverPieces);
        RPG_Item_ArmorPropertiesXML_XMLTree_Type armor_properties_xml(armor_properties.baseWeight,
                                                                      store_price,
                                                                      RPG_Item_ArmorTypeHelper::RPG_Item_ArmorTypeToString(armor->getArmorType()),
                                                                      RPG_Item_ArmorCategoryHelper::RPG_Item_ArmorCategoryToString(armor_properties.category),
                                                                      armor_properties.baseBonus,
                                                                      armor_properties.maxDexterityBonus,
                                                                      armor_properties.checkPenalty,
                                                                      armor_properties.arcaneSpellFailure,
                                                                      armor_properties.baseSpeed);
        if (armor_properties.defenseModifier)
          armor_properties_xml.defenseModifier(armor_properties.defenseModifier);
        if (armor_properties.aura != RPG_MAGIC_SCHOOL_INVALID)
          armor_properties_xml.aura(RPG_Magic_SchoolHelper::RPG_Magic_SchoolToString(armor_properties.aura));
        if (armor_properties.prerequisites.minCasterLevel)
        {
          RPG_Item_MagicalPrerequisites_XMLTree_Type magical_prerequisites;
          magical_prerequisites.minCasterLevel(armor_properties.prerequisites.minCasterLevel);
          armor_properties_xml.prerequisites(magical_prerequisites);
        } // end IF
        if (armor_properties.costToCreate.numGoldPieces ||
            armor_properties.costToCreate.numExperiencePoints)
        {
          RPG_Item_CreationCost_XMLTree_Type costs_to_create;
          if (armor_properties.costToCreate.numGoldPieces)
            costs_to_create.numGoldPieces(armor_properties.costToCreate.numGoldPieces);
          if (armor_properties.costToCreate.numExperiencePoints)
            costs_to_create.numExperiencePoints(armor_properties.costToCreate.numExperiencePoints);
          armor_properties_xml.costToCreate(costs_to_create);
        } // end IF

        item.armor(armor_properties_xml);
        inventory.item().push_back(item);

        break;
      }
      case ITEM_COMMODITY:
      {
        RPG_Item_Commodity* commodity = dynamic_cast<RPG_Item_Commodity*>(item_base);
        ACE_ASSERT(commodity);

        RPG_Item_CommodityProperties commodity_properties =
            RPG_ITEM_DICTIONARY_SINGLETON::instance()->getCommodityProperties(commodity->getCommoditySubType());

        RPG_Item_StorePrice_XMLTree_Type store_price;
        if (commodity_properties.baseStorePrice.numGoldPieces)
          store_price.numGoldPieces(commodity_properties.baseStorePrice.numGoldPieces);
        if (commodity_properties.baseStorePrice.numSilverPieces)
          store_price.numSilverPieces(commodity_properties.baseStorePrice.numSilverPieces);
        RPG_Item_CommodityPropertiesBase_XMLTree_Type commodity_properties_xml(commodity_properties.baseWeight,
                                                                               store_price,
                                                                               RPG_Item_CommodityTypeHelper::RPG_Item_CommodityTypeToString(commodity->getCommodityType()),
                                                                               RPG_Item_Common_Tools::commoditySubTypeToXMLString(commodity->getCommoditySubType()));
        if (commodity_properties.aura != RPG_MAGIC_SCHOOL_INVALID)
          commodity_properties_xml.aura(RPG_Magic_SchoolHelper::RPG_Magic_SchoolToString(commodity_properties.aura));
        if (commodity_properties.prerequisites.minCasterLevel)
        {
          RPG_Item_MagicalPrerequisites_XMLTree_Type magical_prerequisites;
          magical_prerequisites.minCasterLevel(commodity_properties.prerequisites.minCasterLevel);
          commodity_properties_xml.prerequisites(magical_prerequisites);
        } // end IF
        if (commodity_properties.costToCreate.numGoldPieces ||
            commodity_properties.costToCreate.numExperiencePoints)
        {
          RPG_Item_CreationCost_XMLTree_Type costs_to_create;
          if (commodity_properties.costToCreate.numGoldPieces)
            costs_to_create.numGoldPieces(commodity_properties.costToCreate.numGoldPieces);
          if (commodity_properties.costToCreate.numExperiencePoints)
            costs_to_create.numExperiencePoints(commodity_properties.costToCreate.numExperiencePoints);
          commodity_properties_xml.costToCreate(costs_to_create);
        } // end IF

        item.commodity(commodity_properties_xml);
        inventory.item().push_back(item);

        break;
      }
      case ITEM_OTHER:
      case ITEM_VALUABLE:
      {
        // *TODO*
        ACE_ASSERT(false);

        break;
      }
      case ITEM_WEAPON:
      {
        RPG_Item_Weapon* weapon = dynamic_cast<RPG_Item_Weapon*>(item_base);
        ACE_ASSERT(weapon);

        RPG_Item_WeaponProperties weapon_properties =
            RPG_ITEM_DICTIONARY_SINGLETON::instance()->getWeaponProperties(weapon->getWeaponType());

        RPG_Item_BaseXML_XMLTree_Type item(RPG_Item_TypeHelper::RPG_Item_TypeToString(item_base->getType()));
        RPG_Item_StorePrice_XMLTree_Type store_price;
        if (weapon_properties.baseStorePrice.numGoldPieces)
          store_price.numGoldPieces(weapon_properties.baseStorePrice.numGoldPieces);
        if (weapon_properties.baseStorePrice.numSilverPieces)
          store_price.numSilverPieces(weapon_properties.baseStorePrice.numSilverPieces);
        RPG_Dice_Roll_XMLTree_Type base_damage(RPG_Dice_DieTypeHelper::RPG_Dice_DieTypeToString(weapon_properties.baseDamage.typeDice));
        if (weapon_properties.baseDamage.numDice)
          base_damage.numDice(weapon_properties.baseDamage.numDice);
        if (weapon_properties.baseDamage.modifier)
          base_damage.modifier(weapon_properties.baseDamage.modifier);
        RPG_Item_CriticalHitProperties_XMLTree_Type critical_hit_properties(weapon_properties.criticalHit.minToHitRoll,
                                                                            weapon_properties.criticalHit.damageModifier);
        RPG_Item_WeaponPropertiesXML_XMLTree_Type weapon_properties_xml(weapon_properties.baseWeight,
                                                                        store_price,
                                                                        RPG_Item_WeaponTypeHelper::RPG_Item_WeaponTypeToString(weapon->getWeaponType()),
                                                                        RPG_Item_WeaponCategoryHelper::RPG_Item_WeaponCategoryToString(weapon_properties.category),
                                                                        RPG_Item_WeaponClassHelper::RPG_Item_WeaponClassToString(weapon_properties.weaponClass),
                                                                        base_damage,
                                                                        critical_hit_properties);
        if (weapon_properties.toHitModifier)
          weapon_properties_xml.toHitModifier(weapon_properties.toHitModifier);
        if (weapon_properties.rangeIncrement)
          weapon_properties_xml.rangeIncrement(weapon_properties.rangeIncrement);
        RPG_Item_WeaponPropertiesBase_XMLTree_Type::typeOfDamage_sequence type_of_damage;
        int index = PHYSICALDAMAGE_NONE; index++;
        for (unsigned int i = 0;
             i < weapon_properties.typeOfDamage.size();
             i++, index++)
         if (weapon_properties.typeOfDamage.test(i))
           type_of_damage.push_back(RPG_Common_PhysicalDamageTypeHelper::RPG_Common_PhysicalDamageTypeToString(static_cast<RPG_Common_PhysicalDamageType>(index)));
        weapon_properties_xml.typeOfDamage(type_of_damage);
        weapon_properties_xml.isNonLethal(weapon_properties.isNonLethal);
        weapon_properties_xml.isReachWeapon(weapon_properties.isReachWeapon);
        weapon_properties_xml.isDoubleWeapon(weapon_properties.isDoubleWeapon);
        if (weapon_properties.aura != RPG_MAGIC_SCHOOL_INVALID)
          weapon_properties_xml.aura(RPG_Magic_SchoolHelper::RPG_Magic_SchoolToString(weapon_properties.aura));
        if (weapon_properties.prerequisites.minCasterLevel)
        {
          RPG_Item_MagicalPrerequisites_XMLTree_Type magical_prerequisites;
          magical_prerequisites.minCasterLevel(weapon_properties.prerequisites.minCasterLevel);
          weapon_properties_xml.prerequisites(magical_prerequisites);
        } // end IF
        if (weapon_properties.costToCreate.numGoldPieces ||
            weapon_properties.costToCreate.numExperiencePoints)
        {
          RPG_Item_CreationCost_XMLTree_Type costs_to_create;
          if (weapon_properties.costToCreate.numGoldPieces)
            costs_to_create.numGoldPieces(weapon_properties.costToCreate.numGoldPieces);
          if (weapon_properties.costToCreate.numExperiencePoints)
            costs_to_create.numExperiencePoints(weapon_properties.costToCreate.numExperiencePoints);
          weapon_properties_xml.costToCreate(costs_to_create);
        } // end IF

        item.weapon(weapon_properties_xml);
        inventory.item().push_back(item);

        break;
      }
      default:
      {
        ACE_DEBUG((LM_ERROR,
                   ACE_TEXT("invalid item type (was: \"%s\"), aborting\n"),
                   ACE_TEXT(RPG_Item_TypeHelper::RPG_Item_TypeToString(item_base->getType()).c_str())));

        return NULL;
      }
    } // end SWITCH
  } // end FOR

  RPG_Character_Class character_class = player_in.getClass();
  RPG_Character_ClassXML_XMLTree_Type classXML(RPG_Character_MetaClass_XMLTree_Type(static_cast<RPG_Character_MetaClass_XMLTree_Type::value>(character_class.metaClass)));
  for (RPG_Character_SubClassesIterator_t iterator = character_class.subClasses.begin();
       iterator != character_class.subClasses.end();
       iterator++)
    classXML.subClass().push_back(RPG_Common_SubClass_XMLTree_Type(static_cast<RPG_Common_SubClass_XMLTree_Type::value>(*iterator)));

  RPG_Player_PlayerXML_XMLTree_Type* player_p = NULL;
  ACE_NEW_NORETURN(player_p,
                   RPG_Player_PlayerXML_XMLTree_Type(player_in.getName(),
                                                     alignment,
                                                     attributes,
                                                     RPG_Common_Size_XMLTree_Type(static_cast<RPG_Common_Size_XMLTree_Type::value>(player_in.getSize())),
                                                     player_in.getNumTotalHitPoints(),
                                                     classXML,
                                                     RPG_Character_Gender_XMLTree_Type(static_cast<RPG_Character_Gender_XMLTree_Type::value>(player_in.getGender())),
                                                     RPG_Character_OffHand_XMLTree_Type(static_cast<RPG_Character_OffHand_XMLTree_Type::value>(player_in.getOffHand())),
                                                     player_in.getWealth(),
                                                     inventory,
                                                     player_in.getExperience()));
  if (!player_p)
  {
    ACE_DEBUG((LM_CRITICAL,
               ACE_TEXT("failed to allocate memory(%u), aborting\n"),
               sizeof(RPG_Player_PlayerXML_XMLTree_Type)));

    return NULL;
  } // end IF
  ACE_ASSERT(player_p);

  // *NOTE*: add race, skills, feats, abilities, known spells, prepared spells sequences "manually"
  RPG_Character_Race_t character_race = player_in.getRace();
  int index = RACE_NONE; index++;
  for (unsigned int i = 0;
       i < character_race.size();
       i++, index++)
    if (character_race.test(i))
      player_p->race().push_back(RPG_Character_RaceHelper::RPG_Character_RaceToString(static_cast<RPG_Character_Race>(index)));

  RPG_Character_Skills_XMLTree_Type skills;
  RPG_Character_Skills_t character_skills = player_in.getSkills();
  for (RPG_Character_SkillsConstIterator_t iterator = character_skills.begin();
       iterator != character_skills.end();
       iterator++)
  {
    RPG_Character_SkillValue_XMLTree_Type skill(RPG_Common_SkillHelper::RPG_Common_SkillToString((*iterator).first),
                                                (*iterator).second);
    skills.skill().push_back(skill);
  } // end FOR
  player_p->skills().set(skills);

  RPG_Character_Feats_XMLTree_Type feats;
  RPG_Character_Feats_t character_feats = player_in.getFeats();
  for (RPG_Character_FeatsConstIterator_t iterator = character_feats.begin();
       iterator != character_feats.end();
       iterator++)
    feats.feat().push_back(RPG_Character_FeatHelper::RPG_Character_FeatToString(*iterator));
  player_p->feats().set(feats);

  RPG_Player_Abilities_XMLTree_Type abilities;
  RPG_Character_Abilities_t character_abilities = player_in.getAbilities();
  for (RPG_Character_AbilitiesConstIterator_t iterator = character_abilities.begin();
       iterator != character_abilities.end();
       iterator++)
    abilities.ability().push_back(RPG_Character_AbilityHelper::RPG_Character_AbilityToString(*iterator));
  player_p->abilities().set(abilities);

  RPG_Player_Spells_XMLTree_Type spell_list;
  RPG_Magic_SpellTypes_t character_known_spells = player_in.getKnownSpells();
  for (RPG_Magic_SpellTypesIterator_t iterator = character_known_spells.begin();
       iterator != character_known_spells.end();
       iterator++)
    spell_list.spell().push_back(RPG_Magic_SpellTypeHelper::RPG_Magic_SpellTypeToString(*iterator));
  player_p->knownSpells().set(spell_list);

  return player_p;
}