其实用Canvas来画网格还更好,更省内存,可惜只是在学习中,先了解一下组件的用法,以后再深入。
A Drawable is a general abstraction for "something that can be drawn." Most often you will deal with
Drawable as the type of resource retrieved for drawing things to the screen;
Drawable一般用于处理res/drawable目录下的文件,
Activity.getResources().getDrawable(R.drawable.m0);
// 这样就可以取得目录下名字叫m0的资源文件了,比较方便,
ImageButton.setImageDrawable( m0 );
// 就可以设定要显示的图了,
Drawable可以是混合的一串图,比如某个动作的一连贯图或层次图,然后可以用
setBounds(Rect),setState(int[]), setLevel(int) 来取得要用的部分
// boomArr存放的是网格的数组指针,在boomArr中的随机置生成炸弹,根据难度不同生成不同数量的炸弹
void setBooms( final int level ) {
// 以线程方式在后台生成炸弹,level是难度,每个难度增加50个炸弹
new Thread() {
public void run() {
int count = 250 + level * 50;
int total = columnCount * rowCount;
for( int i=0; i<count; i++) {
//生成从[0,count-1]间的数字,即随机设置某些网格是炸弹
boomArr[(int) ((total) * java.lang.Math.random())].isBoom = true;
}
}
}.start();
}
// 生成网格,第一列为1,2,3...第二列是4,5,6...的顺序生成
void loadBooms( final int level ) {
int index = 0;
boomArr = new Boom[columnCount * rowCount];
int x = 0, y = 0, start_x = 10, start_y = 46;
for( int c=0; c<columnCount; c++ ) {
x = start_x + c + c * 14;
for( int r=0; r<rowCount; r++ ) {
y = start_y + r + r * 14;
boomArr[ index ] = new Boom(this, index);
//指向生成的网格的指针,可能是炸弹,也可能不是
layout.addView( boomArr[ index ++ ],
new AbsoluteLayout.LayoutParams(14, 14, x, y) );
}
}
setBooms( level );
}
void resetBooms( final int level ) {
for(int c=0; c<boomArr.length; c++) {
boomArr[c].reset();
}
setBooms( level );
}
void seeAllBooms() {
for(int c=0; c<boomArr.length; c++) {
if( !boomArr[c].hasClicked ) {
boomArr[c].performClick();
// 响应boom的点击事件,
}
}
}
最看看某个网格的点击代码:这个就是扫雷功能的主要算法了,比较简单,
int[] tmp = new int[8];
tmp[0] = index - Booms.rowCount - 1; // 左上角
tmp[1] = index - 1; // 正上方
tmp[2] = index + 25 - 1; // 右上角
tmp[3] = tmp[0] + 1; // 左边
tmp[4] = tmp[2] + 1; // 右边
tmp[5] = tmp[0] + 2; // 左下角
tmp[6] = index + 1; // 正下方
tmp[7] = tmp[2] + 2; // 右下角
int total = 0;
AbsoluteLayout.LayoutParams t1 = (AbsoluteLayout.LayoutParams) getLayoutParams();
AbsoluteLayout.LayoutParams t2;
for( int c=0; c<tmp.length; c++ ) {
if( tmp[c] < 0 || tmp[c] >= Booms.columnCount * Booms.rowCount)
continue ;
if( Booms.boomArr[ tmp[c] ].isBoom ) {
t2 = (AbsoluteLayout.LayoutParams) Booms.boomArr[ tmp[c] ].getLayoutParams();
if( Math.abs(t1.x - t2.x) > 14 * 2 || Math.abs(t1.y - t2.y) > 14 * 2)
continue ;
total ++;
}
}
// 载入数字对应的图
setImageDrawable( Booms.ms[ total ] );