4. เลือกปฏิบัติ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 4-3  โปรแกรมแสดงลูกบอลสีดำเคลื่อนที่ และเด้งผนังวินโดว์ได้
import jlab.graphics.DWindow;
// โปรแกรมแสดงลูกบอลสีดำเคลื่อนที่ และเด้งผนังได้ 
public class BouncingBall {
  public static void main(String[] args) {
    DWindow w = new DWindow(200, 100);
    double r = 10, x = 100, y = r+1;
    double dx = 4, dy = 2;
    while (true) {
      x = x + dx;  y = y + dy;
      if ((x-r) <= 0) {              // ชนด้านซ้าย 
        dx = -dx;  x = r;
      }
      if ((y-r) <= 0) {              // ชนด้านบน 
        dy = -dy;  y = r;
      }
      if ((x+r) >= w.getWidth() ) {  // ชนด้านขวา 
        dx = -dx;  x = w.getWidth() - r;
      }
      if ((y+r) >= w.getHeight()) {  // ชนด้านล่าง 
        dy = -dy;  y = w.getHeight() - r;
      }
      w.fade(0.3);
      w.fillEllipse(w.BLACK, x, y, 2*r, 2*r);
      w.sleep(50);
    }
  }
}
©2009 S.Prasitjutrakul