实现时间的变化
将以下内容添加到MainActivity.java的onCreate函数中:
//进来后,每1s发送一条空消息,接收该空消息,改变TextView,达到柜台效果
//延迟1s发送空消息。 发送消息的号码为1,延迟时间为1000ms=1s
handler.sendemptymessagedelayed (1,1000 );
然后在onCreate函数之外添加以下内容:
//定义计数时间的变量
int time=0;
//消息通信的结构,改写handleMessag方法接收消息,形成时间累计的效果
Handler handler=new Handler
@Override
publicvoidhandlemessage (@ nonnullmessagemsg )。
if(msg.what==1) {
时间;
timeTv.setText ('时间: ' time '秒);
handler.sendemptymessagedelayed (1,1000 );
}
}
(;
时间变化有两种情况。 一个是拼图游戏结束时停止时间,另一个是重新开始时重新测量时间。 现在先实现点击重新开始按钮时重新测量。
公共语音重启(视图视图) {
//中断前的新闻
Handler.removemessages(1;
//使时间归零,重新开始时间
时间=0;
timeTv.setText ('时间: ' time '秒);
handler.sendemptymessagedelayed (1,1000 );
}
打乱拼图的显示
想法:根据数组的随机顺序随机排列图像
首先声明几个变量。
//存储碎片数组,易于集中管理
private int [ ] image={ r.mipmap.img _ 00x 00,R.mipmap.img_00x01,R.mipmap.img_00x02,r.mi pmap.img
//声明图像数组的下标数组,并随机排列该数组
私有int [ ] image index=new int [ image.length ];
接下来,写一种洗牌的方法,以便在onCreate进入时显示洗牌的数组。
首先洗牌角标,然后将顺序混乱的角标设置为ImageButton,保证进入后处于洗牌状态。 具体代码如下。
//随机打乱排列中的要素,以不规则的形式进行图像显示
私有语音灾难随机(
for(intI=0; i imageIndex.length; I ) {
imageIndex[i]=i;
}
//决定20次,随机选择与2个角标记对应的值进行交换
int rand1、rand2;
for(intj=0; j 20; j ) {
//随机生成第一个角标记,生成0-8之间的随机数
rand1=(int ) ) Math.random ) * ) *(imageIndex.length-1 ); //Math.random ()生成介于0-1之间的随机数,将最大值乘以最小值(即8-0 ),最后将最小值0加到整体上
//第二次随机生成的角标不能与第一次相同。 同样的话交换变得不方便
do {
rand2=(int ) ) Math.random ) * ) *(imageIndex.length-1 );
if(rand1!=rand2)
布雷克;
(while ) true;
//交换与数组两个角点对应的值
SWAP(rand1、rand2);
}
//随机排列在指定的控件上
ib00.setimageresource (image [ image index [0];
ib01.setimageresource (image [ image index [1];
ib02.setimageresource (image [ image index [2];
ib10.setimageresource (image [ image index [3];
ib11.setimageresource (image [ image index [4];
ib12.setimageresource (image [ image index [5];
ib20.setimageresource (image [ image index [6];
ib21.setimageresource (image [ image index [7];
ib22.setimageresource (image [ image index [8];
}
//替换数组指定角的数据
隐私保护软件(int rand2,int rand2) {
int temp=imageIndex[rand1];
image index [ rand2]=image index [ rand1];
imageIndex[rand1]=temp;
}
碎片位置切换
碎片移动条件:空白区域只能移动同行或位于同一列且相邻的图像。 否则,不能完成。
必须确定空白位置和其他图的位置是否在同一行或同一列中。
移动的过程写在onClick上: