#include #include //for rand and exit functions #include "rabbit.h" using namespace std; rabbit::rabbit(const terminal& init_t, unsigned init_x, unsigned init_y) : t {&init_t}, x {init_x}, y {init_y}, c {'r'} { if (!t->in_range(x, y)) { cerr << "Initial rabbit 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 rabbit position (" << x << ", " << y << ") already occupied by '" << other << "'.\n"; exit(EXIT_FAILURE); } if (c == background) { cerr << "Rabbit character '" << c << "' can't be the same as " << "the terminal's background character.\n"; exit(EXIT_FAILURE); } t->put(x, y, c); } rabbit::~rabbit() { t->beep(); // Beep the terminal t->wait(1000); // Pause for one second if (t->get(x, y) == c) { t->put(x, y); // Erase the rabbit } cout << "Rabbit has died." << endl; } bool rabbit::move() { const int dx {rand() % 3 - 1}; const int dy {rand() % 3 - 1}; if (dx == 0 && dy == 0) { return true; // This rabbit decided not to move. } const unsigned newx {x + dx}; const unsigned newy {y + dy}; if (!t->in_range(newx, newy)) { return true; // Can't move off the screen. } const char other {t->get(newx, newy)}; if (other != t->background()) { if (other == c) { return true; // Rabbit collided with another rabbit. } else { return false; // Rabbit was eaten. } } t->put(x, y); // Erase this rabbit from its old location. x = newx; y = newy; t->put(x, y, c); // Redraw this rabbit at its new location. return true; }