#include #include //for the exit function #include "wabbit.h" using namespace std; //Definition of static data member. list wabbit::master; wabbit::wabbit(const terminal& init_t, unsigned init_x, unsigned init_y, char init_c): t {&init_t}, x {init_x}, y {init_y}, c {init_c} { if (!t->in_range(x, y)) { cerr << "Initial wabbit position (" << x << ", " << y << ") off " << t->xmax() << " by " << t->ymax() << " terminal.\n"; exit(EXIT_FAILURE); } const char other {t->get(x, y)}; const char background {t->background()}; if (other != background) { cerr << "Initial wabbit position (" << x << ", " << y << ") already occupied by '" << other << "'.\n"; exit(EXIT_FAILURE); } if (c == background) { cerr << "wabbit character '" << c << "' can't be the same as " "the terminal's background character.\n"; exit(EXIT_FAILURE); } t->put(x, y, c); master.push_back(this); } wabbit::~wabbit() { master.remove(this); t->beep(); t->wait(1000); //Dying wabbit stands frozen in the headlights. if (t->get(x, y) == c) { //If no other animal is here, t->put(x, y); //draw the terminal's background character. } } bool wabbit::move() { int dx {0}; int dy {0}; decide(&dx, &dy); //Put new values into dx and dy. if (dx == 0 && dy == 0) { return true; //This wabbit decided not to move. } const unsigned newx {x + dx}; const unsigned newy {y + dy}; if (!t->in_range(newx, newy)) { punish(); return true; } if (wabbit *const other {wabbit::get(newx, newy)}) { const bool I_ate_him { this->hungry() > other->bitter()}; const bool he_ate_me {other->hungry() > this->bitter()}; if (I_ate_him) { //Call the other's destructor, //which removes the other from the master list. delete other; } if (he_ate_me) { return false; //not allowed to delete myself } if (!I_ate_him) { //I bumped into a wabbit that I could neither eat nor be //eaten by. punish(); return true; } } t->put(x, y); //Erase this wabbit from its old location. x = newx; y = newy; t->put(x, y, c); //Redraw this wabbit at its new location. return true; } //Return a pointer to the wabbit at the specified coordinates. wabbit *wabbit::get(unsigned x, unsigned y) { for (auto& p: master) { if (p->x == x && p->y == y) { return p; } } return nullptr; //No such wabbit. }