疯狂连连看之开发游戏界面组件一

疯狂连连看之开发游戏界面组件一

开发游戏界面组件

本游戏的界面组件采用了一个自定义ViewGameView,它从View基类派生而出,这个自定义View的功能就是根据游戏状态来绘制游戏界面上的全部方块。

为了开发这个GameView,本程序还提供了一个Piece类,一个Piece对象代表游戏界面上的一个方块,它除了封装方块上的图片之外,还需要封装该方块代表二维数组中的哪个元素;也需要封装它的左上角在游戏界面中XY坐标。图18.4示意了方块左上角的XY坐标的作用。

                 

 

方块左上角的XY坐标可决定它的绘制位置,GameView根据这两个坐标值绘制全部方块即可。下面是该程序中Piece类的代码。

程序清单:codes\18\Link\src\org\crazyit\link\view\Piece.java

public class Piece

{

    // 保存方块对象的所对应的图片

    private PieceImage image;

    // 该方块的左上角的x坐标

    private int beginX;

    // 该方块的左上角的y坐标

    private int beginY;

    // 该对象在Piece[][]数组中第一维的索引值

    private int indexX;

    // 该对象在Piece[][]数组中第二维的索引值

    private int indexY;

    // 只设置该Piece对象在棋盘数组中的位置

    public Piece(int indexX , int indexY)

    {

        this.indexX = indexX;

        this.indexY = indexY;

    }

    public int getBeginX()

    {

        return beginX;

    }

    public void setBeginX(int beginX)

    {

        this.beginX = beginX;

    }

    // 下面省略了各属性的settergetter方法

    ...

    // 判断两个Piece上的图片是否相同

    public boolean isSameImage(Piece other)

    {

        if (image == null)

        {

             if (other.image != null)

                 return false;

        }

        // 只要Piece封装图片ID相同,即可认为两个Piece相等

        return image.getImageId() == other.image.getImageId();

    }

}

上面的Piece类中封装的PieceImage代表了该方块上的图片,但此处并未直接使用Bitmap对象来代表方块上的图片—因为我们需要使用PieceImage来封装两个信息:

Ø  Bitmap对象。

Ø  图片资源的ID

其中Bitmap对象用于在游戏界面上绘制方块;而图片资源的ID则代表了该Piece对象的标识,当两个Piece所封装的图片资源的ID相等时,即可认为这两个Piece上的图片相同。如以上程序中粗体字代码所示。

下面是PieceImage类的代码。

程序清单:codes\18\Link\src\org\crazyit\link\view\PieceImage.java

public class PieceImage

{

    private Bitmap image;

    private int imageId;

    // 有参数的构造器

    public PieceImage(Bitmap image, int imageId)

    {

        super();

        this.image = image;

        this.imageId = imageId;

    }

    // 省略了各属性的settergetter方法

    ...

}

 

本文节选自《疯狂Android讲义(CD光盘1)》一书。

《疯狂Android讲义(CD光盘1)》一书已由电子工业出版社正式出版,本书由李刚编著。

当当:

http://product.dangdang.com/product.aspx?product_id=21099097&ref=search-1-pub

卓越:

http://www.amazon.cn/%E7%96%AF%E7%8B%82Android%E8%AE%B2%E4%B9%89-%E6%9D%8E%E5%88%9A/dp/B0055BH3PY/ref=sr_1_1?ie=UTF8&qid=1309491286&sr=8-1

互动:

http://product.china-pub.com/193974

原文地址:https://www.cnblogs.com/broadview/p/2099362.html