Exemple #1
0
void
MainThread::work()
{
    setMaxHeartbeatInterval( 5.0 );

    while ( !isStopping() )
    {
        try {
            bool dummy;
            const int TIMEOUT_MS = 1000;
            int ret = requestStore_.getNext( dummy, TIMEOUT_MS );
            if ( ret == 0 )
            {
                takeSnapshot();
            
                // Clear any requests that might have arrived while we were taking the snapshot
                if ( !requestStore_.isEmpty() )
                    requestStore_.get( dummy );
            }
            health().ok();
        }
        catch ( ... ) 
        {
            orcaice::catchMainLoopExceptions( health() );
        }
    }
}
Exemple #2
0
t_bunny_response	main_loop(t_data *pic)
{
  if (pic->wolf->left == 1)
    left(pic);
  if (pic->wolf->up == 1)
    if (up(pic) == 1)
      return (0);
  if (pic->wolf->down == 1)
    if (down(pic) == 1)
      return (0);
  if (pic->wolf->right == 1)
    right(pic);
  if (pic->wolf->player.health < 0)
    {
      my_putstr("Game Over\n");
      return (0);
    }
  bunny_set_key_response(get_mykey);
  set_background(pic->pix, &pic->color[0]);
  raycasting(pic->wolf, pic->pix);
  health(pic->wolf, pic->pix);
  bunny_blit(&pic->win->buffer, &pic->pix->clipable, NULL);
  bunny_display(pic->win);
  return (GO_ON);
}
Exemple #3
0
 int calculateMinimumHP(vector<vector<int>>& dungeon) {
     int row = dungeon.size();
     int col = dungeon[0].size();
     
     // health[i][j] represents the min health the knight need at position (i, j)
     vector<vector<int>> health(row + 1, vector<int>(col + 1, INT_MAX));
     
     // If at any point his health point drops to 0 or below, he dies immediately
     health[row][col-1] = 1;
     health[row-1][col] = 1;
     
     for(int i = row - 1; i >= 0; i--) {
         for(int j = col - 1; j >= 0; j--) {
             // to calculate how much extra health need at point (i, j)
             int need = min(health[i+1][j], health[i][j+1]) - dungeon[i][j];
             
             // if no extra health required, the knight only need 1 health to keep his life
             if(need <= 0) {
                 health[i][j] = 1;
             } else {
                 health[i][j] = need;
             }
         }
     }
     
     return health[0][0];
 }
Exemple #4
0
pd::player::player(pd::game_session *session, float x, float y)
    : pd::entity(session, x, y, 60.0f, 90.0f, -20.0f, 20.0f, 0.0f, true),
      m_thermal_idle_anim(pd::get_resource<pd::texture>("textures/character_thermal_idle.png"), 17, 0.05f),
      m_flamethrower_anim(pd::get_resource<pd::texture>("textures/flamer.png"), 5, 0.1f)
{
    stance(thermal_stance);

    m_energy = 1.0f;
    health(200.0f);
    m_shooting = false;
    m_stoped = true;
}
Exemple #5
0
	void Creep::draw(int size) {
		LabSetColor(LABCOLOR_DARK_RED);
		MyRect center(0, 0, 50*size/100, 50*size/100);
		center.drawFilled(m_x - 50*size/200, m_y - 50*size/200);

		LabSetColor(m_color);
		MyRect health(0, 0, (m_health*50*size/100/m_health_default), (m_health*50*size/100/m_health_default));
		health.drawFilled(m_x - 50*size/200, m_y - 50*size/200);

		MyRect border(0, 0, 50*size/100, 50*size/100);
		LabSetColor(LABCOLOR_BLACK);
		border.draw(m_x - 50*size/200, m_y - 50*size/200);
	}
Exemple #6
0
void Menu::draw(sf::RenderWindow* w) {
  sf::Sprite health(healthIcon_);
  health.setPosition(IMAGE_X + ICON_SIZE/2, HEALTH_Y + ICON_SIZE/2);
  w->draw(health);

  sf::Sprite armor(armorIcon_);
  armor.setPosition(IMAGE_X + ICON_SIZE/2, ARMOR_Y + ICON_SIZE/2);
  w->draw(armor);

  w->draw(healthText_);
  w->draw(meleeText_);
  w->draw(rangeText_);
  w->draw(magicText_);
  w->draw(armorText_);
}
Exemple #7
0
		void npc::action_unit(environment &current)
		{
			person::action_unit(current);

			point dest = current.player()->position();

			if (m_ai_state == ai_state::idle)
			{
				if (current.distance(dest, position()) <= alert_distance || !health().full())
				{
					m_ai_state = ai_state::alert;
					current.broadcast({ "!", 0xff0000, position(), 1.0 });
				}
			}
			else if (m_ai_state == ai_state::alert)
			{
				auto scene = current.scene();
				auto path = path::find(position(), dest, 50, [&](const point &p) { return scene->traversable(p); });
				if (path)
				{
					auto step = path->begin();
					if (step != path->end())
					{
						auto blocking = scene->blocking(*step);
						if (blocking && !blocking->invincible())
						{
							for (auto &skill : m_skills)
							{
								if (skill.targeted() && skill.useable(this, blocking))
								{
									skill.use(this, blocking);
									break;
								}
								else if (skill.useable(this, dest))
								{
									skill.use(this, dest);
									break;
								}
							}
						}
						else
						{
							scene->move(*this, *step);
						}
					}
				}
			}
		}
