public boolean envelops(Shape s) {
boolean flag = true;
double distance = 0.0;
if(s instanceof Square){ //check if the shape is a Square
Point bottomLeft= new Point(((Square)s).getTopLeft().getX(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength()); //calculating the cordinates of the square
Point bottomRight= new Point(((Square)s).getTopLeft().getX()+((Square)s).getSideLength(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength());
Point topRight= new Point(((Square)s).getTopLeft().getX()+ ((Square)s).getSideLength(),((Square)s).getTopLeft().getY());
ArrayList<Point> points = new ArrayList<Point>(); //storing points in a ArrayList of points
points.add(((Square)s).getTopLeft());
points.add(bottomLeft);
points.add(topRight);
points.add(bottomRight);
for(int i=0; i<points.size(); i++)
{
distance= this.center.distance(points.get(i)); //finding ditance of each cordinate from the center of the circle
if(distance-this.radius>Shape.TOLERANCE) flag= false; //if the distance is greater than the radius then flag becomes false, ie., the cordinate is outside the circle
}
}
if(s instanceof Circle){
distance=this.center.distance(((Circle)s).getCenter()); //finding distance between the centers of the 2 circles
distance= distance +((Circle)s).getRadius();
if(distance- this.getRadius()> Shape.TOLERANCE || distance==this.getRadius()){ //The method will return false if both circles have 0 radius
flag=false; //make flag false if the distance is more than the radius of the object Circle
}
}
return flag;
}
嗨,我有一个代码来检查一个形状(圆形或方形)是否包围另一个形状。我用过这段代码。如果this
对象包含传递的形状,则为true。任何人都可以建议我改进或更好的替代方法。在此先感谢:)