import jlab.graphics.DWindow;
public class Ball {
//------- ตัวแปรประจำอ็อบเจกต์ (object variable) --------
public double x, y;
public double dx, dy;
public double r;
//------- ตัวสร้าง (constructor) ----------------------
public Ball(double r0, double x0, double y0) {
r = r0; x = x0; y = y0;
dx = random(-3, 3); dy = random(-3, 3);
}
public Ball(double r0,double x0,double y0,double dx0,double dy0){
r = r0; x = x0; y = y0;
dx = dx0; dy = dy0;
}
//------- เมท็อดประจำอ็อบเจกต์ (object method) ----------
public void move(DWindow w) {
x += dx; y += dy;
if (hitWall(x, w.getWidth())) dx = -dx;
if (hitWall(y, w.getHeight())) dy = -dy;
x = Math.min(Math.max(x, r), w.getWidth() - r);
y = Math.min(Math.max(y, r), w.getHeight() - r);
}
public void draw(DWindow w) {
w.fillEllipse(DWindow.BLACK, x, y, 2*r, 2*r);
}
private boolean hitWall(double c, double length) {
return (c <= r || c >= length-r);
}
//------- เมท็อดประจำคลาส (class method) -------------
private static double random(double a, double b) {
return a + (b - a) * Math.random();
}
//------- เมท็อด main เพื่อทดสอบการทำงานของ Ball --------
public static void main(String[] args) {
DWindow w = new DWindow(200, 200);
Ball[] balls = new Ball[300];
for (int i=0; i<balls.length; i++)
balls[i] = new Ball(2, 100, 100);
w.setRepaintDuringSleep(true);
while (true) {
w.fade(0.3);
for (int i=0; i<balls.length; i++) {
balls[i].move(w); balls[i].draw(w);
}
w.sleep(50);
}
}
}
|