#include #include #include "except.h" #include "game.h" #include "boulder.h" #include "rabbit.h" #include "sitting_duck.h" #include "wolf.h" using namespace std; game::game(char initial_c) : term(initial_c) { static const size_t xmax = 36; //number of columns in the picture static const char a[][xmax + 1] = { //plus 1 for terminating '\0' "....................................", "....................................", "......bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "......b............................b", "......b.....r..............s.......b", "......b............................b", "......b............................b", "......b.....r......................b", "......b..............W.............b", "......b............................b", "......bbbbbbbbbbbbbb.bbbbbbbbbbbbbbb" }; static const size_t ymax = sizeof a / sizeof a[0]; try { for (size_t y = 0; y < ymax; ++y) { for (size_t x = 0; x < xmax; ++x) { if (term.in_range(x, y)) { switch (a[y][x]) { //sorry y before x case '.': break; case 'b': new boulder(this, x, y); break; case 'r': new rabbit(this, x, y); break; case 's': new sitting_duck(this, x, y); break; case 'W': new wolf(this, x, y); break; default: ostringstream os; os << "bad character '" << a[y][x] << "' at (" << x << ", " << y << ")\n"; throw except(os); } } } } } catch (...) { depopulate(); throw; } } void game::depopulate() { for (master_t::const_iterator it = master.begin(); it != master.end();){ const wabbit *const p = *it; ++it; delete p; } } game::master_t::value_type game::get(unsigned x, unsigned y) const { for (master_t::const_iterator it = master.begin(); it != master.end(); ++it) { const master_t::value_type p = *it; if (p->x == x && p->y == y) { return p; } } return 0; } game::master_t::size_type game::count(char c) const { master_t::size_type n = 0; for (master_t::const_iterator it = master.begin(); it != master.end(); ++it) { if ((*it)->c == c) { ++n; } } return n; } void game::play() { for (;; term.wait(250)) { for (master_t::const_iterator it = master.begin(); it != master.end();) { wabbit *const p = *it; const bool alive = p->move(); ++it; if (!alive) { //The wabbit that just moved blundered into //another wabbit and was eaten. delete p; } if (count('s') == 0 && count('r') == 0) { term.put(0, 0, "You killed all the " "sitting ducks and rabbits."); //Give user three seconds to read the message. term.wait(3000); return; } } } }