#include #include "CPstring.h" #include "observer.h" #include "walk.h" // constants define the size of the observing window // and the size of the rectangle that shows a walker // MAX_Y = range in Y direction: [-MAX_Y .. MAX_Y] // e.g., [-100..100] for MAX_Y = 100 // MAX_X = range in X direction // // RECT_HEIGHT = height of rectangle that represents walker // graphically // RECT_WIDTH = width of rectangle for walker // const int MAX_Y = 100; const int MAX_X = 100; const int RECT_HEIGHT = 20; const int REC_WIDTH = 20; // DRAW_WIDTH = width used by samba to draw (done in terms of RECT_WIDTH) // DRAW_HEIGHT = height used by samba to draw (done in terms of RECT_HEIGHT) const double DRAW_WIDTH = REC_WIDTH; const double DRAW_HEIGHT = 3.0 * RECT_HEIGHT / 4.0; // table of colors (can have more values for more colors) // also set number of colors = MAX_COLORS const char * colorTable[] = {"red","orange", "yellow", "green", "cyan","blue", "black", "brown" }; const int MAX_COLORS = sizeof colorTable / sizeof colorTable[0]; WalkObserver::WalkObserver(ostream & OutputStream, int maxWalkers) : myOutputStream(OutputStream) // postcondition: all fields initizlied { InitializeStream(maxWalkers); // set up animation } void WalkObserver::Update(RandomWalk & walker) // postcondition: animation/observation is updated for walker { int id; int x; int y; id = walker.GetID(); // the walker's id # x = walker.GetPosition(); // the walker's X-coordinate y = GetYFromID(id); // the walker's Y-coordinate MoveRectangle(id, x, y); // animator command } void WalkObserver::InitializeStream(int maxWalkers) // postcondition: myOutputStream initialized for animation { int k; myOutputStream.precision(1); // show one decimal point for myOutputStream.setf(ios::fixed); // all numbers myOutputStream.setf(ios::showpoint); // initialize coordinates in samba myOutputStream << "coords " << -MAX_X << " " << -MAX_Y << " " << MAX_X << " " << MAX_Y << endl; // draw a shape (rectangle) for each walker for (k = 0 ; k < maxWalkers; k++) { double xStart = 0.0; // x-coordinate, bottom left double yStart = GetYFromID(k); // y-coordinate, bottom left DrawRectangle(k, xStart, yStart); } } void WalkObserver::DrawRectangle(int id, double x, double y) // postcondition: rectangle drawn (using Samba) { myOutputStream << "rectangle RECT" << id << " " << x << " " << y << " " << DRAW_WIDTH << " " << DRAW_HEIGHT << " " << GetColorFromID(id) << " solid" << endl; } void WalkObserver::MoveRectangle (int id, double x, double y) // postcondition: rectangle for a particular walker is moved { myOutputStream << "move RECT" << id << " " << x << " " << y << endl; } string WalkObserver::GetColorFromID (int ColorID) // postcondition: returns a string that represents a color // for drawing in Samba { return colorTable[ColorID % MAX_COLORS]; } int WalkObserver::GetYFromID(int id) // postcondition: returns a y-coordinate for walker with id { return (-MAX_Y + id * RECT_HEIGHT); }