3. ทำซ้ำ ๆ

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.

 
รหัสที่ 3-5  โปรแกรมแสดงงูเลื้อยตามเมาส์
import jlab.graphics.DWindow;
// โปรแกรมงูเลื้อยตามเมาส์ 
public class Snake {
  public static void main(String[] args) {
    DWindow w = new DWindow(160, 160);
    double x0=0, y0=0, x1=0, y1=0;
    double x2=0, y2=0, x3=0, y3=0;
    double x4=0, y4=0, x5=0, y5=0;
    while (true) {
      x5 = w.getMouse().getX(); //อ่านตำแหน่งใหม่ 
      y5 = w.getMouse().getY();  
      w.clearBackground();      //ล้างภาพ 
      w.drawLine(x0, y0, x1, y1); //วาดงู 5 เส้น 
      w.drawLine(x1, y1, x2, y2); // จากตำแหน่ง 
      w.drawLine(x2, y2, x3, y3); // ของเมาส์ในอดีต 
      w.drawLine(x3, y3, x4, y4);
      w.drawLine(x4, y4, x5, y5);
      w.sleep(100);      //หยุด 100ms.
      x0 = x1; y0 = y1;  //เลื่อนตำแหน่งของงูไปหนึ่งตำแหน่ง 
      x1 = x2; y1 = y2;   
      x2 = x3; y2 = y3;
      x3 = x4; y3 = y4;
      x4 = x5; y4 = y5;
    }
  }
}
©2009 S.Prasitjutrakul