Skip to content

Instantly share code, notes, and snippets.

@shrddr
Last active November 23, 2020 09:25
Show Gist options
  • Save shrddr/69d7332586e37bc7abd9 to your computer and use it in GitHub Desktop.
Save shrddr/69d7332586e37bc7abd9 to your computer and use it in GitHub Desktop.
component architecture
/* In this model, the actor owns a bunch of components, which in turn
serves as the base class for the component interfaces. Whenever a
system needs access to a component, it asks the actor for that interface
and gets a pointer to the appropriate interface object. */
struct Component
{
};
struct AiComponent: public Component
{
};
struct HumanAiComponent: public AiComponent
{
};
struct DrawComponent: public Component
{
};
struct Actor
{
~Actor()
{
for (auto c : components) delete component;
}
std::map<std::string, Component*> components;
};
struct ActorFactory
{
Actor* create(const char* fileName)
{
std::ifstream f(fileName);
std::string line;
Actor* pActor = new Actor;
while (std::getline(f, line))
{
if (line == "human_ai")
pActor.components["ai"] = new HumanAiComponent;
if (line == "zombie_ai")
pActor.components["ai"] = new HumanAiComponent;
if (line == "draw")
pActor.components["draw"] = new DrawComponent;
}
return pActor;
}
};
struct System
{
void think(Actor a)
{
AiComponent* ac = a.components["ai"];
if (ac) ac->think(a);
}
void draw(Actor a)
{
DrawComponent* dc = a.components["draw"];
if (dc) dc->draw(a);
}
}
int main()
{
ActorFactory af;
std::list<Actor*> actors;
actors.push_back(af.create("human.txt"));
actors.push_back(af.create("zombie.txt"));
System s;
for (auto actor : actors)
{
s.think(actor);
s.draw(actor);
}
for (auto actor : actors) delete actor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment