#include #include #include "except.h" #include "wabbit.h" using namespace std; /* Delete any other wabbit that got eaten during the move (line 32), but do not delete this wabbit. If this wabbit was eaten during the move, return false (line 36); otherwise return true. */ wabbit::wabbit(game *initial_g, unsigned initial_x, unsigned initial_y, char initial_c) : g(initial_g), x(initial_x), y(initial_y), c(initial_c) { if (!g->term.in_range(x, y)) { ostringstream os; os << "Initial wabbit position (" << x << ", " << y << ") off " << g->term.xmax() << " by " << g->term.ymax() << " terminal.\n"; throw except(os); } const char other = g->term.get(x, y); const char background = g->term.background(); if (other != background) { ostringstream os; os << "Initial wabbit position (" << x << ", " << y << ") already occupied by '" << other << "'.\n"; throw except(os); } if (c == background) { ostringstream os; os << "Wabbit character '" << c << "' can't be the same as " "the terminal's background character.\n"; throw except(os); } g->term.put(x, y, c); g->master.push_back(this); } wabbit::~wabbit() { g->master.remove(this); g->term.put(x, y); } bool wabbit::move() { int dx; //uninitialized variables int dy; decide(&dx, &dy); if (dx == 0 && dy == 0) { return true; } const unsigned newx = static_cast(x) + dx; const unsigned newy = static_cast(y) + dy; if (!g->term.in_range(newx, newy)) { punish(); return true; } if (wabbit *const other = g->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) { other->beep(); other->g->term.wait(1000); delete other; } if (he_ate_me) { beep(); g->term.wait(1000); return false; } if (!I_ate_him) { //I bumped into a wabbit that I could neither eat nor be //eaten by. punish(); return true; } } g->term.put(x, y); //Erase this wabbit from its old location. x = newx; y = newy; g->term.put(x, y, c); //Redraw this wabbit at its new location. return true; }