Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1490131
  • 博文数量: 465
  • 博客积分: 8915
  • 博客等级: 中将
  • 技术积分: 6365
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-30 15:05
文章分类

全部博文(465)

文章存档

2017年(33)

2016年(2)

2015年(4)

2014年(29)

2013年(71)

2012年(148)

2011年(178)

分类: IT业界

2011-07-06 16:50:20

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

开发游戏界面组件

本游戏的界面组件采用了一个自定义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)》一书已由电子工业出版社正式出版,本书由李刚编著。

当当:

卓越:

互动:

阅读(389) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~