void RegularBattleScene::updateHp(int spot, int val)
{
    int value = val == -1 ? data()->poke(spot).life() : val;
    int pvalue = value * 100 / data()->poke(spot).totalLife();
    if (pvalue == 0 && value > 0) {
        pvalue = 1;
    }

    gui.bars[spot]->setStyleSheet(health(pvalue));
    if (info.percentage[spot]) {
        gui.bars[spot]->setValue(pvalue);
    } else {
        gui.bars[spot]->setRange(0, data()->poke(spot).totalLife());
        gui.bars[spot]->setValue(value);
    }
}
Exemple #9
0
 int calculateMinimumHP(vector<vector<int>>& dungeon) {
     if (dungeon.empty() || dungeon.back().empty()) return 1;
     int n = dungeon.back().size();
     vector<int> health(n + 1, INT_MAX);
     health[n-1] = 1;
     for (int i=dungeon.size() -1; i>=0; --i) {
         for (int j=n-1;j>=0;--j) {
             int h = INT_MAX;
             int hh = min(health[j],health[j+1]);
             if (hh <= dungeon[i][j]) {
                 h = 1;
             } else {
                 hh -= dungeon[i][j];
                 if (hh > 0) h=hh;   //overflow check
             }
             health[j] = h;
         }
     }
     return health[0];
 }
Exemple #10
0
Entity *Message::ExtractEntity() {
  if (message_type_ == kEntityDataMessage ||
      message_type_ == kViewUpdateMessage) {
    boost::uuids::uuid source = ExtractUuid();
    std::string name = ExtractString();
    int health_value = ExtractInt();
    int health_bound = ExtractInt();
    BoundedAttribute health(health_value, health_bound);

    Entity *entity = new Entity(name, health);
    entity->AssignId(source);

    std::string weapon_name = ExtractString();
    int value = ExtractInt();
    int min_damage = ExtractInt();
    int max_damage = ExtractInt();
    Weapon *weapon = new Weapon(weapon_name, value, min_damage, max_damage);
    weapon->Equip(*entity);

    return entity;
  }

  return NULL;
}
Exemple #11
0
174. Dungeon Game

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.


Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

-2 (K)	-3	3
-5	-10	1
10	30	-5 (P)

Notes:

The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

//Microsoft

//Hard
class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        if (dungeon.size() == 0 || dungeon[0].size() == 0) return 0;
	void FuzzyAITest(void)
	{
		AI::Fuzzy::Logic health("Health");
		health.getSet("Bad")->add(AI::Fuzzy::Set::Member(0.0f,1.0f));
		health.getSet("Bad")->add(AI::Fuzzy::Set::Member(0.3f,1.0f));
		health.getSet("Bad")->add(AI::Fuzzy::Set::Member(0.6f,0.0f));

		health.getSet("Good")->add(AI::Fuzzy::Set::Member(0.4f,0.0f));
		health.getSet("Good")->add(AI::Fuzzy::Set::Member(0.7f,1.0f));
		health.getSet("Good")->add(AI::Fuzzy::Set::Member(1.0f,1.0f));

		AI::Fuzzy::Logic armour("Armour");
		armour.getSet("Inadequate")->add(AI::Fuzzy::Set::Member(0.0f, 1.0f));
		armour.getSet("Inadequate")->add(AI::Fuzzy::Set::Member(0.2f, 1.0f));
		armour.getSet("Inadequate")->add(AI::Fuzzy::Set::Member(0.4f, 0.0f));

		armour.getSet("Marginal")->add(AI::Fuzzy::Set::Member(0.3f, 0.0f));
		armour.getSet("Marginal")->add(AI::Fuzzy::Set::Member(0.5f, 1.0f));
		armour.getSet("Marginal")->add(AI::Fuzzy::Set::Member(0.7f, 0.0f));

		armour.getSet("Adequate")->add(AI::Fuzzy::Set::Member(0.6f, 0.0f));
		armour.getSet("Adequate")->add(AI::Fuzzy::Set::Member(0.8f, 1.0f));
		armour.getSet("Adequate")->add(AI::Fuzzy::Set::Member(1.0f, 1.0f));

		AI::Fuzzy::Logic risk("Risk");
		risk.getSet("Low")->add(AI::Fuzzy::Set::Member(0.0f, 1.0f));
		risk.getSet("Low")->add(AI::Fuzzy::Set::Member(0.2f, 1.0f));
		risk.getSet("Low")->add(AI::Fuzzy::Set::Member(0.4f, 0.0f));

		risk.getSet("Med")->add(AI::Fuzzy::Set::Member(0.3f, 0.0f));
		risk.getSet("Med")->add(AI::Fuzzy::Set::Member(0.5f, 1.0f));
		risk.getSet("Med")->add(AI::Fuzzy::Set::Member(0.7f, 0.0f));

		risk.getSet("High")->add(AI::Fuzzy::Set::Member(0.6f, 0.0f));
		risk.getSet("High")->add(AI::Fuzzy::Set::Member(0.8f, 1.0f));
		risk.getSet("High")->add(AI::Fuzzy::Set::Member(1.0f, 1.0f));

		AI::Fuzzy::Set::Ptr a = risk.getSet(0.35f, AI::Fuzzy::Logic::MAX);
		AI::Fuzzy::Set::Ptr b = risk.getSet(0.35f, AI::Fuzzy::Logic::MIN);
		AI::Fuzzy::Set::Ptr c = risk.getSet(0.35f, AI::Fuzzy::Logic::RAND);


		AI::Fuzzy::Set::Member currHealth(0.45f), currArmour(0.65f);
		float badHealth = health.getSet("Bad")->membership(currHealth.value());
		float goodHealth = health.getSet("Good")->membership(currHealth.value());

		float inadequateArmour = armour.getSet("Inadequate")->membership(currArmour.value());
		float marginalArmour = armour.getSet("Marginal")->membership(currArmour.value());
		float adequateArmour = armour.getSet("Adequate")->membership(currArmour.value());

		AI::Fuzzy::EvalRule::Ptr healthGood(new AI::Fuzzy::EvalRule(health.getSet("Good"), currHealth));
		AI::Fuzzy::Rule::Ptr armourAdequate(new AI::Fuzzy::EvalRule(armour.getSet("Adequate"), currArmour));
		AI::Fuzzy::Rule::Ptr healthGoodAndArmourAdequate(new AI::Fuzzy::AndRule(healthGood, armourAdequate));

		AI::Fuzzy::EvalRule::Ptr healthBad(new AI::Fuzzy::EvalRule(health.getSet("Bad"), currHealth));
		AI::Fuzzy::Rule::Ptr armourMarginal(new AI::Fuzzy::EvalRule(armour.getSet("Marginal"), currArmour));
		AI::Fuzzy::Rule::Ptr healthBadAndArmourMarginal(new AI::Fuzzy::OrRule(healthBad, armourMarginal));

		AI::Fuzzy::EvalRule::Ptr armourInadequate(new AI::Fuzzy::EvalRule(armour.getSet("Inadequate"), currArmour));
		AI::Fuzzy::Rule::Ptr healthBadAndArmourInadequate(new AI::Fuzzy::AndRule(healthBad, armourInadequate));

		AI::Fuzzy::RuleSet ruleset; 
		ruleset.add(AI::Fuzzy::RuleSet::Pair(risk.getSet("Low"), healthGoodAndArmourAdequate));
		ruleset.add(AI::Fuzzy::RuleSet::Pair(risk.getSet("Med"), healthBadAndArmourMarginal));
		ruleset.add(AI::Fuzzy::RuleSet::Pair(risk.getSet("High"), healthBadAndArmourInadequate));

		float centroid = ruleset.apply(10);
	}
