#include #include //for rand and exit functions #include "rabbit.h" //const char rabbit::c = 'r'; //not needed if line 8 of rabbit.h has = 'r' rabbit::rabbit(game *initial_g, unsigned initial_x, unsigned initial_y) : g(initial_g), x(initial_x), y(initial_y) { if (c == g->term.background()) { cerr << "Rabbit 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 << "rabbit 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 rabbit.\n"; exit(EXIT_FAILURE); } } g->term.put(x, y, c); g->master.push_back(this); } rabbit::~rabbit() { g->term.beep(); g->master.remove(this); g->term.put(x, y); } //If this rabbit blundered into the wolf and got eaten, return false. //Otherwise, return true. bool rabbit::move() { //The values of dx and dy are either 1, 0, or -1. const int dx = rand() % 3 - 1; const int dy = rand() % 3 - 1; if (dx == 0 && dy == 0) { return true; //This rabbit had no desire to move. } const unsigned newx = x + dx; const unsigned newy = y + dy; if (!g->term.in_range(newx, newy)) { return true; //Can't move off the screen. } const char newc = g->term.get(newx, newy); if (newc != g->term.background()) { //Return true if this rabbit bumped into another rabbit. //Return false if it blundered into the wolf and was eaten. return newc == c; } g->term.put(x, y); //Erase the rabbit from its old location. x = newx; y = newy; g->term.put(x, y, c); //Redraw this rabbit at its new location. return true; }