#include #include // for the exit function #include "wolf.h" using namespace std; wolf::wolf(const terminal& init_t, unsigned init_x, unsigned init_y): t {&init_t}, x {init_x}, y {init_y}, c {'W'} { if (!t->in_range(x, y)) { cerr << "Initial wolf 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 wolf position (" << x << ", " << y << ") already occupied by '" << other << "'.\n"; exit(EXIT_FAILURE); } if (c == background) { cerr << "Wolf character '" << c << "' can't be the same as " << "the terminal's background character.\n"; exit(EXIT_FAILURE); } t->put(x, y, c); } // Return false if this wolf ate another animal, true otherwise. bool wolf::move() { struct keystroke { char c; int dx; // horizontal motion int dy; // vertical motion }; static const keystroke a[] = { {'h', -1, 0}, // left {'j', 0, 1}, // down {'k', 0, -1}, // up {'l', 1, 0} // right }; if (const char k {t->key()}) { // If a key was pressed, for (const auto& stroke : a) { if (k == stroke.c) { const unsigned newx {x + stroke.dx}; const unsigned newy {y + stroke.dy}; if (!t->in_range(newx, newy)) { break; // Can't move off the screen. } const bool I_ate_him {t->get(newx, newy) != t->background()}; t->put(x, y); // Erase wolf from its old location x = newx; y = newy; t->put(x, y, c); // Redraw wolf at new location. return !I_ate_him; } } // Arrive here to punish user who pressed an illegal key // or tried to move off the screen. t->beep(); } return true; // Keep the game going if wolf didn't move. }