import java.awt.Graphics; public class Bubble extends Shape { private double radius; /** * Constructor for the Bubble class. * * @param x the x coordinate of the center of the bubble * @param y the y coordinate of the center of the bubble */ public Bubble(int x, int y) { super(x, y); this.radius = 10; } // Find the point (wx, wy) inside the window which is closest to the // center (x, y) of the circle. In other words, find the wx in the // interval [0, w - 1] which is closest to x, and find the wy in the // interval [0, h - 1] which is closest to y. // If the distance between (wx, wy) and (x, y) is less than the radius // of the circle (using Pythagoras's theorem) then at least part of // the circle is visible in the window. // Note: if the center of the circle is inside the window, then (wx, wy) // is the same as (x, y), and the distance is 0. @Override public boolean isVisible(int w, int h) { double x = getX(); double y = getY(); double wx = (x < 0 ? 0 : (x > w - 1 ? w - 1 : x)); double wy = (y < 0 ? 0 : (y > h - 1 ? h - 1 : y)); double dx = wx - x; double dy = wy - y; return dx * dx + dy * dy <= radius * radius; } /** * Whether the point at xy is currently inside the bubble * * @param x the x coordinate of the point * @param y the y coordinate of the point * @return true if the point is inside the bubble, false otherwise */ @Override public boolean isIn(int x, int y) { double dx = x - getX(); double dy = y - getY(); return dx * dx + dy * dy < radius * radius; } /** * Draw the bubble. * * @param g the graphics context */ @Override public void draw(Graphics g) { super.draw(g); g.drawOval( getX() - (int) radius, getY() - (int) radius, (int) radius * 2, (int) radius * 2); } public static void testBubble() { Bubble b = new Bubble(20, 30); System.out.println(b.getX() == 20); System.out.println(b.getY() == 30); b.setX(40); System.out.println(b.getX() == 40); System.out.println(b.getY() == 30); b.setY(60); System.out.println(b.getX() == 40); System.out.println(b.getY() == 60); System.out.println(b.isVisible(100, 100) == true); b.setX(50); b.setY(0); System.out.println(b.isVisible(100, 100) == true); b.setX(99); b.setY(50); System.out.println(b.isVisible(100, 100) == true); } }