void Experiment::timer_cb(const ros::TimerEvent& event) { switch(mode_) { case MODE_REP_START: actions_->Start(); last_time_ = ros::Time::now().toSec(); state_ = states_->GetState(); action_ = qobj_->GetAction(state_); actions_->Move(action_); ROS_INFO("Starting rep: %d", cnt_rep_); mode_ = MODE_REP; cnt_timesteps_++; break; case MODE_REP: state_p_ = (int)states_->GetState(); if (learn_) { reward_ = states_->GetReward(); qobj_->Update(reward_, state_, state_p_, action_); ROS_INFO("Action: %d, produced state: %d with reward: %f", action_, state_p_, reward_); ROS_INFO("Table: \n%s", qobj_->PrintTable().c_str()); } state_ = state_p_; action_ = qobj_->GetAction(state_); actions_->Move(action_); cnt_timesteps_++; if (getDistance() < goal_radius_ || outOfBounds()) { stopAndMoveToStart(); } break; case MODE_RETURN: if (move_stopped_ == true) { move_stopped_ = false; mode_ = MODE_REP_START; qobj_->DecreaseTemp(); cnt_rep_++; } if (cnt_rep_ > num_reps_) mode_ = MODE_DONE; break; case MODE_DONE: //lc_->ShowImage(); exit(1); break; } }
void Actor::terminateAllActions() { Actions childs; m_rootAction->getChilds(childs); for (Actions::iterator it= childs.begin(),end= childs.end(); it!=end; it++) { Action* action = *it; action->terminate(Action::CANCELED); } }
/// Sort actions by their expected likelihood /// WRITEME more documentation /// \todo Make bucket size a parameter /// \todo Don't hardcode children span frequencies void Parser::sort_actions(Actions& actions) const { /// Put all TOP inferences last (first?) Actions top_actions; vector<Actions> sort; /// \todo Make bucket size a parameter unsigned bucketsize = 1000; sort.resize(bucketsize); for (Actions::const_iterator a = actions.begin(); a != actions.end(); a++) { if (a->label() == Label_TOP()) { top_actions.push_back(*a); continue; } double sizefreq = 0; /// \todo Don't hardcode children span frequencies /// We exclude TOP from these frequencies, since it skews the number of unaries switch(a->children().size()) { case 1: sizefreq = 0.231926; break; case 2: sizefreq = 0.565159; break; case 3: sizefreq = 0.147423; break; case 4: sizefreq = 0.0422515; break; case 5: sizefreq = 0.00985868; break; case 6: sizefreq = 0.00269639; break; case 7: sizefreq = 0.000553723; break; case 8: sizefreq = 3.61124e-05; break; case 9: sizefreq = 6.01873e-05; break; case 10: sizefreq = 1.20375e-05; break; case 11: sizefreq = 2.40749e-05; break; default: sizefreq = 0; break; } sizefreq /= 0.565159; double labelfreq = label_frequency(a->label()) / max_label_frequency(); double freq = sizefreq * labelfreq; unsigned bucket = (unsigned)((bucketsize-1) * freq); assert(bucket >= 0 && bucket < bucketsize); sort.at(bucket).push_back(*a); } unsigned actionsize = actions.size(); actions.clear(); //for(vector<Actions>::const_reverse_iterator as = sort.rbegin(); for(vector<Actions>::reverse_iterator as = sort.rbegin(); as != sort.rend(); as++) { actions.insert(actions.end(), as->begin(), as->end()); } // Insert TOP inferences at the end of the list actions.insert(actions.end(), top_actions.begin(), top_actions.end()); assert(actions.size() == actionsize); }
void Actor::setActionToEffectors(Action* action, Action* parent) { GB_ASSERT(action,"Actor::setActionToEffectors: action must be defined"); EffectorIDVector actualNonAcquiredEffectors = action->getAcquiredEffectors(); const EffectorIDVector &requiredEffectors = action->getRequiredEffectors(); //set new action to effectors for (size_t i = 0; i<requiredEffectors.size(); i++) { Effector* effector = getEffector(requiredEffectors[i]); GB_ASSERT(effector, format("Actor::getEffector: actor doesn't have effector %s", \ Effector::convertToString(requiredEffectors[i]))); Actions parentChain; getResponsibleParent(requiredEffectors[i],parent,&parentChain); //insert parents int customPriority = action->getEffectorPriority(requiredEffectors[i]); //case of multiple responsible children if (parentChain.size()==1 && (parent->hasEffectorResponsibleChild(requiredEffectors[i]))) { parent->addResponsibleChildForEffector(requiredEffectors[i], action); } for (size_t j = parentChain.size()-1; j>0; j--) { //action notification about new added effectors can be placed here Action* actionToInsert = parentChain[j-1]; Action* parentAction = parentChain[j]; Action* responsibleChild = j>1 ? parentChain[j-2] : action; actionToInsert->addRequiredEffector(requiredEffectors[i],false,customPriority,responsibleChild); if (effector->insertAction(actionToInsert,parentAction)) { actionToInsert->addAcquiredEffector(requiredEffectors[i]); } } //insert action if (effector->insertAction(action,parent)) { //maybe this is only for debug EffectorIDVector::iterator it = std::find(actualNonAcquiredEffectors.begin(),actualNonAcquiredEffectors.end(), requiredEffectors[i]); GB_ASSERT(it!=actualNonAcquiredEffectors.end(),"Actor::setActionToEffectors: can't set action properly."); actualNonAcquiredEffectors.erase(it); } } GB_ASSERT(actualNonAcquiredEffectors.empty(),"Actor::setActionToEffectors: can't set action properly."); }
void addInfo(Effector* effector,Actions actions) { for(size_t i = 0; i < actions.size(); i++) { _addInfo(effector,actions[i]); } }
void sendNow(ActionItem *item) { mutex.wait(); actions.clear(); _send(item); mutex.post(); }
ActionItem *pop() { mutex.wait(); ActionItem *ret=actions.pop(); mutex.post(); return ret; }
void Experiment::stopAndMoveToStart(void) { double rand_ang, rand_orientation, start_x, start_y; double x = odom_msg_.pose.pose.position.x, y = odom_msg_.pose.pose.position.y; ROS_INFO("X: %f, Y: %f, B0: %f, B1: %f, B2: %f, B3: %f", x, y, bounds_[0], bounds_[1], bounds_[2], bounds_[3]); std_msgs::Float64 timeDiff; timeDiff.data = ros::Time::now().toSec() - last_time_; lc_pub_.publish(timeDiff); path_final_pub_.publish(path_msg_); mode_ = MODE_RETURN; ROS_INFO("Completed rep: %d, returning to start location", cnt_rep_); actions_->Stop(); //lc_->UpdateSteps(cnt_timesteps_); cnt_timesteps_ = 0; // Calculate next position rand_ang = 2.0 * M_PI * (rand() / ((double)RAND_MAX + 1)); rand_orientation = 2.0 * M_PI * (rand() / ((double)RAND_MAX + 1)); ROS_INFO("Rand_Ang: %f, Rand orient: %f", rand_ang, rand_orientation); start_x = goalx_ + start_radius_ * cos(rand_ang); start_y = goaly_ + start_radius_ * sin(rand_ang); // Send the next start position and wait for move_stopped flag geometry_msgs::Pose start_msg; start_msg.position.x = start_x; start_msg.position.y = start_y; start_msg.orientation = tf::createQuaternionMsgFromYaw(rand_orientation); move_pub_.publish(start_msg); }
void QtViewGui::contextMenu(const panda::types::Point& pos, panda::graphview::MenuTypes types, const Actions& customActions) { if (!types && customActions.empty()) return; QMenu menu(m_mainWindow); m_mainWindow->fillContextMenu(menu, types); for (const auto& action : customActions) { const auto& label = action.menuName; if (label.empty() && !menu.isEmpty()) menu.addSeparator(); if (!label.empty()) { auto actionPtr = menu.addAction(QString::fromStdString(label), action.callback); actionPtr->setParent(m_mainWindow); // So that the status tip can be shown on the status bar of the main window if (!action.statusTip.empty()) actionPtr->setStatusTip(QString::fromStdString(action.statusTip)); } } if (!menu.actions().empty()) menu.exec(m_viewWrapper.mapToGlobal(convert(pos))); }
bool Battle::AIApplySpell(const Spell & spell, const Unit* b, const HeroBase & hero, Actions & a) { u8 mass = Spell::NONE; switch(spell()) { case Spell::CURE: mass = Spell::MASSCURE; break; case Spell::HASTE: mass = Spell::MASSHASTE; break; case Spell::SLOW: mass = Spell::MASSSLOW; break; case Spell::BLESS: mass = Spell::MASSBLESS; break; case Spell::CURSE: mass = Spell::MASSCURSE; break; case Spell::DISPEL: mass = Spell::MASSDISPEL; break; case Spell::SHIELD: mass = Spell::MASSSHIELD; break; default: break; } if(mass != Spell::NONE && AIApplySpell(mass, b, hero, a)) return true; if(hero.CanCastSpell(spell) && (!b || b->AllowApplySpell(spell, &hero))) { a.push_back(Battle::Command(MSG_BATTLE_CAST, spell(), (b ? b->GetHeadIndex() : -1))); return true; } return false; }
bool Actor::checkEffectors(Action* action, Action* parentAction,EffectorIDVector &acquiredEffectors) { acquiredEffectors.clear(); bool principalAcquired = true; const Action::EffectorInfoMap &requiredEffectors = action->getRequiredEffectorInfos(); for (Action::EffectorInfoMap::const_iterator it = requiredEffectors.begin(),end = requiredEffectors.end(); it!=end; it++) { EffectorID effectorID = it->first; Effector* effector = getEffector(effectorID); GB_ASSERT(effector, format("Actor::getEffector: actor doesn't have effector %s", Effector::convertToString(effectorID))); bool principal = it->second.principal; //check if effector will be acquired by action when action is setting to parent bool isAcquired = false; Actions parentChain; Action* responsibleParent = getResponsibleParent(effectorID,parentAction,&parentChain); if (effector->isActive(responsibleParent)) { isAcquired = true; int customActionPriority = action->getEffectorPriority(effectorID); Action* currentAction = parentChain.size()>1 ? parentChain[parentChain.size()-2] : action; Action* settedAction = effector->getActiveChildAction(responsibleParent); //in our case, this can be done simpler, because comparing is based on action's priority //and doesn't depend on action(so action can be used instead of currentAction) if (!settedAction || compareActions(settedAction,currentAction,effectorID, settedAction->getEffectorPriority(effectorID),customActionPriority)) { isAcquired = true; acquiredEffectors.push_back(effectorID); } } if (principal && !isAcquired) { principalAcquired = false; } } return principalAcquired; }
/// Make all consistent parse decisions. /// \param state The state in which the parse decisions should be made. void Parser::make_all_consistent_decisions(ParseState& state) { Actions actions = state.consistent_actions(); assert(!actions.empty()); Debug::log(3) << "Performing " << actions.size() << " consistent decisions...\n"; Actions legal_actions = state.consistent_legal_actions(); Actions illegal_actions = state.consistent_illegal_actions(); assert(legal_actions.size() + illegal_actions.size() == actions.size()); // Output the confidences *before* actually performing any of the actions. // (Otherwise, the confidences values will be tainted.) for (vector<Action>::const_iterator a = legal_actions.begin(); a != legal_actions.end(); a++) Debug::log(3) << "\t" << a->to_string() << " (conf=" << this->confidence(state, *a) << ")\n"; for (vector<Action>::const_iterator a = illegal_actions.begin(); a != illegal_actions.end(); a++) Debug::log(3) << "\t" << a->to_string() << " (ILLEGAL)\n"; for (vector<Action>::iterator a = actions.begin(); a != actions.end(); a++) { Debug::log(4) << "Actually performing " << a->to_string() << "\n"; // TRACE; cerr << state.to_string() << "\n"; // TRACE; cerr << a->to_string() << "\n"; bool b = state.perform(*a); assert(b); // Debug::log(4) << this->m_items.to_string() << "\n"; // Debug::log(9) << this->to_string() << "\n"; } Debug::log(3) << "...done performing " << actions.size() << " consistent decisions.\n"; }
void Actor::releaseActionEffectors(Action* action,const EffectorIDVector& effectorIDs) { for (size_t i=0;i<effectorIDs.size();i++) { Effector* effector = getEffector(effectorIDs[i]); GB_ASSERT(effector, format("Actor::getEffector: actor doesn't have effector %s", Effector::convertToString(effectorIDs[i]))); Actions children; effector->getDirectChildren(action, children); GB_ASSERT(children.empty(), "Actor::releaseActionEffectors: action isn't allowed to have children on effector at this moment"); Actions becameActive; effector->removeAction(action,becameActive); for(size_t j=0; j<becameActive.size(); j++) { m_activatedEffectors[becameActive[j]].push_back(effectorIDs[i]); } } }
int Database::saveSession(Sessions session) { int decoderId = this->userExist(session.getDecoder()); if(decoderId == 0){ decoderId = this->insertUser(Users(session.getDecoder())); if(decoderId <= 0) return -1; this->cacheUserId.insert(session.getDecoder().toString(),decoderId); } int observerId = this->userExist(session.getObserver()); if(observerId == 0){ observerId = this->insertUser(Users(session.getObserver())); if(observerId <= 0) return -2; this->cacheUserId.insert(session.getObserver().toString(),observerId); } int specieId = this->specieExist(session.getSpecies()); if (specieId == 0){ specieId = this->insertSpecie(Species(session.getSpecies())); if (specieId <= 0) return -2; } int subjectId = this->subjectExist(session.getSubject()); if (subjectId == 0){ Subjects s; s.setName(session.getSubject()); subjectId = this->insertSubject(s); if (subjectId <= 0) return -2; } int sessionId = this->insertSession(decoderId, session.getDateDecoding(), observerId, subjectId, specieId, session.getDateSession(), session.getDescription()); if(sessionId <= 0) return -3; QList<Actions> sequence = session.getActions(); for(int s=0; s < sequence.size(); s++){ Actions action = sequence.at(s); int stateId = this->stateExist(action.getStateDescription()); if(stateId == 0){ stateId = this->insertState(States(action.getStateDescription())); if(stateId <= 0) return -4; this->cacheStateId.insert(action.getStateDescription(),stateId); } int eventId = this->eventExist(action.getEventDescription()); if(eventId == 0){ eventId = this->insertEvent(Events(action.getEventDescription())); if(eventId <= 0) return -5; this->cacheEventId.insert(action.getEventDescription(),eventId); } if(this->insertAction(action.getTimeAction(), sessionId, stateId, eventId) <= 0) return -6; } // qDebug() << this->query.lastQuery(); // qDebug() << this->query.lastError(); // qDebug() << sessionId; return sessionId; }
void Actor::print(Effector* effector,Action* action,std::ostringstream& buff,std::string& tabs,bool full) { static const char* spaces = "----"; std::ostringstream actionBuff; if (action!=m_rootAction) { tabs += spaces; buff<<tabs; action->print(actionBuff); std::string actionStr = actionBuff.str(); size_t pos = 0; while ((pos = actionStr.find("\n",pos))!=std::string::npos) { pos += 1; if (pos==actionStr.size()) break; actionStr.insert(pos,tabs); pos += tabs.size(); } buff<<actionStr; } Actions childs; if (full) { effector->getDirectChildren(action,childs); for (size_t i=0; i<childs.size();i++) { print(effector,childs[i],buff,tabs,full); } } else { Action* child = effector->getActiveChildAction(action); if (child) print(effector,child,buff,tabs,full); } if (action!=m_rootAction) tabs.erase(tabs.size()-sizeof(spaces),sizeof(spaces)); }
Actions::Actions(const Actions &actions) { if(actions.getAttack() == nullptr) { attack = nullptr; } else { attack = actions.getAttack()->clone(); } if(actions.getSkill() == nullptr) { skill = nullptr; } else { skill = actions.getSkill()->clone(); } }
/// Make some consistent parse decision. /// Randomly choose some consistent action, and perform it. /// \param state The state in which the parse decision should be made. /// \todo Allow classifier to confidence-rate actions, and choose highest rated /// action to perform? void Parser::make_consistent_decision(ParseState& state) { assert(!parameter::treebank_has_parse_paths()); Actions actions = state.consistent_actions(); assert(!actions.empty()); if (parameter::parse_left_to_right() || parameter::parse_right_to_left()) { assert(actions.size() == 1); } // Randomly choose some consistent action. Action action = actions.at(ParsePathRandom.get(actions.size())); //Action action = this->best_action(state, actions); Debug::log(5) << "Performing: " << action.to_string() << "\n"; state.perform(action); // FIXME: Don't necessarily use _parse_span_chart. _parse_span_chart.subtract(SpanItem(action), _parse_prc, _parse_rcl, _parse_cbs); }
/// Make some consistent parse decision using the Classifier and an oracle. /// If the Classifier makes a correct decision, then we make that. /// Otherwise, we use an oracle to randomly choose /// a consistent decision to perform. void Parser::make_decision_with_oracle(ParseState& state) { Actions actions = state.legal_actions(); assert(!actions.empty()); Action action = this->best_action(state, actions).first; if(state.is_consistent(action)) { Debug::log(5) << "Correctly performing: " << action.to_string() << "\n"; stats::correct_actions_add(1); } else { Debug::log(5) << "Instead of " << action.to_string() << ", "; actions = state.consistent_actions(); assert(!actions.empty()); if (parameter::parse_left_to_right() || parameter::parse_right_to_left()) { assert(actions.size() == 1); } // Randomly choose some consistent action. action = actions.at((unsigned)(drand48() * actions.size())); Debug::log(5) << "oracle chose " << action.to_string() << "\n"; } bool ret = state.perform(action, true); assert(ret); stats::total_actions_add(1); // FIXME: Don't necessarily use _parse_span_chart. _parse_span_chart.subtract(SpanItem(action), _parse_prc, _parse_rcl, _parse_cbs); Debug::warning(__FILE__, __LINE__, this->current_scores()); }
void Experiment::timer_cb(const ros::TimerEvent& event) { switch(mode_) { case MODE_REP_START: state_ = (int)states_->GetState(); ROS_INFO("Starting rep: %d", cnt_rep_); mode_ = MODE_REP; break; case MODE_REP: action_ = qobj_->GetAction(state_); actions_->Move((Actions::moveType)action_); state_p_ = (int)states_->GetState(); ROS_INFO("Action: %d, produced state: %d", action_, state_p_); if (learn_) { reward_ = states_->GetReward(); qobj_->Update(reward_, state_, state_p_, action_); ROS_INFO("Action: %d, produced state: %d with reward: %f", action_, state_p_, reward_); ROS_INFO("Table: \n%s", qobj_->PrintTable().c_str()); } state_ = state_p_; if (states_->GetDistance() < radius_) { mode_ = MODE_RETURN; ROS_INFO("Completed rep: %d, returning to start location", cnt_rep_); // Move to starting spot srv_.request.pose.position.x = start_x_; srv_.request.pose.position.y = start_y_; client_.call(srv_); } break; case MODE_RETURN: if (move_stopped_ == true) { move_stopped_ = false; mode_ = MODE_REP_START; cnt_rep_++; } if (cnt_rep_ > num_reps_) mode_ = MODE_DONE; break; case MODE_DONE: break; } }
void Actor::releaseAction(Action* action) { //GB_INFO("ReleaseAction begin: %s (%p)",action->getDescString().c_str(), action); static std::string tabs; //GB_INFO("%sReleaseAction: %s (%p)",tabs.c_str(), action->getDescString().c_str(), action); tabs.append(" "); GB_ASSERT(m_actionsToDelete.find(action) == m_actionsToDelete.end(), "Action has already been deleted. Action logic is corrupted!"); m_actionsToDelete.insert(action); //terminate childs Actions childs; action->getChilds(childs); for (Actions::iterator it=childs.begin(), end=childs.end(); it!=end; it++) { Action* child = *it; child->terminate(Action::CANCELED); } //remove from effectors const EffectorIDVector& effectorIDs = action->getRequiredEffectors(); for (size_t i=0;i<effectorIDs.size();i++) { Effector* effector = getEffector(effectorIDs[i]); GB_ASSERT(effector, format("Actor::getEffector: actor doesn't have effector %s", Effector::convertToString(effectorIDs[i]))); Actions becameActive; effector->removeAction(action,becameActive); for(size_t j=0; j<becameActive.size(); j++) { m_activatedEffectors[becameActive[j]].push_back(effectorIDs[i]); } } tabs.erase(tabs.size()-4,4); //GB_INFO("ReleaseAction end: %s",action->getDescString().c_str()); }
/// Make some parse decision. /// We find all possible actions at the current parse state. /// We choose some action, and perform it. /// \param state The state in which the parse decision should be made. /// \param output_threshold If the absolute value of the /// confidence of the chosen decision is at least output_threshold, /// then we will output the pre- and post-decision states to /// Debug::log(3). /// \return True iff the action performed is already in the parse /// chart. This can be used to detect the first inconsistent /// decision, but no subsequent inconsistencies. bool Parser::make_decision(ParseState& state, double output_threshold) { Actions actions = state.legal_actions(); assert(!actions.empty()); pair<Action, double> p = this->best_action(state, actions); Action action = p.first; double conf= p.second; bool debugout = false; if (fabs(conf) >= output_threshold) debugout = true; if (debugout) Debug::log(3) << "PRE (conf=" << conf << "): " << state.to_string() << "\n"; else Debug::log(5) << "Performing: " << action.to_string() << "\n"; bool ret = state.perform(action, true); if (debugout) Debug::log(3) << "POST (conf=" << conf << ", ret=" << ret << "): " << state.to_string() << "\n"; // FIXME: Don't necessarily use _parse_span_chart. _parse_span_chart.subtract(SpanItem(action), _parse_prc, _parse_rcl, _parse_cbs); return ret; }
/// Return the action with highest confidence. /// \note This can only score legal actions. [TODO: Check for action legality] /// \todo Tiebreak in favor of more common label? /// \return A pair containing the highest confidence action, and its confidence. pair<Action, double> Parser::best_action(const ParseState& state, Actions& actions) const { unsigned tiecount = 1; // DISABLED FOR NOW assert(parameter::minconf_for_greedy_decision() > 100); //this->sort_actions(actions); pair<Action, double> best; best.second = -BIGVAL; Actions::const_iterator a; for (a = actions.begin(); a != actions.end(); a++) { // Debug::log(5) << "Considering action " << a->to_string() << "...\n"; double conf = this->confidence(state, *a); if (conf > -10) Debug::log(5) << "Action " << a->to_string() << " has conf = " << conf << "\n"; if (best.first.label() == NO_LABEL || conf > best.second) { best = make_pair(*a, conf); tiecount = 1; } else if (fabs(conf - best.second) < parameter::small_epsilon()) { tiecount++; if (drand48() < 1. / tiecount) { best = make_pair(*a, conf); } } if (conf > parameter::minconf_for_greedy_decision()) { assert(*a == best.first); assert(conf == best.second); Debug::log(3) << "Greedily choosing action " << best.first.to_string() << " with conf = " << best.second << " > mingreedyconf " << parameter::minconf_for_greedy_decision() << "\n"; break; } } Debug::log(3) << "Best action " << best.first.to_string() << " with conf = " << best.second << "\n"; return best; }
void UnitAttackAbility::DetermineAvailableActions( const Unit* unit, const Path& movementPath, Actions& result ) const { // Get the UnitType of the Unit. UnitType* unitType = unit->GetUnitType(); if( unitType->HasWeapons() ) { // If this Unit has weapons, determine whether the Unit can wait in the destination square. Map* map = unit->GetMap(); Map::Iterator destinationTile = map->GetTile( movementPath.GetDestination() ); if( unit->CanOccupyTile( destinationTile ) ) { // If the Unit can stop here, get the list of Units in attack range from this location. Map::Units unitsInRange; map->FindUnitsInRange( destinationTile.GetPosition(), unitType->GetAttackRange(), unitsInRange ); for( auto it = unitsInRange.begin(); it != unitsInRange.end(); ++it ) { Unit* target = *it; if( unit->CanAttack( target ) ) { // Add an attack action to the list of actions. UnitAttackAbility::Action* attackAction = new UnitAttackAbility::Action(); attackAction->UnitID = unit->GetID(); attackAction->TargetID = target->GetID(); attackAction->MovementPath = movementPath; result.push_back( attackAction ); } } } } }
/// Make some consistent parse decision using the Classifier. /// Choose the highest confidence legal consistent action. /// Only is no legal consistent action exists do /// we choose an illegal (consistent) action. /// \param state The state in which the parse decision should be made. void Parser::make_consistent_decision_with_classifier(ParseState& state) { assert(!parameter::treebank_has_parse_paths()); Actions actions = state.consistent_legal_actions(); Action action; // If some consistent legal action exists, if (!actions.empty()) { action = this->best_action(state, actions).first; Debug::log(5) << "Performing: " << action.to_string() << "\n"; bool debugout = false; double conf = this->confidence(state, action); if (conf <= -5) debugout = true; //if (conf <= -10) debugout = true; if (debugout) Debug::log(3) << "PRE (conf=" << conf << "): " << state.to_string() << "\n"; bool ret = state.perform(action, true); assert(ret); if (debugout) Debug::log(3) << "POST (conf=" << conf << "): " << state.to_string() << "\n"; } else { actions = state.consistent_illegal_actions(); assert(!actions.empty()); if (parameter::parse_left_to_right() || parameter::parse_right_to_left()) { assert(actions.size() == 1); } // Randomly choose some consistent (illegal) action. action = actions.at((unsigned)(drand48() * actions.size())); Debug::log(3) << "Performing illegal action: " << action.to_string() << "\n"; bool ret = state.perform(action); assert(ret); } // FIXME: Don't necessarily use _parse_span_chart. _parse_span_chart.subtract(SpanItem(action), _parse_prc, _parse_rcl, _parse_cbs); }
void queue(ActionItem *item) { mutex.wait(); actions.push_back(item); mutex.post(); }
void EditorContext::DoActions(Actions& actions) { for (int i=0; i<actions.size(); ++i) { actions[i](); } actions.clear(); }
void AI::BattleTurn(Arena & arena, const Unit & b, Actions & a) { Board* board = Arena::GetBoard(); // reset quality param for board board->Reset(); // set quality for enemy troop board->SetEnemyQuality(b); const Unit* enemy = NULL; bool attack = false; if(b.isArchers() && !b.isHandFighting()) { enemy = arena.GetEnemyMaxQuality(b.GetColor()); if(BattleMagicTurn(arena, b, a, enemy)) return; /* repeat turn: correct spell ability */ attack = true; } else if(b.isHandFighting()) { enemy = AIGetEnemyAbroadMaxQuality(b); if(BattleMagicTurn(arena, b, a, enemy)) return; /* repeat turn: correct spell ability */ attack = true; } else { s16 move = -1; if(b.Modes(SP_BERSERKER)) { const Indexes positions = board->GetNearestTroopIndexes(b.GetHeadIndex(), NULL); if(positions.size()) move = *Rand::Get(positions); } else { if(BattleMagicTurn(arena, b, a, NULL)) return; /* repeat turn: correct spell ability */ // set quality position from enemy board->SetPositionQuality(b); // get passable quality positions const Indexes positions = board->GetPassableQualityPositions(b); attack = true; if(positions.size()) move = AIAttackPosition(arena, b, positions); } if(Board::isValidIndex(move)) { if(b.isFly()) { enemy = AIGetEnemyAbroadMaxQuality(move, b.GetColor()); if(BattleMagicTurn(arena, b, a, enemy)) return; /* repeat turn: correct spell ability */ a.push_back(Battle::Command(MSG_BATTLE_MOVE, b.GetUID(), move)); attack = true; } else { Position dst = Position::GetCorrect(b, move); Indexes path = arena.GetPath(b, dst); if(path.empty()) { const u8 direction = b.GetPosition().GetHead()->GetPos().x > dst.GetHead()->GetPos().x ? RIGHT : LEFT; // find near position while(path.empty() && Board::isValidDirection(dst.GetHead()->GetIndex(), direction)) { const s16 & pos = Board::GetIndexDirection(dst.GetHead()->GetIndex(), direction); if(b.GetHeadIndex() == pos) break; dst.Set(pos, b.isWide(), direction == RIGHT); path = arena.GetPath(b, dst); } } if(path.size()) { if(b.isWide()) { const s16 & head = dst.GetHead()->GetIndex(); const s16 & tail = dst.GetTail()->GetIndex(); if(path.back() == head || path.back() == tail) { enemy = AIGetEnemyAbroadMaxQuality(head, b.GetColor()); if(!enemy) enemy = AIGetEnemyAbroadMaxQuality(tail, b.GetColor()); } } if(! enemy) enemy = AIGetEnemyAbroadMaxQuality(path.back(), b.GetColor()); a.push_back(Battle::Command(MSG_BATTLE_MOVE, b.GetUID(), path.back())); // archers move and short attack only attack = b.isArchers() ? false : true; } } } else enemy = AIGetEnemyAbroadMaxQuality(b); } if(enemy) { if(attack) a.push_back(Battle::Command(MSG_BATTLE_ATTACK, b.GetUID(), enemy->GetUID(), enemy->GetHeadIndex(), 0)); } else { DEBUG(DBG_BATTLE, DBG_TRACE, "enemy: " << "is NULL" << ", board: " << board->AllUnitsInfo()); } // end action a.push_back(Battle::Command(MSG_BATTLE_END_TURN, b.GetUID())); }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window *window; window = SDL_CreateWindow("SDLwindow", 600, 300, MainWindowWidth, MainWindowHigh, SDL_WINDOW_SHOWN); SDL_Renderer* renderer = NULL; renderer = SDL_CreateRenderer( window, 0, SDL_RENDER_TARGETS_RESET); SDL_SetRenderDrawColor(renderer,255,255,255,255); SDL_RenderClear( renderer ); SDL_SetRenderDrawColor(renderer,0,0,0,0); SDL_RenderDrawLine(renderer,MainWindowWidth/12,MainWindowHigh-30,MainWindowWidth/12,MainWindowHigh-70); SDL_RenderDrawLine(renderer,MainWindowWidth/12,MainWindowHigh-30,MainWindowWidth/12-10,MainWindowHigh-50); SDL_RenderDrawLine(renderer,MainWindowWidth/12,MainWindowHigh-30,MainWindowWidth/12+10,MainWindowHigh-50); SDL_RenderDrawLine(renderer,MainWindowWidth/12*11,MainWindowHigh-30,MainWindowWidth/12*11,MainWindowHigh-70); SDL_RenderDrawLine(renderer,MainWindowWidth/12*11,MainWindowHigh-70,MainWindowWidth/12*11-10,MainWindowHigh-50); SDL_RenderDrawLine(renderer,MainWindowWidth/12*11,MainWindowHigh-70,MainWindowWidth/12*11+10,MainWindowHigh-50); Road road; road.Draw(renderer); Car object; object.SetX(MainWindowWidth/5*3); object.SetY(MainWindowHigh/5*3); object.SetAngle(0); object.Draw(renderer); Actions actions; SDL_Event event; int rl=0,rp=0; while (1) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { if (SDL_GetScancodeFromKey(event.key.keysym.sym)==SDL_SCANCODE_LEFT) { if (((object.GetX()>=MainWindowWidth/2-10)&&(object.GetDirection()==true))|| ((object.GetX()<=MainWindowWidth/2+10)&&(object.GetDirection()==false))) { bool AChecked=false; if ((object.GetX()<MainWindowWidth/2+10)&&(object.GetX()>MainWindowWidth/2-10)) { actions.ScanA(object,road); AChecked=true; } if (rp==1) { rl=0; rp=0; } if (rl==0) { object.RotateLeft(); rl++; } object.Rotate90(renderer); road.Draw(renderer); if (!AChecked) actions.ScanA(object,road); actions.ScanBC(object,road); actions.ActionOutput(); } } if (SDL_GetScancodeFromKey(event.key.keysym.sym)==SDL_SCANCODE_RIGHT) { if (((object.GetX()>=MainWindowWidth/2-10)&&(object.GetDirection()==false))|| ((object.GetX()<=MainWindowWidth/2+10)&&(object.GetDirection()==true))) { bool AChecked=false; if ((object.GetX()<MainWindowWidth/2+10)&&(object.GetX()>MainWindowWidth/2-10)) { actions.ScanA(object,road); AChecked=true; } actions.ScanA(object,road); if (rl==1) { rl=0; rp=0; } if (rp==0) { object.RotateRight(); rp++; } object.Rotate90(renderer); road.Draw(renderer); if (!AChecked) actions.ScanA(object,road); actions.ScanBC(object,road); actions.ActionOutput(); } } if (SDL_GetScancodeFromKey(event.key.keysym.sym)==SDL_SCANCODE_UP) { if ((object.GetX()<MainWindowWidth/2-10)||(object.GetX()>MainWindowWidth/2+10)) { road.Draw(renderer); road.Move(object.GetDirection()); Sleep(50); } } if (SDL_GetScancodeFromKey(event.key.keysym.sym)==SDL_SCANCODE_ESCAPE) return 0; } break; case SDL_QUIT: exit(0); } } } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int main ( int argc, const char * argv[] ) { Actions action; //create Action (to fill up with parameters below...) // ============================================================================================ // ============================================================================================ // ============================================================================================ try { // on try for all //clean parameters (this is not elegant but might avoid some macPPC-side bus error bugs whatsoever action.outfile=""; action.switch_safe=false; action.switch_smart=false; action.switch_scan=false; action.switch_nocheck=false; action.switch_compact=false; action.mediafile=""; action.actiontype=Actions::NONE; action.xmpsnippet=""; //////////////////////////////////////////// // parameter verification if ( argc == 1 ) { //aka no parameters, just command itself. XMPQE::PrintUsageShort(EXENAME); return 0; } else if ( argc == 2 ) //single-paramter-call? { if ( !strcmp("help",argv[1]) || //only "help" and "version" permitted, ... !strcmp("-help",argv[1]) || !strcmp("--help",argv[1]) || !strcmp("-h",argv[1]) || !strcmp("-?",argv[1]) || !strcmp("/?",argv[1]) ) { XMPQE::PrintUsageLong(EXENAME); return 0; } else if ( !strcmp("-version",argv[1]) || !strcmp("version",argv[1]) ) { action.actiontype=Actions::VERSION; } else { //..thus fail anything else Log::error("unknown parameter %s",argv[1]); } } else //multi-argument parameters { int i=1; // "for (int i=1;i<argc;i++)" .... while (true) { if (argv[i][0] != '-') { break; //apparently done parsing switches } if ( !strcmp("-safe",argv[i])) { action.switch_safe=true; } else if ( !strcmp("-smart",argv[i])) { action.switch_smart=true; } else if ( !strcmp("-nocheck",argv[i])) { action.switch_nocheck=true; } else if ( !strcmp("-compact",argv[i])) { action.switch_compact=true; } else if ( !strcmp("-scan",argv[i])) { action.switch_scan=true; } else if ( !strcmp("-out",argv[i])) { i++; //ok, so gimme that file if (i>=argc) Log::error("missing output parameter, etc."); action.outfile=argv[i]; } else Log::error("unknown switch %s",argv[i]); i++; if (i>=argc) Log::error("missing action parameter, etc."); } //check mutually exclusive if (action.switch_scan && action.switch_smart) Log::error("use either -smart or -scan"); if ( !strcmp("info",argv[i])) { action.actiontype= Actions::INFO; } else if ( !strcmp("put",argv[i]) || !strcmp("inject",argv[i]) ) { action.actiontype= Actions::PUT; } else if ( !strcmp("get",argv[i]) || !strcmp("extract",argv[i]) ) { action.actiontype= Actions::GET; } else if ( !strcmp("dump",argv[i])) { action.actiontype= Actions::DUMP; } else Log::error("_unknown action %s",argv[i]); i++; //only inject needs an in-file parameter really... if ( action.actiontype== Actions::PUT) { if (i>=argc) Log::error("missing <xmpfile> parameter"); action.xmpsnippet=argv[i]; i++; } //last argument must be mediafile if (i>=argc) Log::error("missing mediafile parameter"); action.mediafile=argv[i]; i++; if (i!=argc) Log::error("too many parameters."); } //Init =========================================================================== InitDependencies(); //Do Action ////////////////// Log log(action.outfile.c_str()); //will start logging to file (if filename given) or not ("") action.doAction(); // Shutdown ///////////////////////////////////////////// ShutdownDependencies(); } catch (XMP_Error& e ) { Log::info("Unexpected XMP_Error %s\n", e.GetErrMsg()); //throw no further, no Log::error.. ! return -2; } catch (LOG_Exception& q) { Log::info("LOG_Exception:%s\n",q.what()); return -3; } catch (std::runtime_error& p) { Log::info("caught std::runtime_error exception: %s\n",p.what()); return -4; } catch (...) { Log::info("unidentified error on action execution\n"); return -5; } // ============================================================================================ // ============================================================================================ // ============================================================================================ if (Log::noErrorsOrWarnings) return 0; //else Log::info("%s finished with warnings",EXENAME); return 10; }
bool AI::BattleMagicTurn(Arena & arena, const Unit & b, Actions & a, const Unit* enemy) { const HeroBase* hero = b.GetCommander(); if(b.Modes(SP_BERSERKER) || !hero || hero->Modes(Heroes::SPELLCASTED) || !hero->HaveSpellBook() || arena.isDisableCastSpell(Spell(), NULL) || a.HaveCommand(Battle::MSG_BATTLE_CAST)) return false; const Force & my_army = arena.GetForce(b.GetArmyColor(), false); const Force & enemy_army = arena.GetForce(b.GetArmyColor(), true); Units friends(my_army, true); Units enemies(enemy_army, true); // sort strongest friends.SortStrongest(); // troop bad spell - clean { // sort strongest Units::iterator it = std::find_if(friends.begin(), friends.end(), std::bind2nd(std::mem_fun(&Unit::Modes), IS_BAD_MAGIC)); if(it != friends.end()) { if(AIApplySpell(Spell::DISPEL, *it, *hero, a)) return true; if(AIApplySpell(Spell::CURE, *it, *hero, a)) return true; } } // area damage spell { const u8 areasp[] = { Spell::METEORSHOWER, Spell::FIREBLAST, Spell::CHAINLIGHTNING, Spell::FIREBALL, Spell::COLDRING }; s16 dst = AIAreaSpellDst(*hero); if(Board::isValidIndex(dst)) for(u8 ii = 0; ii < ARRAY_COUNT(areasp); ++ii) { if(hero->CanCastSpell(areasp[ii])) { a.push_back(Battle::Command(MSG_BATTLE_CAST, areasp[ii], dst)); return true; } } } // if handfighting if(enemy) { // kill dragons if(enemy->isDragons() && !b.Modes(SP_DRAGONSLAYER) && AIApplySpell(Spell::DRAGONSLAYER, &b, *hero, a)) return true; // curse if(!enemy->Modes(SP_CURSE) && AIApplySpell(Spell::CURSE, enemy, *hero, a)) return true; // enemy good spell - clean if(enemy->Modes(IS_GOOD_MAGIC) && AIApplySpell(Spell::DISPEL, enemy, *hero, a)) return true; // up defense if(!b.Modes(SP_STEELSKIN) && !b.Modes(SP_STONESKIN) && AIApplySpell(Spell::STEELSKIN, &b, *hero, a)) return true; if(!b.Modes(SP_STONESKIN) && !b.Modes(SP_STEELSKIN) && AIApplySpell(Spell::STONESKIN, &b, *hero, a)) return true; } // my army blessing if(b.isArchers()) { if(!b.Modes(SP_BLESS) && AIApplySpell(Spell::BLESS, &b, *hero, a)) return true; if(!b.Modes(SP_BLOODLUST) && AIApplySpell(Spell::BLOODLUST, &b, *hero, a)) return true; } // up speed if(hero->HaveSpell(Spell::HASTE) && !enemy) { // sort strongest Units::iterator it = std::find_if(friends.begin(), friends.end(), std::not1(std::bind2nd(std::mem_fun(&Unit::Modes), SP_HASTE))); if(it != friends.end() && AIApplySpell(Spell::HASTE, *it, *hero, a)) return true; } // shield spell conditions { Units::iterator it = std::find_if(enemies.begin(), enemies.end(), std::mem_fun(&Unit::isArchers)); const Castle* castle = Arena::GetCastle(); // find enemy archers if(it != enemies.end() || // or archers tower (castle && castle->GetColor() != b.GetColor() && castle->isCastle())) { // find strongest archers for(it = friends.begin(); it != friends.end(); ++it) if((*it)->isArchers() && ! (*it)->Modes(SP_SHIELD)) break; // or other strongest friends if(it == friends.end()) it = std::find_if(friends.begin(), friends.end(), std::not1(std::bind2nd(std::mem_fun(&Unit::Modes), SP_SHIELD))); if(it != friends.end() && AIApplySpell(Spell::SHIELD, *it, *hero, a)) return true; } } // enemy army spell { // find mirror image or summon elem Units::iterator it = std::find_if(enemies.begin(), enemies.end(), std::bind2nd(std::mem_fun(&Unit::Modes), CAP_MIRRORIMAGE | CAP_SUMMONELEM)); if(it != enemies.end()) { if(AIApplySpell(Spell::ARROW, *it, *hero, a)) return true; if(AIApplySpell(Spell::LIGHTNINGBOLT, *it, *hero, a)) return true; } // find good magic it = std::find_if(enemies.begin(), enemies.end(), std::bind2nd(std::mem_fun(&Unit::Modes), IS_GOOD_MAGIC)); if(it != enemies.end()) { // slow if((*it)->Modes(SP_HASTE) && AIApplySpell(Spell::SLOW, *it, *hero, a)) return true; // curse if((*it)->Modes(SP_CURSE) && AIApplySpell(Spell::CURSE, *it, *hero, a)) return true; // if(AIApplySpell(Spell::DISPEL, *it, *hero, a)) return true; } // check undead if(std::count_if(friends.begin(), friends.end(), std::mem_fun(&Unit::isUndead)) < std::count_if(enemies.begin(), enemies.end(), std::mem_fun(&Unit::isUndead))) { if(AIApplySpell(Spell::HOLYSHOUT, NULL, *hero, a)) return true; if(AIApplySpell(Spell::HOLYWORD, NULL, *hero, a)) return true; } // check alife if(std::count_if(friends.begin(), friends.end(), std::mem_fun(&Unit::isAlive)) < std::count_if(enemies.begin(), enemies.end(), std::mem_fun(&Unit::isAlive))) { if(AIApplySpell(Spell::DEATHRIPPLE, NULL, *hero, a)) return true; if(AIApplySpell(Spell::DEATHWAVE, NULL, *hero, a)) return true; } Unit* stats = *Rand::Get(enemies); if(AIApplySpell(Spell::LIGHTNINGBOLT, stats, *hero, a)) return true; if(AIApplySpell(Spell::ARROW, stats, *hero, a)) return true; } /* FIX: Damage Spell: */ if(AIApplySpell(Spell::ARMAGEDDON, NULL, *hero, a)) return true; if(AIApplySpell(Spell::ELEMENTALSTORM, NULL, *hero, a)) return true; return false; }