// OOP EXample: Robots is a visual robot that moves forward facing // the directions dictated by its theta. When it runs into a wall // it turns right class Robot { // Attributes float x, y; // location float sz; // size float theta; // direction.orientation float speed = 1;
// Constructor(s) Robot (float s) { float[] dir = {0, 90, 180, 270}; theta = dir[int(random(4))]; sz = s; x = random(2*sz, width-2*sz); y = random(2*sz, height-2*sz);
} // Robot()
void display() { // Display the robot push(); translate(x, y); rotate(radians(theta)); rectMode(CENTER); fill(255, 126, 126); rect(0, 0, sz, sz); fill(0); // eyes circle(sz/2, -sz/5, sz/10); circle(sz/2, sz/5, sz/10); line(0, 0, sz/2, 0); // rib // tail line(-sz/2, 0, -sz/2-10, -5); line(-sz/2, 0, -sz/2-10, 5); pop(); } // display()
void move() { push(); translate(x, y); rotate(radians(theta)); // Move the robot at speed in the direction it is headed, based on theta if (theta == 90) { y = y + speed; } else if (theta == 180) { x = x - speed; } else if (theta == 270) { y = y - speed; } else { x = x + speed; }
// Check which wall it is colliding against and turn right if ((theta == 90) && (distance(x, y, x, height) < sz)) { turnRight(90); } else if ((theta == 180) && (distance(x, y, 0, y) < sz)) { turnRight(90); } else if ((theta == 270) && (distance(x, y, x, 0) < sz)) { turnRight(90); } else if ((theta == 0) && (distance(x, y, width, y) < sz)) { turnRight(90); } pop(); } void turnLeft(float deg) { theta = (theta - deg) % 360; } void turnRight(float deg) { theta = (theta + deg)%360; }
float distance(float x1, float y1, float x2, float y2) { return sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); } // distance() String toString() { return "<Robot of size " + sz + " at <"+x+","+y+"> facing "+theta+" degrees>"; } // toString() } // class Robot