import jlab.graphics.DWindow;
public class TestBall {
public static void main(String[] args) {
DWindow w = new DWindow(200, 200);
Ball b1 = createRandomBall(200,200);
Ball b2 = createRandomBall(200,200);
while (true) {
w.clearBackground();
move(w, b1); move(w, b2);
draw(w, b1); draw(w, b2);
w.sleep(50);
}
}
private static void draw(DWindow w, Ball b) {
w.fillEllipse(DWindow.BLACK, b.x, b.y, 2*b.r, 2*b.r);
}
private static double random(double a, double b) {
return a + (b - a) * Math.random();
}
private static void move(DWindow w, Ball b) {
b.x += b.dx; b.y += b.dy;
if (b.x <= b.r || b.x >= w.getWidth() - b.r) b.dx = -b.dx;
if (b.y <= b.r || b.y >= w.getHeight()- b.r) b.dy = -b.dy;
b.x = Math.min(Math.max(b.x, b.r), w.getWidth() - b.r);
b.y = Math.min(Math.max(b.y, b.r), w.getHeight() - b.r);
}
private static Ball createRandomBall(double w, double h) {
Ball b = new Ball();
b.x = w/2; b.y = h/2;
b.dx = random(-5, 5); b.dy = random(-5, 5);
b.r = random(3, 8);
return b;
}
}
|