import element.*; // includes Drawable interface public class Triangle implements Drawable { private final int n = 3; // n is number of vertices private Pt v[]; // vertices of the triangle public Triangle() // post: generate an equilateral triangle with side 200; // "base" along top { this(new Pt(0,0), new Pt(200,0), new Pt(100,173)); } public Triangle(Triangle other) // pre: other is a non-null triangle // post: this becomes a copy of the triangle { this(other.v[0], other.v[1], other.v[2]); } public Triangle(Pt p, Pt q, Pt r) // pre: p, q, r are non-null // post: new triangle with vertices pqr { v = new Pt[n]; v[0] = new Pt(p); v[1] = new Pt(q); v[2] = new Pt(r); } public int height() // post: returns the height of the triangle { return bottom()-top(); } public int width() // post: returns the width of the triangle { return right()-left(); } public int left() // post: returns the left-most coordinate of the bounding // box containing the triangle { int i; int result = v[0].x(); for (i = 1; i < n; i++) { result = Math.min(result,v[i].x()); } return result; } public int right() // post: returns the right-most coordinate of the bounding // box containing the triangle { int i; int result = v[0].x(); for (i = 1; i < n; i++) { result = Math.max(result,v[i].x()); } return result; } public int bottom() // post: returns the bottom-most coordinate of the bounding // box containing the triangle { int i; int result = v[0].y(); for (i = 1; i < n; i++) { result = Math.max(result,v[i].y()); } return result; } public int top() // post: returns the top-most coordinate of the bounding // box containing the triangle { int i; int result = v[0].y(); for (i = 1; i < n; i++) { result = Math.min(result,v[i].y()); } return result; } public Pt center() // post: returns the center of the bounding box of the triangle { return new Pt((left()+right())/2,(top()+bottom())/2); } public void center(Pt p) // post: sets the center of the bounding box of triangle to p; // the dimensions remain the same. { int i; Pt old = center(); int dx = p.x()-old.x(); int dy = p.y()-old.y(); for (i = 0; i < n; i++) { v[i].move(dx,dy); } } public void drawOn(DrawingWindow d) // post: draws outline of this triangle on window d; // same as d.draw(this) { int i; for (i = 0; i < n; i++) { d.draw(new Line(v[i],v[(i+1)%n])); } } public void fillOn(DrawingWindow d) // post: draws the interior of this triangle on window d; // same as d.fill(this) { drawOn(d); } public void clearOn(DrawingWindow d) // post: erases this triangle from window d; // same as d.clear(this) { int i; for (i = 0; i < n; i++) { d.clear(new Line(v[i],v[(i+1)%n])); } } }