]> ruin.nu Git - popboot.git/blob - planner.cpp
only execute an action when all preconditions are are true
[popboot.git] / planner.cpp
1 #include "planner.h"
2 #include "node.h"
3 #include <iostream>
4 using namespace std;
5 using namespace __gnu_cxx;
6
7 Planner::Planner(std::vector<Action> actions, literals init, literals goal){
8
9         _start = new Node(Action("start",literals(), init));
10         addNode(_start);
11         Node* finish = new Node(Action("finish",goal,literals()));
12
13         for(vector<Action>::iterator action = actions.begin(); action != actions.end(); ++action){
14                 literals effects = action->effects();
15                 for (literals::iterator effect = effects.begin(); effect != effects.end(); ++effect){
16                         cerr << "Adding effect: " << *effect << endl;
17                         _actions[*effect] = *action;
18                 }
19         }
20         makePlan(finish);
21 }
22
23
24 void Planner::makePlan(Node* node){
25         literals preconds = node->action().preconditions();
26
27         if (preconds.size() == 0){
28                 cerr << "Found no preconds" << endl;
29                 _start->addChild(node);
30         }else{
31                 for (literals::iterator precond = preconds.begin(); precond != preconds.end(); ++precond){
32                         cerr << "Looking for: " << *precond << endl;
33                         hash_map<string,Node*>::iterator addedNode = _addedNodes.find(*precond);
34                         if(addedNode != _addedNodes.end()){
35                                 cerr << "Using already added node" << endl;
36                                 addedNode->second->addChild(node);
37                         }else {
38                                 hash_map<string, Action>::iterator action = _actions.find(*precond);
39                                 if (action != _actions.end()){
40                                         cerr << "Adding new node" << endl;
41                                         Node* newnode = new Node(action->second);
42                                         newnode->addChild(node);
43                                         addNode(newnode);
44                                         makePlan(newnode);
45                                 }else{
46                                         cerr << "Action with effect: " << *precond << " not found!" << endl;
47                                 }
48                         }
49                 }
50         }
51 }
52
53 void Planner::addNode(Node* node){
54         literals effects = node->action().effects();
55
56         for (literals::iterator effect = effects.begin(); effect != effects.end(); ++effect){
57                 cout << "Adding node for effect: " << *effect << endl;
58                 _addedNodes[*effect] = node;
59         }
60 }
61
62
63 void Planner::execute(){
64         _start->execute(literals());
65 }