Last active
March 4, 2016 11:15
-
-
Save psqq/45d2702c21649ee40735 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
struct Event { | |
Event(int akey, int ach) : key(akey), ch(ach) {} | |
int key, ch; | |
bool operator==(const Event &other) const { | |
return key == other.key || ch == other.ch; | |
} | |
}; | |
template <class T> | |
class Command2 { | |
public: | |
virtual ~Command2() {} | |
virtual void execute(T&) = 0; | |
}; | |
struct Player { | |
int x; | |
} player; | |
class NullCommand : public Command2<Player> { | |
public: | |
virtual void execute(Player &p) { | |
cout << "NullCommand" << endl; | |
} | |
}; | |
class MoveLeftCommand : public Command2<Player> { | |
public: | |
virtual void execute(Player &p) { | |
cout << "MoveLeftCommand" << endl; | |
p.x -= 1; | |
} | |
}; | |
class EventTable { | |
private: | |
vector<pair<Event, Command2<Player>*>> table; | |
NullCommand nullCommand; | |
public: | |
void setCommand (Event e, Command2<Player> &cmd) { | |
for (auto &p : table) { | |
if (p.first == e) { | |
p.second = &cmd; | |
return; | |
} | |
} | |
table.push_back(make_pair(e, &cmd)); | |
} | |
Command2<Player>* getCommand(Event e) { | |
for (auto &p : table) { | |
if (p.first == e) return p.second; | |
} | |
return &nullCommand; | |
} | |
}; | |
int main() { | |
EventTable hashInputTable; | |
hashInputTable.getCommand(Event(1, 1))->execute(player); | |
MoveLeftCommand moveLeftCommand; | |
hashInputTable.setCommand(Event(1, 1), moveLeftCommand); | |
hashInputTable.getCommand(Event(1, 1))->execute(player); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment