用NetBeans开发J2ME游戏实例讲解(三)[1]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

作者:林刚 文章来源:http://blogs.sun.com/lirincy

4.改进程序

 (1)记录历史步骤,以便可以悔棋:

记录历史步骤的方法是实现一个History类,这个类实际上是一个Vector的封装,用来保存每一步的走法,走法被定义为一个包含5个元素的数组,分别是X,Y,width,height,direction. 这里需要注意的是,Java当中实际上是没有局部变量的,每一个局部变量都需要new出来,所以在使用Vector的addElement()函数时,由于它是传引用,我们必须要新创建一个element,而不能使用全局的,因为如果使用全局的,下一次addElement时,会因为该变了变量的值使得刚才加到Vector中的值也改变了。

import java.util.Vector;
 
/**

 *

 * @author lin

 */

public class History {

    private static Vector steps = new Vector();   

    /** Creates a new instance of History */

    public History() {

        clear();

    }

    public static void addStep(Object step){

        steps.addElement(step);

    }

    public static void removeLastStep(){

        steps.removeElement(steps.lastElement());

    }

    public static Object getLastStep(){

        return steps.lastElement();

    }

    public static Object getStepAt(int index){

        return steps.elementAt(index);

    }

    public static int getSize(){

        return steps.size();

    }

    private void clear(){

        if (!steps.isEmpty())

            steps.removeAllElements();

    }

}

在每一步移动结束后,记录这一步的信息:

ContorlLogic.java: Move()

......

    moves++;// 增加移动的步骤

    byte[] step = new byte[5]; //五个参数分别为,前四个和SelectArea一样,最后一个表示上1,下2,左3,右4。

    //将此次移动记录到历史记录当中;

    step[0]= this.SelectArea[0];

    step[1]= this.SelectArea[1];

    step[2]= this.SelectArea[2];

    step[3]= this.SelectArea[3];

    step[4]= this.getMoveDirection();

    history.addStep(step);

......


增加一个悔棋的按钮,增加一个unMove()函数:

    public void unMove(){

        if ( moves == 0 )

            return;

        byte[] step = new byte[5]; //五个参数分别为,前四个和SelectArea一样,最后一个表示上1,下2,左3,右4。

        step = (byte []) history.getLastStep();//取得上一步移动

        history.removeLastStep();//减少一步;

        moves--;

        for (int i= 0; i< 4;i++){

            this.MoveArea[i] = step[i];//重设MoveArea  

            this.SelectArea[i] = step[i];//重设SelectArea

        }

        if (step[4] == 1){

            this.SelectArea[1] = (byte) (step[1]-1);

            this.loc[1]++;

        }

        else if (step[4] == 2){

            this.SelectArea[1] = (byte) (step[1]+1);

            this.loc[1]--;

        }

        else if (step[4] == 3){

            this.SelectArea[0] = (byte) (step[0]-1);

            this.loc[0]++;

        }

        else if (step[4] == 4){

            this.SelectArea[0] = (byte) (step[0]+1);

            this.loc[0]--;

        }

        //移动回来.

        byte[][] temp = new byte[this.SelectArea[3]][this.SelectArea[2]];

本文关键:用NetBeans开发J2ME游戏实例讲解(三)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top