类似的小游戏大家肯定都接触过,进入程序,图片会无序排列,共九张乱序图片,需要移动到给出模板图片相同方为成功,在游戏进行的过程中会有时间在计时,当拼图成功时时间停止,点击重新开始,图片会重新打乱,时间重新开始计时!
实现步骤:1.拼图游戏绘制,2.拼图游戏打乱设置,3.拼图游戏碎片位置切换,4.拼图成功条件,5.拼图游戏重新开始
本次只实现步骤1和步骤2
实现过程中用到的部分知识,时间计时用到handler线程机制,图片的无序排列实现原理是将其以数值形式写入,然后以两两数值进行交换在放在对应的控件上!
已在代码段中进行了对应的注释,如果有不明白的可以评论区留言或者私信,若文章内容有错误不足,还请各位包涵,指正!
代码如下:
xml拼图布局代码:
activity功能实现代码:
package com.example.jigsaw;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ImageButton ib00,ib01,ib02,ib10,ib11,ib12,ib20,ib21,ib22;
Button restartBtn;
TextView timeTv;
//定义时间的变量
int time = 0;
//存放碎片的数组,便于进行统一的管理
private int[]image={R.drawable.pt_id_00x00,R.drawable.pt_id_00x01,R.drawable.pt_id_00x02,
R.drawable.pt_tv_01x00,R.drawable.pt_tv_01x01,R.drawable.pt_tv_01x02,R.drawable.p1,R.drawable.p2,R.drawable.p3};
//声明一个图片数组的下标数组,随机排列这个数组
private int[]imageIndex=new int[image.length];
Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what==1){
time++;
timeTv.setText("时间:"+time+" 秒");
handler.sendEmptyMessageDelayed(1,1000);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//打乱碎片
disruptRandpm();
handler.sendEmptyMessageDelayed(1,1000);
}
//随机打乱不规则
private void disruptRandpm() {
for(int i=0;i