#include #include #include #include using std::string; using std::vector; using std::cout; using std::cin; using std::endl; class IAgent { public: virtual ~IAgent() {} virtual int position() const = 0; virtual void update() = 0; virtual char displayChar() const = 0; }; class AbstractAgent : public IAgent { public: AbstractAgent(int p) { pos = p; } ~AbstractAgent() {} int position() const override { return pos; } void update() override {} protected: int pos; }; class Snake : public AbstractAgent { public: Snake(int p, int d, int mx) : AbstractAgent{p} { dir = d; max = mx; } void update() override { pos += dir; if (pos == 0 || pos == max) dir *= -1; } char displayChar() const override { return '~'; } protected: int dir; int max; }; class Plant : public AbstractAgent { public: Plant(int p, int gr, const string& c) : AbstractAgent{p}, lifecycle{c} { age = 0; growthRate = gr; } void update() override { age++; } char displayChar() const override; protected: virtual bool alive() const { return true; } int age; int growthRate; string lifecycle; }; class Annual : public Plant { public: Annual(int p, int gr, int ls, const string& c) : Plant(p, gr, c) { lifeSpan = ls; } void foo(); protected: bool alive() const override { return age < lifeSpan; } int lifeSpan; }; char Plant::displayChar() const { if (alive()) { size_t stage = age / growthRate; if (stage >= lifecycle.length()) { stage = lifecycle.length() - 1; } return lifecycle[stage]; } else { return '_'; } } class Animal { public: Animal(int l, int m) { age = 0; loc = l; worldSize = m; } virtual ~Animal() {} int location() const { return loc; } virtual void exist() { age++; } virtual char draw() = 0; protected: int age; int loc; int worldSize; }; class Bird : public Animal { public: using Animal::Animal; char draw() override { return age < 10 ? 'o' : 'v'; } void exist() override; protected: int dir; }; class AnimalAdapter : public IAgent { public: AnimalAdapter(Animal *a) { animal = a; } virtual ~AnimalAdapter() override { delete animal; } int position() const override { return animal->location(); } virtual void update() override { animal->exist(); } virtual char displayChar() const override { return animal->draw(); }; protected: Animal *animal; }; void Bird::exist() { Animal::exist(); if (age == 10) { dir = 1; } else if (age > 15) { if (loc + dir >= worldSize || loc + dir < 0) { dir *= -1; } loc += dir; } } int main(int argc, char **argv) { vector< IAgent * > world{}; world.push_back(new Snake{4, 1, 10}); world.push_back(new Plant{1, 10, ".|TY"}); world.push_back(new Annual{6, 3, 15, ".oO@"}); world.push_back(new AnimalAdapter{new Bird{8, 10}}); while (cin) { string output; for (IAgent *a : world) { size_t p = a->position(); while (output.length() < p + 1) { output += ' '; } output[p] = a->displayChar(); a->update(); } cout << output << endl; string dummy; std::getline(cin, dummy); } for (IAgent *a : world) { delete a; } }