Files
oop/assignment6/Question3/Bubble.java
2022-05-25 13:14:19 +08:00

66 lines
1.8 KiB
Java

import java.awt.Graphics;
public class Bubble extends Shape implements IShape {
// instance variables
private double radius;
// constructor
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;
}
@Override
public boolean isIn(int x, int y) {
double dx = x - getX();
double dy = y - getY();
return dx * dx + dy * dy < radius * radius;
}
@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);
}
}