标题:求帮忙解释一下android的拼图游戏代码
只看楼主
kidangel666
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:93
专家分:139
注 册:2010-9-15
结帖率:78.95%
 问题点数:0 回复次数:1 
求帮忙解释一下android的拼图游戏代码
程序代码:
package org.android.picture_demo;

import  android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ImageView.ScaleType;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class PictureDemo extends Activity {
    @SuppressWarnings("unused")
    private static final String TAG = PictureDemo.class.getName();

    private int levalNow = 3;

    private ImageView mImages[][];// 存放小图片的数组
    private Bitmap mBitmap;// 资源图片
    private int mImageWidth, mImageHeight;// slot的宽高
    private int mImageNum[];// 图片的顺序
    private int x, y;// 图片裁剪的起始位置
    private int clickNum = 0;// 点击参数
    // 资源图片群
    private int image[] = new int[] { R.drawable.aa13, R.drawable.iamge,
        R.drawable.naruto_ying_chutian, R.drawable.zaibuzhan_bai,
        R.drawable.you2, R.drawable.woailuo2, R.drawable.you3, };

    Editor edit;

    // 屏幕的参数
    private int windowWidth;
    private int windowHeight;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    edit = this.getSharedPreferences("LEVAL", Context.MODE_WORLD_WRITEABLE)
        .edit();

    levalNow = this.getSharedPreferences("LEVAL",
        Context.MODE_WORLD_WRITEABLE).getInt("MYLEVAL",
        MainActivity.LEVAL1);
    // Log.e(TAG, "" + levalNow);
    WindowManager w = this.getWindowManager();
    windowHeight = w.getDefaultDisplay().getHeight();
    windowWidth = w.getDefaultDisplay().getWidth();

    setBitmap();
    setImage();
    }

    public void setImage() {

    mImageWidth = mBitmap.getWidth() / levalNow;
    mImageHeight = mBitmap.getHeight() / levalNow;
    mImageNum = new int[levalNow * levalNow];

    erraLen(levalNow * levalNow);
    readyImage();

    setLayout();
    }

    private void setLayout() {

    PictureLayout lay = new PictureLayout(this, mImages);
    lay.setGravity(Gravity.CENTER);
    setContentView(lay);
    }

    private void setBitmap() {
    // 计算选择的是第几张图片
    int postion = (int) Math.floor(Math.random() * image.length);

    // 从资源文件中读取图片
    mBitmap = readBitmap(getResources(), image[postion]);

    }

    /**
     * @see 把一个有序数组通过随机取数打乱
     * @param a
     */
    public void erraLen(int a) {

    int errInt[] = new int[a];
    for (int i = 0; i < a; i++) {
        errInt[i] = i;
    }

    int len = a;// 设置随机数的范围
    for (int i = 0; i < a; i++) {
        int index = (int) Math.floor((Math.random() * len));
        mImageNum[i] = errInt[index];

        for (int j = index; j < errInt.length - 1; j++) {
        // 把选中的数之后的数一次向前移一位
        errInt[j] = errInt[j + 1];
        }
        len--;// 随机数的范围减一
    }
    }

    /**
     * @see 准备图片 把一张图片截成几张小的通过打乱的数组来取cache里的图片放到View里面就成打乱二维数组
     */
    private void readyImage() {
    Matrix matrix = new Matrix();
    mImages = new ImageView[levalNow][levalNow];

    // 设置缩放比例
    float scaleW = ((float) mBitmap.getWidth()) / windowWidth;
    float scaleH = ((float) mBitmap.getHeight()) / windowHeight;
   
    float scale = scaleW > scaleH ? 1 / scaleW : 1 / scaleH;
    matrix.postScale(scale, scale);

    Bitmap bitss[][] = new Bitmap[levalNow][levalNow];
    ImageView[][] cache = new ImageView[levalNow][levalNow];
    int cont = 1;
    for (int i = 0; i < levalNow; i++) {
        for (int j = 0; j < levalNow; j++) {
        int x = i * mImageWidth;
        int y = j * mImageHeight;
        // 第一个是要在那个图片上截取 x,y是要在这个图的那个位置截取
        // blockWidth,blockHeight是截取的长和宽matrix是缩放的比例
       
        //源代码
        /*Bitmap mapi = Bitmap.createBitmap(mBitmap, x, y, mImageWidth,
            mImageHeight, matrix, true);*/
        //修改的

        Bitmap mapi = Bitmap.createBitmap(mBitmap, x, y, mImageWidth,
                mImageHeight, matrix, true);
       
        bitss[i][j] = mapi;
        ImageView img = new ImageView(this);
        BitmapDrawable draw = new BitmapDrawable(bitss[i][j]);
        img.setImageDrawable(draw);
        img.setId(cont);
        img.setScaleType(ScaleType.FIT_XY);
        img.setOnClickListener(OnClickImageView1);
        cache[i][j] = img;
        cont++;
        }
    }

    for (int i = 0; i < mImageNum.length; i++) {
        int x = mImageNum[i] / levalNow;
        int y = mImageNum[i] % levalNow;
        int x1 = i / levalNow;
        int y1 = i % levalNow;
        mImages[x1][y1] = cache[x][y];
    }
    }

    private android.view.View.OnClickListener OnClickImageView1 = new ImageView.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (clickNum == 0) {// 即需要交换的第一个图片
        for (int i = 0; i < mImages.length; i++) {
            boolean f = false;
            for (int j = 0; j < mImages[i].length; j++) {
            ImageView imgg = mImages[i][j];
            if (imgg == v) {
                x = i;
                y = j;
                clickNum++;
                f = true;
                break;
            }
            }
            if (f) {
            break;
            }
        }
        } else {// 即需要交换的第二个图片
        for (int i = 0; i < mImages.length; i++) {
            for (int j = 0; j < mImages[i].length; j++) {
            ImageView imgg = mImages[i][j];
            if (imgg == v) {
                if (clickNum == 1) {
                changePosition(i, j, x, y);
                x = 0;
                y = 0;
                clickNum = 0;
                }
            }
            }
        }
        }
    }
    };

    private void changePosition(int x1, int y1, int x2, int y2) {
    // 判断宽和高差的绝对值是否是1如果是1交换不是提示用户
    if (Math.abs(x1 - x2) + Math.abs(y1 - y2) != 1) {
        Builder bul = new AlertDialog.Builder(this);
        bul.setTitle(R.string.dialog);
        bul.setMessage(R.string.cannot_change);
        bul.setPositiveButton(R.string.yes, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
        }).show();
    } else {
        String str = "";
        ImageView bitF = null;
        bitF = mImages[x1][y1];
        mImages[x1][y1] = mImages[x2][y2];
        mImages[x2][y2] = bitF;

        for (int i = 0; i < mImages.length; i++) {
        for (int j = 0; j < mImages[i].length; j++) {
            ImageView img = mImages[i][j];
            // 得到imageview的父控件
            LinearLayout pa = (LinearLayout) img.getParent();
            // 在移除imageview使其父控件没有
            pa.removeView(img);
        }
        }

        setLayout();

        for (int i = 0; i < mImages.length; i++) {
        for (int j = 0; j < mImages[i].length; j++) {
            str += mImages[i][j].getId();
        }
        }

        switch (levalNow) {
        case 2:
        if (str.equals("1324")) {
            this.success();
        }
        break;
        case 3:
        if (str.equals("147258369")) {
            this.success();
        }
        break;
        case 4:
        if (str.equals("15913261014371115481216")) {
            this.success();
        }
        break;
        case 5:
        if (str.equals("16111621271217223813182349141924510152025")) {
            this.success();
        }
        break;
        }

    }
    }

    public void success() {

    Builder bul = new AlertDialog.Builder(this);
    bul.setTitle(R.string.dialog);
    bul.setMessage(R.string.congratulation);
    bul.setPositiveButton(R.string.restart, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(PictureDemo.this, PictureDemo.class);
        PictureDemo.this.startActivity(intent);
        finish();
        }
    });
    bul.setNegativeButton(R.string.quit, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
        finish();
        }
    });
    bul.show();

    }

    RadioButton r;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.change_leval:
        changeLeval();
        break;
    case R.id.rechoose:
        setBitmap();
        setImage();
        break;
    case R.id.quit:
        PictureDemo.this.finish();
        break;
    }

    return super.onOptionsItemSelected(item);
    }

    public void changeLeval() {
    AlertDialog.Builder build = new Builder(PictureDemo.this);
    build.setTitle(R.string.leval);
    LayoutInflater inflater = LayoutInflater.from(PictureDemo.this);
    final RadioGroup view = (RadioGroup) inflater.inflate(
        R.layout.leval_dialog, null);

    view.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
        r = (RadioButton) view.findViewById(checkedId);

        switch (checkedId) {
        case R.id.leval1:
            r.setChecked(true);
            levalNow = 3;
            break;
        case R.id.leval2:
            r.setChecked(true);
            levalNow = 4;
            break;
        case R.id.leval3:
            levalNow = 5;
            r.setChecked(true);
            break;
        }

        }

    });

    switch (levalNow) {
    case 3:
        r = (RadioButton) view.findViewById(R.id.leval1);
        r.setChecked(true);
        break;
    case 4:
        r = (RadioButton) view.findViewById(R.id.leval2);
        r.setChecked(true);
        break;
    case 5:
        r = (RadioButton) view.findViewById(R.id.leval3);
        r.setChecked(true);
        break;
    }

    build.setNeutralButton(R.string.yes, new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        setImage();
        edit.putInt("LEVAL", levalNow);
        ();
        }
    });
    build.setNegativeButton(R.string.cancel, null);
    build.setView(view);
    build.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // 加载menu
    getMenuInflater().inflate(R.menu.my_menu, menu);

    return true;
    }

    /**
     * @see 获取资源文件中的图片,节省内存的方法
     * @param r
     * @param resId
     * @return
     */
    public static Bitmap readBitmap(Resources r, int resId) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.RGB_565;
    opt.inPurgeable = true;
    opt.inInputShareable = true;
    // 获取资源图片
/*    InputStream is = r.openRawResource(resId);
    return BitmapFactory.decodeStream(is, null, opt);*/            //获取内部图片
    return BitmapFactory.decodeFile("/sdcard/camera1.jpg", opt);   //获取照相机拍照的照片
   
    }

}
也可以加我的QQ:624800258,我贴出来的是游戏的主要代码
搜索更多相关主题的帖子: 拼图游戏 android package import 
2011-10-05 13:44
kidangel666
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:93
专家分:139
注 册:2010-9-15
得分:0 
我需要的是每一句的解释
2011-10-05 13:45



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-351619-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.025094 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved