import java.awt.*; /** * Class that will draw a square given any 4 points * @author Crystal Furman */ public class SlantedSquare { /////////////fields//////////////////// private Point p1; private Point p2; private Point p3; private Point p4; ///////////// constructors ///////// /** * Constructor that takes 4 points * @param point1 the first point * @param point2 the second point * @param point3 the third point * @param point4 the fourth point */ public SlantedSquare(Point point1, Point point2, Point point3, Point point4) { p1 = point1; p2 = point2; p3 = point3; p4 = point4; } /////////////// methods /////////////// /** * Method to find the midpoint between two points * @param pt1 the first point * @param pt2 the second point * @return the point in the middle of the * two points */ public static Point getMidpoint(Point pt1, Point pt2) { double x = Math.abs(pt1.x - pt2.x) * 0.5 + Math.min(pt1.x,pt2.x); double y = Math.abs(pt1.y - pt2.y) * 0.5 + Math.min(pt1.y,pt2.y); Point pt = new Point((int) x,(int) y); return pt; } /** * Method to get the length between the two points * @param pt1 the first point * @param pt2 the second point * @return the distance between the points */ public static double getDistance(Point pt1, Point pt2) { double diffX = pt1.x - pt2.x; double diffY = pt1.y - pt2.y; double dist = Math.sqrt((diffX * diffX) + (diffY * diffY)); return dist; } /** * Method to recursively subdivide the slanted square * @param g the graphics context to draw in * @param smallestLength the smallest allowed length */ public void subdivideSquare(Graphics g, int smallestLength) { double currLength = this.getDistance(this.p1,this.p2); if (currLength > smallestLength) { Point pt12 = this.getMidpoint(p1,p2); Point pt23 = this.getMidpoint(p2,p3); Point pt34 = this.getMidpoint(p3,p4); Point pt41 = this.getMidpoint (p4,p1); g.drawLine(pt12.x,pt12.y,pt23.x,pt23.y); g.drawLine(pt23.x,pt23.y,pt34.x,pt34.y); g.drawLine(pt34.x,pt34.y,pt41.x,pt41.y); g.drawLine(pt41.x,pt41.y,pt12.x,pt12.y); SlantedSquare s1 = new SlantedSquare (pt12,pt23, pt34,pt41); s1.subdivideSquare(g, smallestLength); } } }