#include #include //for exit function #include "wabbit.h" 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)) { cerr << "Initial object position (" << x << ", " << y << ") off " << g->term.xmax() << " by " << g->term.ymax() << " terminal.\n"; exit(EXIT_FAILURE); } const char other = g->term.get(x, y); const char background = g->term.background(); if (other != background) { cerr << "Initial object position (" << x << ", " << y << ") already occupied by '" << other << "'.\n"; exit(EXIT_FAILURE); } if (c == background) { cerr << "Object's character '" << c << "' can't be the same as " "the terminal's background character.\n"; exit(EXIT_FAILURE); } g->term.put(x, y, c); g->master.push_back(this); } wabbit::~wabbit() { //g->term.beep(); //g->term.wait(150); g->master.remove(this); g->term.put(x,y); } /* Return the offset that would move us from the location of w1 to the location of w2. For example, if w1 was at (10, 10) and w2 was at (13, 6), the return value would be (3, -4), i.e., 3 units to the right and 4 units up. */ void difference(const wabbit *w1, const wabbit *w2, int *dx, int *dy) { if (w1->g != w2->g) { cerr << "difference method called on two wabbits " << "that don't belong to the same game!\n"; exit(EXIT_FAILURE); } *dx = static_cast(w2->x) - static_cast(w1->x); *dy = static_cast(w2->y) - static_cast(w1->y); } /* Delete any other wabbit that got eaten during the move, but do not delete this wabbit. If this wabbit was eaten during the move, return false; otherwise return true. */ bool wabbit::move(int* value, char* collisionObj) { *value = 0; //default *collisionObj = '\0'; //default int dx; //uninitialized variables int dy; decide(&dx, &dy); if (dx==0 && dy==0) { //maskable objects must be immobile if (maskable() && g->term.get(x,y) == g->term.background()) //other wabbit moved away { //Redraw this wabbit since it may have been masked g->term.put(x, y, c); } 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; } unsigned i = 0; while (wabbit *const other = g->get(newx, newy, &i)) { *collisionObj = other->id(); const bool I_ate_him = this->hungry() > other->bitter(); const bool he_ate_me = other->hungry() > this->bitter(); if (I_ate_him) { *value = other->value(); other->beep(); //other->g->term.wait(100); delete other; } if (he_ate_me) { *value = other->value(); beep(); //g->term.wait(100); return false; //not allowed to delete myself } if (!I_ate_him && !(other->maskable())) { //I hit a wabbit that I could neither eat nor be eaten by nor mask. 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; }