#include #include "visionary.h" using namespace std; static int signum(int i) { return ( i == 0 ? 0 : i/abs(i)); //return ( i == 0 ? 0 : i < 0 ? -1 : 0); } /* Return the offset that would take one step 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 (1, -1), i.e., one step diagonally to the upper right. */ static void step(const wabbit *w1, const wabbit *w2, int *dx, int *dy) { difference(w1, w2, dx, dy); *dx = signum(*dx); *dy = signum(*dy); } /* Return the distance between w1 and w2. For example, if w1 was at (10, 10) and w2 was at (13, 6), the return value would be 5 == sqrt(3*3 + 4*4). */ static double dist(const wabbit *w1, const wabbit *w2) { int dx,dy; //contain garbage, remedied on next line. difference(w1, w2, &dx, &dy); return sqrt(static_cast(dx*dx + dy*dy)); } void visionary::decide(int *dx, int *dy) const { //static const unsigned radius = 4; //of vision //Move one step away from a wabbit that could eat me. for (const_iterator it = begin(); it != end(); ++it) { const wabbit *const other = *it; if (other != static_cast(this) && dist(this, other) <= rad && other->hungry() > this->bitter()) { step(other, this, dx, dy); return; } } /* Arrive here if there were no enemies within the visual radius. Now see if there's any food I could eat within the visual radius. If so, take one step towards it. */ for (const_iterator it = begin(); it != end(); ++it) { const wabbit *const other = *it; if (other != static_cast(this) && dist(this, other) <= rad && this->hungry() > other->bitter()) { step(this, other, dx, dy); return; } } //Arrive here if there were neither enemies nor food nearby: //lethargic (or random, if you wish) in the absence of stimulation. // *dx = *dy = 0; *dx = rand() % 3 - 1; *dy = rand() % 3 - 1; }