#include #include //for exit function #include "wolf.h" #include "rabbit.h" //for lines 66-68 using namespace std; //const char wolf::c = 'W'; //not needed if line 8 of wolf.h has = 'W' wolf::wolf(const game *initial_g, unsigned initial_x, unsigned initial_y) : g(initial_g), x(initial_x), y(initial_y) { if (c == g->term.background()) { cerr << "Wolf character '" << c << "' can't be the same as " "the terminal's background character.\n"; exit(EXIT_FAILURE); } if (!g->term.in_range(x, y)) { cerr << "wolf out of range: (" << x << ", " << y << ")\n"; exit(EXIT_FAILURE); } while (g->term.get(x, y) != g->term.background()) { g->term.next(x, y); if (!g->term.in_range(x, y)) { cerr << "No free space for wolf.\n"; exit(EXIT_FAILURE); } } g->term.put(x, y, c); } wolf::~wolf() { g->term.beep(); g->term.put(x, y); } void 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 }; static const size_t n = sizeof a / sizeof a[0]; if (const char k = g->term.key()) { for (const keystroke *p = a; p < a + n; ++p) { if (k == p->c) { const unsigned newx = x + p->dx; const unsigned newy = y + p->dy; if (!g->term.in_range(newx, newy)) { break; //Go to line 80. } if (rabbit *const other = g->get(newx, newy)) { delete other; } g->term.put(x, y); //Erase this wolf from its old location. x = newx; y = newy; g->term.put(x, y, c); //Redraw this wolf at its new location. return; } } //Punish user who pressed illegal key or tried to move off screen. g->term.beep(); } }