void Human::print()
{
    qDebug() << name() << "-" << profession();
    qDebug() << "   Exp:" << experience() << "  Health:" << health();
}
Exemple #14
0
void AppManager::rescan()
{
    m_appList.clear();
    m_apps.clear();

    AppInfo settingsApp(QUuid(SETTINGS_APP_UUID), false, gettext("Settings"), gettext("System app"));
    m_appList.append(settingsApp.uuid());
    m_apps.insert(settingsApp.uuid(), settingsApp);
    AppInfo watchfaces(QUuid("18e443ce-38fd-47c8-84d5-6d0c775fbe55"), false, gettext("Watchfaces"), gettext("System app"));
    m_appList.append(watchfaces.uuid());
    m_apps.insert(watchfaces.uuid(), watchfaces);
    if (m_pebble->capabilities().testFlag(CapabilityHealth)) {
        AppInfo health(QUuid("36d8c6ed-4c83-4fa1-a9e2-8f12dc941f8c"), false, gettext("Health"), gettext("System app"), true);
        m_appList.append(health.uuid());
        m_apps.insert(health.uuid(), health);
    }
    AppInfo music(QUuid("1f03293d-47af-4f28-b960-f2b02a6dd757"), false, gettext("Music"), gettext("System app"));
    m_appList.append(music.uuid());
    m_apps.insert(music.uuid(), music);
    if(m_pebble->capabilities().testFlag(CapabilityWeather)) {
        AppInfo weather(WeatherApp::appUUID, false, gettext("Weather"), gettext("System app"), true);
        m_appList.append(weather.uuid());
        m_apps.insert(weather.uuid(), weather);
    }
    if(m_pebble->capabilities().testFlag(CapabilitySendSMS)) {
        AppInfo sendsms(SendTextApp::appUUID, false, SendTextApp::appName, gettext("System app"), true);
        m_appList.append(sendsms.uuid());
        m_apps.insert(sendsms.uuid(), sendsms);
    }
    AppInfo notifications(QUuid("b2cae818-10f8-46df-ad2b-98ad2254a3c1"), false, gettext("Notifications"), gettext("System app"));
    m_appList.append(notifications.uuid());
    m_apps.insert(notifications.uuid(), notifications);
    AppInfo alarms(QUuid("67a32d95-ef69-46d4-a0b9-854cc62f97f9"), false, gettext("Alarms"), gettext("System app"));
    m_appList.append(alarms.uuid());
    m_apps.insert(alarms.uuid(), alarms);
    AppInfo ticToc(QUuid("8f3c8686-31a1-4f5f-91f5-01600c9bdc59"), true, "Tic Toc", gettext("Default watchface"));
    m_appList.append(ticToc.uuid());
    m_apps.insert(ticToc.uuid(), ticToc);

    QDir dir(m_pebble->storagePath() + "/apps/");
    qDebug() << "Scanning Apps dir" << dir.absolutePath();
    Q_FOREACH(const QString &path, dir.entryList(QDir::Dirs | QDir::Readable)) {
        QString appPath = dir.absoluteFilePath(path);
        if (dir.exists(path + "/appinfo.json")) {
            scanApp(appPath);
        } else if (QFileInfo(appPath).isFile()) {
            scanApp(appPath);
        }
    }

    QSettings settings(m_pebble->storagePath() + "/apps.conf", QSettings::IniFormat);
    QStringList storedList = settings.value("appList").toStringList();
    if (storedList.isEmpty()) {
        // User did not manually sort the app list yet... We can stop here.
        return;
    }
    // Run some sanity checks
    if (storedList.count() != m_appList.count()) {
        qWarning() << "Installed apps not matching order config. App sort order might be wrong.";
        return;
    }
    foreach (const QUuid &uuid, m_appList) {
        if (!storedList.contains(uuid.toString())) {
            qWarning() << "Installed apps and stored config order cannot be matched. App sort order might be wrong.";
            return;
        }
    }
    // All seems fine, repopulate m_appList
    m_appList.clear();
    foreach (const QString &storedId, storedList) {
        m_appList.append(QUuid(storedId));
    }
Exemple #15
0
void PlayerObject::regen() {
  setHealth(health() + healthRegen());
  setMana(mana() + manaRegen());
}
/**
 * @brief Write the Human data back to a file.
 */
void Human::writeToFile( QFile &unitFile )
{
    QTextStream unitStream(&unitFile);

    unitStream << profession() << "/"
               << QString("%1").arg(posX(),0,'g',8) << "/"
               << QString("%1").arg(posY(),0,'g',8) << "/"
               << QString("%1").arg(posZ(),0,'g',8) << "/"
               << name() << "/";
    unitStream.flush();

    unitFile.write(Utils::toBinary(archerLevel()));
    unitFile.write(Utils::toBinary(blacksmithLevel()));
    unitFile.write(Utils::toBinary(builderLevel()));
    unitFile.write(Utils::toBinary(carpenterLevel()).constData());
    unitFile.write(Utils::toBinary(engineerLevel()).constData());
    unitFile.write(Utils::toBinary(farmerLevel()).constData());
    unitFile.write(Utils::toBinary(fishermanLevel()).constData());
    unitFile.write(Utils::toBinary(foragerLevel()).constData());
    unitFile.write(Utils::toBinary(infantryLevel()).constData());
    unitFile.write(Utils::toBinary(minerLevel()).constData());
    unitFile.write(Utils::toBinary(stoneMasonLevel()).constData());
    unitFile.write(Utils::toBinary(woodChopperLevel()).constData());
    unitFile.write(Utils::toBinary(tailorLevel()).constData());
    unitFile.write(Utils::toBinary(traderLevel()).constData());
    unitFile.write(Utils::toBinary(herderLevel()).constData());
    unitFile.write(Utils::toBinary(adventurerLevel()).constData());
    unitFile.write(Utils::toBinary(unknown1Level()).constData());
    unitFile.write(Utils::toBinary(unknown2Level()).constData());
    unitFile.write(Utils::toBinary(unknown3Level()).constData());
    unitFile.write(Utils::toBinary(unknown4Level()).constData());
    unitStream << "/"; unitStream.flush();

    unitFile.write(Utils::toBinary(experience()).constData());
    unitStream << "/"; unitStream.flush();

    unitStream << QString(autoChop()?"True":"False") << "/"
               << QString(gatherBerries()?"True":"False") << "/"
               << QString(huntChicken()?"True":"False") << "/"
               << QString(huntBoar()?"True":"False") << "/"
               << QString(showBowRange()?"True":"False") << "/";

    unitStream << QString(trainNearTarget()?"True":"False") << "/";

    unitStream << QString("%1").arg(rotation(),0,'g',8) << "/";
    unitStream.flush();

    unitFile.write(Utils::toBinary(equipHand()).constData());
    unitStream << "/"; unitStream.flush();
    unitFile.write(Utils::toBinary(equipOffhand()).constData());
    unitStream << "/"; unitStream.flush();
    unitFile.write(Utils::toBinary(equipHead()).constData());
    unitStream << "/"; unitStream.flush();
    unitFile.write(Utils::toBinary(equipBody()).constData());
    unitStream << "/"; unitStream.flush();
    unitFile.write(Utils::toBinary(equipFeet()).constData());
    unitStream << "/"; unitStream.flush();
    unitFile.write(Utils::toBinary(health()).constData());
    unitStream << "/"; unitStream.flush();

    // Dump some of the options in the file.
    for (unsigned int i = 0; i<52; i++) {
        unitStream << QString(option(i)?"True":"False") << "/";
    }
    unitStream << timeToEat() << "/"
               << morale() << "/"
               << fatigue() << "/"
               << hunger() << "/";

    // Dump more options in the file.
    for (unsigned int i = 52; i<52+12; i++) {
        unitStream << QString(option(i)?"True":"False") << "/";
    }

    // Inventory Preferences
    for (int i = 0; i<inventoryPreferences()->length(); i++) {
        unitStream << inventoryPreferences()->at(i) << "/";
    }

    // Inventory Items
    unitStream << inventoryItems()->length() << "/";
    for (int i = 0; i<inventoryItems()->length(); i++) {
        unitStream << inventoryItems()->at(i) << "/";
    }

    // Spare Inventory
    unitStream << spareInventory()->length() << "/";
    for (int i = 0; i<spareInventory()->length(); i++) {
        unitStream << spareInventory()->at(i) << "/";
    }

    // Patrol
    unitStream << patrolSetpoints()->length() << "/";
    for (int i = 0; i<patrolSetpoints()->length(); i++) {
        unitStream << patrolSetpoints()->at(i) << "/";
    }
    unitStream << patrolIndex() << "/";

    unitStream << guardedUnit() << "/";

    // Profession Experience
    for (int i = 0; i<professionEXP()->length(); i++) {
        unitStream << professionEXP()->at(i) << "/";
    }

    unitStream << maxWeight() << "/";

    unitStream << endl;
    unitStream.flush();

}
Exemple #17
0
void
DriverThread::enableHardware()
{
    while ( !isStopping() )
    {
        stringstream exceptionSS;
        try {
            segwayRmp_.enable();
            tracer_.info( "DriverThread: Enable succeeded." );
            stateMachine_.setOK();
            callback_.hardwareInitialised();
            return;
        }
        catch ( ... ) {
            string problem = hydroiceutil::catchExceptionsWithStatusAndSleep( "enabling", health(), gbxutilacfr::SubsystemFault, 2000 );

            stateMachine_.setFault( problem );
        }
    }
    cout<<"TRACE(driverthread.cpp): dropping out of enableHardware.  isStopping(): " << isStopping() << endl;
}
//****************************************对抽取的语料库按类别进行分类****************************************
void corpus_category(string filename_path, string path_read, string path_write) //参数1:文件名列表路径 参数2:读取文件的目录 参数3:写入文件的目录
{

	string file_name;    //存储读取的各个文件的名字
	ifstream read_filename(filename_path);  //从LIST.TXT读取文件名
	ofstream sports(path_write+"sports.txt");//属于sport类的存放在sport.txt文件中
	ofstream house(path_write+"house.txt");
	ofstream it(path_write+"it.txt");
	ofstream test_2008(path_write+"2008.txt");
	ofstream news(path_write+"news.txt");
	ofstream yule(path_write+"yule.txt");
	ofstream business(path_write+"business.txt");
	ofstream travel(path_write+"travel.txt");
	ofstream mil_news(path_write+"mil.news.txt");
	ofstream women(path_write+"women.txt");
	ofstream health(path_write+"health.txt");
	ofstream test_auto(path_write+"auto.txt");
	ofstream cul(path_write+"cul.txt");
	ofstream learning(path_write+"learning.txt");
	ofstream test_else(path_write+"else.txt");
	string path_in, str_line,cut_str;//path_in:存放读文件路径 str_line:读取的一行文件 cut_str:存放截取的字符串
	string::size_type pos1, pos2;
	int number = 0;
	while (getline(read_filename, file_name))
	{
		number++;
		cout << number << endl;
		path_in = path_read + file_name;
		ifstream infile(path_in);
		while (getline(infile, str_line))              //读取各个文件的每一行字符串
		{
			pos1 = 0;
			pos2 = str_line.find("####");
			cut_str = str_line.substr(pos1, pos2 - pos1);
			if (string(cut_str) == string("sports"))         //字符串匹配  是否为sports类
			{
				sports << str_line << endl;                  //如果是sports类就把该行输出到sports.txt文件
			}
			else if (cut_str == "house")
			{
				house << str_line << endl;
			}
			else if (cut_str == "it")
			{
				it << str_line << endl;
			}
			else if (cut_str == "2008")
			{
				test_2008 << str_line << endl;
			}
			else if (cut_str == "news")
			{
				news << str_line << endl;
			}
			else if (cut_str == "yule")
			{
				yule << str_line << endl;
			}
			else if (cut_str == "business")
			{
				business << str_line << endl;
			}
			else if (cut_str == "travel")
			{
				travel << str_line << endl;
			}
			else if (cut_str == "mil.news")
			{
				mil_news << str_line << endl;
			}
			else if (cut_str == "women")
			{
				women << str_line << endl;
			}
			else if (cut_str == "health")
			{
				health << str_line << endl;
			}
			else if (cut_str == "auto")
			{
				test_auto << str_line << endl;
			}
			else if (cut_str == "cul")
			{
				cul << str_line << endl;
			}
			else if (cut_str == "learning")
			{
				learning << str_line << endl;
			}
			else
			{
				test_else << str_line << endl;
			}
		}
		infile.close();   //每次结束都得关闭文件.
	}
}
void AbstractCombatItem::getDamage(int damage)
{
    PlayerLog::instance() << QString("got damage");
    setHealth(health() - damage);
}
Exemple #20
0
bool ITank::isDead() const { return armour() <= 0 || health() <= 0; }
#import "template_component.h"

TEST_CASE("unit_health_manager") {
  component_template thing_template;
  thing_template.health = 10;

  auto thing_a = std::make_shared<template_component>(thing_template);
  auto thing_b = std::make_shared<template_component>(thing_template);

  auto components = std::make_shared<component_set>();
  components->push_back(thing_a);
  components->push_back(thing_b);

  unit_health_manager unit_health_manager(components);

  REQUIRE(thing_a->health() == 10);
  REQUIRE(thing_b->health() == 10);
  REQUIRE(unit_health_manager.health() == 20);
  REQUIRE(unit_health_manager.alive());
  REQUIRE(!unit_health_manager.dead());
  REQUIRE(unit_health_manager.initial_health() == 20);

  SECTION("With all components set to 0 health") {
    thing_a->apply_damage(10);
    thing_b->apply_damage(10);
    REQUIRE(thing_a->health() == 0);
    REQUIRE(thing_b->health() == 0);
    REQUIRE(unit_health_manager.health() == 0);
    REQUIRE(!unit_health_manager.alive());
    REQUIRE(unit_health_manager.dead());
    REQUIRE(unit_health_manager.initial_health() == 20);
Exemple #22
0
void
MainThread::initialise()
{
    setMaxHeartbeatInterval( 10.0 );

    //
    // INITIAL CONFIGURATION
    //
    std::string prefix = context_.tag() + ".Config.";
    hydroutil::Properties prop = context_.toHydroContext(prefix).properties();

    //
    // Create hardware driver factory
    //
    std::string driverLibName = 
        prop.getPropertyWithDefault( "DriverLib", "libHydroSegwayRmpAcfrCan.so" );
    hydroDriverLib_.reset( new hydrodll::DynamicallyLoadedLibrary(driverLibName) );
    std::auto_ptr<hydrointerfaces::SegwayRmpFactory> driverFactory( 
        hydrodll::dynamicallyLoadClass<hydrointerfaces::SegwayRmpFactory,SegwayRmpDriverFactoryMakerFunc>
        ( *hydroDriverLib_, "createSegwayRmpDriverFactory" ) );

    //
    // Create powerbase managers
    //
    std::vector<std::string> powerbaseNames = 
        hydroutil::toStringSeq( prop.getPropertyWithDefault( "PowerbaseNames", "" ), ' ' );
    if ( powerbaseNames.size() == 0 )
        powerbaseNames.push_back( "Main" );

    for ( size_t i=0; i < powerbaseNames.size(); i++ )
    {
        std::string stripPrefix = prefix;
        if ( powerbaseNames.size() > 1 )
        {
            stripPrefix += powerbaseNames[i]+".";
        }
        std::auto_ptr<hydrointerfaces::SegwayRmp> hydroDriver( 
            driverFactory->createDriver( powerbaseNames[i], context_.toHydroContext(stripPrefix) ) );
        powerbaseManagers_.push_back( hydrormputil::PowerbaseManagerPtr( 
                                          new hydrormputil::PowerbaseManager( powerbaseNames[i],
                                                                             i,
                                                                             *this,
                                                                             hydroDriver,
                                                                             context_.toHydroContext(stripPrefix)) ) );
    }

    //
    // Read (user-configured) vehicle description
    //
    orca::VehicleDescription descr;
    orcaobjutil::readVehicleDescription( context_.properties(), context_.tag()+".Config.", descr );
    stringstream ss;
    ss<<"TRACE(component.cpp): Read vehicle description from configuration: " 
        << endl << orcaobj::toString(descr) << endl;
    context_.tracer().info( ss.str() );

    //
    // Check vehicle desciption sanity
    //
    orca::VehicleControlVelocityDifferentialDescription *controlDescr =
        dynamic_cast<orca::VehicleControlVelocityDifferentialDescription*>(&(*(descr.control)));
    if ( controlDescr == NULL )
        throw gbxutilacfr::Exception( ERROR_INFO, "Can only deal with differential drive vehicles." );
    if ( controlDescr->maxForwardSpeed != controlDescr->maxReverseSpeed ) 
        throw gbxutilacfr::Exception( ERROR_INFO, "Can't handle max forward speed != max reverse speed." );

    //
    // Set constraints
    //
    // convert the user-configured description into capabilities
    convert( *controlDescr, capabilities_ );
    // constrain based on hardware capabilities
    hydrointerfaces::constrain( capabilities_, powerbaseManagers_.back()->capabilities() );
    // convert back to orca format
    update( capabilities_, *controlDescr );

    //
    // Initialise the powerbase managers
    //
    hydrormputil::DriverThread::Config cfg;
    cfg.driveInReverse = (bool)prop.getPropertyAsIntWithDefault( "DriveInReverse", 0 );
    cfg.isMotionEnabled = (bool)prop.getPropertyAsIntWithDefault( "EnableMotion", 0 );
    cfg.maxForwardAcceleration = controlDescr->maxForwardAcceleration;
    cfg.maxReverseAcceleration = controlDescr->maxReverseAcceleration;
    std::string stallPrefix = "StallSensor.";
    cfg.stallSensorConfig.torqueThreshold = prop.getPropertyAsDoubleWithDefault( stallPrefix+"TorqueThreshold", 3.0 );
    cfg.stallSensorConfig.speedThreshold = prop.getPropertyAsDoubleWithDefault( stallPrefix+"speedThreshold", 0.5 );
    cfg.stallSensorConfig.timeThreshold = prop.getPropertyAsDoubleWithDefault( stallPrefix+"TimeThreshold", 0.5 );
    
    for ( size_t i=0; i < powerbaseManagers_.size(); i++ )
    {
        try {
            powerbaseManagers_[i]->init( cfg );
        }
        catch ( std::exception &e )
        {
            stringstream ss;
            ss << "Failed to init powerbase '"<<powerbaseManagers_[i]->name()<<": " << e.what();
            throw gbxutilacfr::Exception( ERROR_INFO, ss.str() );
        }
    }

    //
    // EXTERNAL PROVIDED INTERFACES
    //
    // Initialise external interfaces
    odometry2dI_ = new orcaifaceimpl::Odometry2dImpl( descr, "Odometry2d", context_ );
    odometry2dI_->initInterface( this, subsysName() );
    
    odometry3dI_ = new orcaifaceimpl::Odometry3dImpl( descr, "Odometry3d", context_ );
    odometry3dI_->initInterface( this, subsysName() );

    powerI_ = new orcaifaceimpl::PowerImpl( "Power", context_ );
    powerI_->initInterface( this, subsysName() );

    velocityControl2dI_ = new orcaifaceimpl::VelocityControl2dImpl( *this, descr, "VelocityControl2d", context_ );
    velocityControl2dI_->initInterface( this, subsysName() );

    // Set up the publisher
    publisherThread_ = new PublisherThread( prop.getPropertyAsDoubleWithDefault( "Odometry2dPublishInterval", 0.1 ),
                                            prop.getPropertyAsDoubleWithDefault( "Odometry3dPublishInterval", 0.1 ),
                                            prop.getPropertyAsDoubleWithDefault( "PowerPublishInterval", 20.0 ),
                                            odometry2dI_,
                                            odometry3dI_,
                                            powerI_,
                                            context_.tracer(),
                                            context_.status(),
                                            context_.history() );
    publisherThreadPtr_ = publisherThread_;
    publisherThread_->start();

    //
    // (optionally) required e-stop interface
    //
    const bool isEStopEnabled = (bool)prop.getPropertyAsIntWithDefault( "EnableEStopInterface", 0 );
    if ( isEStopEnabled )
    {
        while ( !isStopping() )
        {
            try {
                orca::EStopPrx eStopPrx;
                orcaice::connectToInterfaceWithTag( context_, eStopPrx, "EStop" );
                orca::EStopDescription descr = eStopPrx->getDescription();
                eStopMonitor_.reset( new orcaestoputil::EStopMonitor(descr) );

                eStopConsumerI_ = new orcaifaceimpl::NotifyingEStopConsumerImpl(context_);
                eStopConsumerI_->setNotifyHandler( this );
                eStopConsumerI_->subscribeWithTag( "EStop", this, subsysName() );

                break;
            }
            catch ( ... ) {
                orcaice::catchExceptionsWithStatusAndSleep( "connecting to e-stop", health() );
            }
        }
    }

    //
    // Finally, start the powerbase threads rolling
    //
    for ( size_t i=0; i < powerbaseManagers_.size(); i++ )
    {
        powerbaseManagers_[i]->startThread();
    }
}
Exemple #23
0
void Player::move(char c){
    
    //heal the player
    if(trueWithProbability(.1)){
        if( health() < max_health)
            setHealth(health()+1);
    }
    
    //check if the player is asleep
    if( asleep() < 1){
    
        
        switch (c) {
            case 'h':
                //if there is a monster above the player attack it
                if(checkForMonster("UP"))
                    attack(dungeon()->returnMonster(row(), col()-1));
                
                //if the next space is something the player can move onto(empty space or item) then move
                else if(dungeon()->gameGrid[row()][col()-1] == ' '|| dungeon()->gameGrid[row()][col()-1] == '>' || dungeon()->gameGrid[row()][col()-1] == '&')
                    setCol(col()-1);
                break;
                
            case 'l':
                //if there is a monster below the player attack it
                if(checkForMonster("DOWN"))
                    attack(dungeon()->returnMonster(row(), col()+1));
                
                else if(dungeon()->gameGrid[row()][col()+1] == ' ' || dungeon()->gameGrid[row()][col()+1] == '>'|| dungeon()->gameGrid[row()][col()-1] == '&')
                    setCol(col()+1);
                break;
                
            case 'k':
                //if there is a monster to the left of the player attack it
                if(checkForMonster("LEFT"))
                    attack(dungeon()->returnMonster(row()-1, col()));
                
                else if(dungeon()->gameGrid[row()-1][col()] == ' '|| dungeon()->gameGrid[row()-1][col()] == '>'|| dungeon()->gameGrid[row()][col()-1] == '&')
                    setRow(row()-1);
                break;
                
            case 'j':
                //if there is a monster to the right of the player attack it
                if(checkForMonster("RIGHT"))
                    attack(dungeon()->returnMonster(row()+1, col()));
                
                else if(dungeon()->gameGrid[row()+1][col()] == ' '|| dungeon()->gameGrid[row()+1][col()] == '>'|| dungeon()->gameGrid[row()][col()-1] == '&')
                    setRow(row() +1);
                break;
                
            default:
                break;
        
        }
    }
    else{
        //if the player is asleep then each move reduce his sleepTime by 1 point
        setSleep(asleep()-1);
        dungeon()->action_vector.push_back("Player is asleep");
    }
}
Exemple #24
0
void
DriverThread::operateHardware()
{
    // temp data structures.
    hydrointerfaces::SegwayRmp::Data data;
    hydrointerfaces::SegwayRmp::Command command(0,0);

    // monitor the speed set-point, don't allow it to change faster than the acceleration limits
    // (initialises to zero speed)
    SpeedSetPoint speedSetPoint( config_.maxForwardAcceleration,
                                 config_.maxReverseAcceleration );

    // initialise stall sensor
    StallSensor stallSensor( config_.stallSensorConfig );
    StallType stallType;

    // clear any pending commands
    commandStore_.set( command );

    gbxiceutilacfr::Timer newCommandTimer;

    //
    // The big loop (we exit immediately on detecting a fault)
    //
    while ( !isStopping() )
    {
        speedSetPoint.evaluateDt();

        if ( stateMachine_.isFault() )
        {
            // Can't operate in a fault condition.
            break;
        }

        //
        // Read from the hardware
        //

        try {
            segwayRmp_.read( data );
            if ( config_.driveInReverse ) reverseDirection( data );

            // Let the higher-ups know
            stallType = stallSensor.isStalled(data);
            callback_.receiveData( data, stallType );

            // Check for warnings/faults
            if ( data.hasFaults ||
                 (stallType != NoStall) )
            {
                stringstream ssFault;
                if ( data.hasFaults )
                {
                    ssFault << data.warnFaultReason << "\n";
                }
                if ( stallType != NoStall )
                {
                    ssFault << stallString( data, stallType );
                }
                health().fault( ssFault.str() );
                if ( data.hasFaults )
                {
                    stateMachine_.setFault( ssFault.str() );
                    break;
                }
            }
            else if ( data.hasWarnings )
            {
                stateMachine_.setWarning( data.warnFaultReason );
                health().warning( data.warnFaultReason );
            }
            else
            {
                stateMachine_.setOK();
                health().ok();
            }
        }
        catch ( ... ) {
            string problem = hydroiceutil::catchExceptionsWithStatus( "reading from hardware", health() );
            stateMachine_.setFault( problem );
            break;
        }

        //
        // Write pending commands to the hardware
        //

        // Have we got a new command?
        bool gotNewCommand = false;
        if ( commandStore_.isNewData() )
        {
            gotNewCommand = true;
            commandStore_.get( command );
            speedSetPoint.set( command.vx );
            newCommandTimer.restart();
        }

        // Are we still trying to hit our set-point?
        bool setPointAlreadyReached = false;
        command.vx = speedSetPoint.currentCmdSpeed( setPointAlreadyReached );

        // Write if we're supposed to
        if ( gotNewCommand || !setPointAlreadyReached )
        {
            if ( config_.driveInReverse ) reverseDirection( command );
            try {
                // Probably better not to have this (mutex-locking)
                // statement in the middle of this very tight loop...
                //
                //stringstream ss;
                //ss << "DriverThread::"<<__func__<<"(): writing command: " << command.toString();
                //tracer_.debug( ss.str(), 2 );

                segwayRmp_.write( command );
            }
            catch ( ... ) {
                string problem = hydroiceutil::catchExceptionsWithStatus( "writing to hardware", health() );
                stateMachine_.setFault( problem );
                break;
            }
        }

        // Check for timeouts in receiving commands
        if ( newCommandTimer.elapsedSec() > 0.2 )
        {
            if ( command.vx != 0 || command.w != 0 )
            {
                tracer_.info( "newCommandTimer timed out, resetting desired speed to zero" );
                command = hydrointerfaces::SegwayRmp::Command(0,0);
                commandStore_.set(command);
                newCommandTimer.restart();
            }
        }
    }

    std::string faultReason;
    if ( stateMachine_.isFault(faultReason) )
    {
        health().fault( faultReason );
        // pause in case of persistent fault
        sleep(1);
    }
}
Exemple #25
0
void
MainThread::initInterface()
{
    while ( !isStopping() )
    {
        try {
            buttonInterface_ = new orcaifaceimpl::ButtonImpl( "Button", context_ );
            buttonInterface_->setNotifyHandler( this );
            buttonInterface_->initInterface();
            context_.tracer().debug( "Activated button interface" );
            break;
        }
        catch ( ... ) {
            orcaice::catchExceptionsWithStatusAndSleep( "initialising Button interface", health() );
        }
    }
}
Exemple #26
0
	virtual void greet() const { std::cout << "I am an enemy! I have " << health() << " health!\n"; }
QVariant Human::data(int role) const
{
    switch(role) {
    case IdRole:
        return (unsigned int)id();
    case FilterStringRole:
        return filterString();

    case ProfessionRole:
        return profession();
    case PosXRole:
        return posX();
    case PosYRole:
        return posY();
    case PosZRole:
        return posZ();
    case NameRole:
        return name();

    case ArcherLevelRole:
        return archerLevel();
    case BlacksmithLevelRole:
        return blacksmithLevel();
    case BuilderLevelRole:
        return builderLevel();
    case CarpenterLevelRole:
        return carpenterLevel();
    case EngineerLeveRole:
        return engineerLevel();
    case FarmerLevelRole:
        return farmerLevel();
    case FishermanLevelRole:
        return fishermanLevel();
    case ForagerLevelRole:
        return foragerLevel();
    case InfantryLevelRole:
        return infantryLevel();
    case MinerLevelRole:
        return minerLevel();
    case StoneMasonLevelRole:
        return stoneMasonLevel();
    case WoodChopperLevelRole:
        return woodChopperLevel();
    case TailorLevelRole:
        return tailorLevel();
    case TraderLevelRole:
        return traderLevel();
    case HerderLevelRole:
        return herderLevel();
    case AdventurerLevelRole:
        return adventurerLevel();
    case Unknown1Role:
        return unknown1Level();
    case Unknown2Role:
        return unknown2Level();
    case Unknown3Role:
        return unknown3Level();
    case Unknown4Role:
        return unknown4Level();

    case ExperienceRole:
        return experience();

    case AutoChopTreesRole:
        return autoChop();
    case GatherBerriesRole:
        return gatherBerries();
    case HuntChickenRole:
        return huntChicken();
    case HuntBoarRole:
        return huntBoar();
    case ShowBowRangeRole:
        return showBowRange();
    case TrainNearTargetRole:
        return trainNearTarget();

    case RotationRole:
        return rotation();

    case EquipHandRole:
        return equipHand();
    case EquipOffhandRole:
        return equipOffhand();
    case EquipHeadRole:
        return equipHead();
    case EquipBodyRole:
        return equipBody();
    case EquipFeetRole:
        return equipFeet();

    case HealthRole:
        return health();

    case MoraleRole:
        return morale();
    case FatigueRole:
        return fatigue();
    case HungerRole:
        return hunger();

    default:
        return QVariant();
    }
}
Exemple #28
0
	void greet() { std::cout << "I am a flobb enemy! I have " << health() << " health!\n"; }
Exemple #29
0
 void Shield::update(const sf::Time& dt) {
     publish(ShieldMessage(position(), health()));
 }
Exemple #30
0
void
DriverThread::work()
{
    while ( !isStopping() )
    {
        try {
            setMaxHeartbeatInterval( 5.0 );
            enableHardware();

            setMaxHeartbeatInterval( 1.0 );
            operateHardware();
        }
        catch ( ... ) {
            string problem = hydroiceutil::catchExceptionsWithStatusAndSleep( "work loop", health(), gbxutilacfr::SubsystemFault, 1000 );

            stateMachine_.setFault( problem );
        }
    }
}