java遊戲開發–簡單的幾行代碼就完成瞭驅動小精靈的編程 – JAVA編程語言程序開發技術文章

  今天編寫瞭一個驅動小精靈,簡短的幾行代碼就完成瞭;雖然簡單但是用處很大,很多用java、android開發的遊戲界面佈局都或多或少的用的這些簡單代碼。

packagecom.csdn.code;

 

importjava.awt.Color;

importjava.awt.Frame;

importjava.awt.Graphics;

importjava.awt.event.WindowAdapter;

importjava.awt.event.WindowEvent;

public classDriveElf extends Frame{

      private int x = 40;   //精靈在畫板上的初始位置—橫坐標

      private int y = 40;   //精靈在畫板上的初始位置—縱坐標

      private int arc = 320;   //精靈嘴張合的角度

      public DriveElf() {

           setBounds(200,200,600,500);

           setVisible(true);

           setBackground(Color.cyan);

           addWindowListener(new WindowAdapter(){

                 public voidwindowClosing(WindowEvent e) {

                      System.exit(0);

                 }             

           });

           new Thread(){

                 public void run(){

                     while(true){

                            // 兩個for循環作用分別是使精靈在畫板上移動

                            for(inti=0;i<40;i++){

                                  arc += 1;

                                  x += 10;

                                  y += 3;

                                  }

                                  try{

                                       Thread.sleep(50);

                                       }catch(Exceptione){

                                             e.printStackTrace();

                                       }

                                       repaint();

                            for(inti=0;i<40;i++){

                                  arc -= 1;

                                  x -= 8;

                                  y -= 1;

                                  try{

                                       Thread.sleep(100);

                                        }catch(Exceptione){

                                             e.printStackTrace();

                                       }

                                       repaint();

                            }                        

                     }

                 }

           }.start();

      }

//噴繪方法,實現在畫板上的繪圖

      public void paint(Graphics g){

           g.setColor(Color.red);

           g.fillArc(x, y, 90, 90, 0, arc);  //畫出精靈身子

           g.setColor(Color.gray);

           g.fillArc(x+50, y+10, 20, 20, 0,360);  //畫出精靈眼白

           g.setColor(Color.black);

           g.fillArc(x+56, y+15, 10, 10, 0,360);  //畫出精靈眼球

      }

      public static void main(String[] args) {

           new DriveElf();

 

      }

 

}

發佈留言