// Implementation of the Position class and Direction-related functions. // CSE143 Spring '01 // Homework 6 #include "position.h" #include // Returns true iff the direction is valid (one of the enum values) bool validDir(Direction dir) { return (dir == North || dir == East || dir == South || dir == West); } // Returns the opposite direction, i.e. North for South, East for West, etc. Direction oppositeDir(Direction dir) { assert (validDir(dir)); switch (dir) { case North: return South; case East: return West; case South: return North; case West: return East; } return North; // for compiler's benefit: never get here. } // Returns the next direction clockwise (e.g. nextDir(North) = East). Direction nextDir(Direction dir) { assert (validDir(dir)); switch (dir) { case North: return East; case East: return South; case South: return West; case West: return North; } return North; // for compiler's benefit: never get here. } // Initialize the position at (0,0) Position::Position() { x = 0; y = 0; } // Initialize the position to (x,y) Position::Position(int x, int y) { this->x = x; this->y = y; } // Initialize the position to same as the other position Position::Position(const Position& other) { x = other.x; y = other.y; } // Set the position to be the same as the other position Position& Position::operator =(const Position& other) { x = other.x; y = other.y; return *this; } // = x coordinate of this position int Position::getX() const { return x; } // = y coordinate of this position int Position::getY() const { return y; } // Move the position units in direction , where North // is up the screen (bigger y's) and East is right on the screen (bigger // x's). void Position::move(Direction dir, int distance) { assert (validDir(dir)); switch(dir) { case North: y += distance; break; case East: x += distance; break; case South: y -= distance; break; case West: x -= distance; break; } } // Rotate this position around , according to : rotate 90, 180, // or 270 degrees clockwise, for = East, South or West, respectively. // If = North, ignore. Returns the new position. void Position::rotate(Position axis, Direction dir) { assert (validDir(dir)); int dx = x - axis.x; int dy = y - axis.y; int temp; for (Direction cur = North; cur != dir; cur = nextDir(cur)) { temp = -dx; dx = dy; dy = temp; } x = axis.x + dx; y = axis.y + dy; }