網路上或是書本上,都已經很多關於HelloWorld的教學了,在此就不多做介紹 , 直接切入正題 , 做遊戲 , 少不了畫面的處理 , 今天就教各位如何開始在手機上繪圖.


首先我們開起一個新檔案 , 命名為Lession1 , 請注意大小寫 , Java是一個大小寫有差異的語言 . 此檔案為主要Midlet的進入點 , 我們可以看到他只有一個 new NewClass 這樣的一個東西 , 主要是在new我們主要的繪圖物件
package Lession1;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Lession1 extends MIDlet implements CommandListener
 {

    private Command exitCommand; // The exit command
    private Display display;     // The display for this MIDlet

    public Lession1() {
        display = Display.getDisplay(this);
    }

    public void startApp() {
        display.setCurrent(new NewClass());
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable s) {
    }

}




以下是 NewClasses() 這個class的程式碼 , 也是主要的繪圖核心部分 , 我們可以看到他繼承了GameCanvas這個物件 , 和implement Runnable ,這些是甚麼呢?
GameCanvas 這個物件比較特殊的地方是 , 他針對遊戲所設計的 , 此Canvas中可以抓到每個手機對Game的對應按鈕 , 也可以在上面加入對於圖層的處理 ,可以做到像是RPG遊戲的海的動畫 , 天空的動畫 , 人物的動畫及移動等等的功能 , 讓開發者可以輕鬆的控制每個圖層
Runnable 也就是我們常聽到的執行緒的部分 , 他可以做甚麼呢 ? 打個比方 , 他可以幫助我們在設計的時候 , 一邊處理動畫 , 一邊還能讓手機接收到我們所按下的按鈕 , 酷吧!
implements Runnable之後 , 在這個class中比需要實做run()這個function喔 . 否則編譯會有錯誤 , 請注意 .

package Lession1;


import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.Graphics;
/**
 *
 * @author user
 */
public class NewClass extends GameCanvas  implements Runnable
{
    protected static Graphics gGrap;
    static int scrWidth = 0;        // 螢幕寬度
    static int scrHight = 0;        // 螢幕高度
    int moveX=0 ;                 // 目前的方塊寬度
    int moveY=0;                  // 目前的方塊長度
    int verX=3, verY=3;           // 方塊移動距離
    public NewClass()
    {
        super(true);
        this.setFullScreenMode(true) ;  // 設定全螢幕
        gGrap = getGraphics ();
        System.out.println(getWidth());
        scrWidth = getWidth();            // 取得手機螢幕寬度
        scrHight = getHeight();           // 取得手機螢幕高度
        new Thread (this).start();      // 新建執行緒並開始
    }

    public void run()
    // 功能 : 執行緒
    {
        while(true)
        {
            if (moveX > scrWidth)
                verX = -3;
            if (moveY > scrHight)
                verY = -3;


            if (moveX < 0)
                verX = 3;
            if (moveY < 0)
                verY = 3;
            moveX =moveX+verX;
            moveY =moveY+verY;
            //======這裡是底圖=====
            gGrap.setColor (0x000000);
            gGrap.fillRect(0, 0, scrWidth, scrHight);
            //======這裡是上層的移動方塊=====
            gGrap.setColor (0xff00ff);
            gGrap.fillRect(0,0,moveX,moveY);
            flushGraphics ();
            delay(200);
        }
    }

    protected void delay(long tTime)
    // 功能 : 延遲
    {
        try{
            Thread.sleep (tTime);
        }
        catch (Exception e) {};
    }

}



相关文章