安卓的拼图游戏(二)

表示已经做完了整个程序,感觉收获还是很多的。。对着视频敲代码也发生了很多的错   误,但是对于时间的控制和RelativeLayout的自控件的使用也有了了解,觉得还不错。

MainActivity

package com.innoc.game.pintu;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.TextView;

import com.example.first.R;
import com.innoc.game.view.GamepintuLayout;
import com.innoc.game.view.GamepintuLayout.GamepintuListener;

public class MainActivity extends Activity {

    
    
    
    
    private GamepintuLayout mgamepintuLayout;
    private TextView mlevel;
    private TextView mtime;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mlevel=(TextView) findViewById(R.id.id_level);
        mtime=(TextView) findViewById(R.id.id_time);
       
     
        
        mgamepintuLayout=(GamepintuLayout) findViewById(R.id.id_gamepintu);
        /*
         * 先定义下才能去引用,操蛋改了一个小时竟然
         */
        
        mgamepintuLayout.setTimeEnabled(true);
        mgamepintuLayout.setOnGamepintuListener(new GamepintuListener()
        {

			@Override
			public void nextLevel(final int nextlevel) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(MainActivity.this).setTitle("GameInfo").setMessage("level up")
				.setPositiveButton("NEXT Level", new OnClickListener()
				{

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						mgamepintuLayout.nextLevel();
						//System.out.println("GGGGGGGGGGG"+nextlevel);
						 mlevel.setText(""+nextlevel);
					} 
					
				}).show();
			}

			@Override
			public void timechanged(int currentTime) {
				// TODO Auto-generated method stub
				mtime.setText(""+currentTime);
			}

			@Override
			public void gameover() {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(MainActivity.this).setTitle("GameInfo").setMessage("Game Over")
				.setPositiveButton("RESTART", new OnClickListener()
				{

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						
						mgamepintuLayout.restart();
						
						
						//mgamepintuLayout.nextLevel();
					}
					
				}).setNegativeButton("QUIT", new OnClickListener()
						{

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								finish();
							}
					
						}
				).show();
			}
        	
        });
        
    }
      protected void onPause()
      {
    	  super.onPause();
    	  mgamepintuLayout.pause();
      }
      protected void onResume()
      {
    	  super.onResume();
    	  mgamepintuLayout.resume();
      }

   
    
}

gameLayout:


package com.innoc.game.view;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.LogRecord;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.first.R;
import com.innoc.game.utils.ImagePiece;
import com.innoc.game.utils.ImageSpiltterUtil;

/**
 * 
 * @author YangPeiLin 0 1 2 3 4 5 6 7 8
 * 
 * 
 * 
 */

public class GamepintuLayout extends RelativeLayout implements OnClickListener {

	

	private int mColumn = 3;

	/*
	 * 游戏面板的宽度
	 */
	private int mWidth;
	/*
	 * 这个接口的功能包括游戏结束,下一关,改变时间
	 */

	private boolean isGameSuccess;
	private boolean isGameOver;

	public interface GamepintuListener {
		void nextLevel(int nextlevel);

		void timechanged(int currentTime);

		void gameover();

	}

	private static final int TIME_CHANGED = 0x110;
	private static final int NEXT_LEVEL = 0x111;

	/*
	 * 
	 * 设置接口回调
	 */
	public GamepintuListener mListener;

	public void setOnGamepintuListener(GamepintuListener mListener) {
		this.mListener = mListener;
	}

	private int level=1;

	private Handler mhandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIME_CHANGED:
				if (isGameSuccess || isGameOver||isPause)
					return;
				if (mListener != null) {
					mListener.timechanged(mtime);
					if (mtime == 0) {
						isGameOver = true;
						mListener.gameover();
						return;
					}

				}

				mtime--;
				mhandler.sendEmptyMessageDelayed(TIME_CHANGED, 1000);

				break;
			case NEXT_LEVEL:

				//System.out.println("GGPPPPPPPPG"+level);
				level = level + 1;
               // System.out.println("RRRRRRRRRR"+level);	             
				if (mListener != null) {
               //    System.out.println("TTTTTTTTT"+level);
					mListener.nextLevel(level);
				} else {
					nextLevel();
				}

				break;
			default:
				break;
			}
		};

	};

	/*
	 * 
	 * 设置开始时间
	 */
	private boolean isTimeEnabled = false;
	public boolean isTimeEnabled() {
		return isTimeEnabled;
	}

	public void setTimeEnabled(boolean isTimeEnabled) {
		//System.out.println("TTTTTTTTTTTTTTTTTTTGGGGGG");
		this.isTimeEnabled = isTimeEnabled;
	}

	private int mtime;// 还有多少时间
   

	
	
	/*
	 * 容器的内边距
	 */
	private int mPadding;
	/*
	 * 
	 * 每张小图之间的距离 (heng,zong) dp
	 */
	private int mMargin = 3;

	private List<ImageView> mItems = new ArrayList<ImageView>();
	private ImageView[] mGamepintuItems;

	private int mItemWidth;

	/*
	 * 游戏的拼图
	 */
	private Bitmap mBitmap;

	private List<ImagePiece> mItemBitmaps;

	private boolean once;

	public GamepintuLayout(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public GamepintuLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public GamepintuLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		init();

	}

	private void init() {
		// TODO Auto-generated method stub
		mMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				3, getResources().getDisplayMetrics());

		/*
		 * 将sp换成dp,尽量不使用px
		 */
		mPadding = min(getPaddingLeft(), getPaddingRight(), getPaddingTop(),
				getPaddingBottom());

	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 取宽和高中的最小值
		mWidth = Math.min(getMeasuredHeight(), getMeasuredWidth());
		if (!once) {
			// 进行切图,和排序
			initBitmap();
			// 设置item的宽高属性
			initItem();
			/*
			 * 
			 * 根据关卡设置时间
			 */
			CheckTimeEnabled();

			once = true;
		}
		// 设置为正方形
		setMeasuredDimension(mWidth, mWidth);

	}

	private void CheckTimeEnabled() {
		if (isTimeEnabled) {
			// 根据当前等级计算时间
			countTimeBaseLevel();
			mhandler.sendEmptyMessage(TIME_CHANGED);
		}

	}

	private void countTimeBaseLevel() {

		mtime = (int) (Math.pow(2, level) * 60);

	}

	// 进行切图,和排序
	private void initBitmap() {
		// TODO Auto-generated method stub
		if (mBitmap == null) {
			mBitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.image);
		}

		mItemBitmaps = ImageSpiltterUtil.splitImage(mBitmap, mColumn);

		// 使用sort乱序
		Collections.sort(mItemBitmaps, new Comparator<ImagePiece>() {
			@Override
			public int compare(ImagePiece a, ImagePiece b) {

				return Math.random() > 0.5 ? 1 : -1;
			}
		});

	}

	// 设置ImageView(item)的宽高属性
	private void initItem() {
		// TODO Auto-generated method stub
		mItemWidth = (mWidth - mPadding * 2 - mMargin * (mColumn - 1))
				/ mColumn;

		mGamepintuItems = new ImageView[mColumn * mColumn];

		for (int i = 0; i < mGamepintuItems.length; i++) {
			ImageView item = new ImageView(getContext());
			item.setOnClickListener(this);
			item.setImageBitmap(mItemBitmaps.get(i).getBitmap());
			mGamepintuItems[i] = item;
			item.setId(i + 1);
			// 在item的tag中存储了index,index是真正的顺序
			item.setTag(i + "_" + mItemBitmaps.get(i).getIndex());

			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
					mItemWidth, mItemWidth);

			// 设置item间横向间隙,通过rightMargin
			// 不是最后一列

			if ((i + 1) % mColumn != 0) {
				lp.rightMargin = mMargin;
			}
			// 不是第一列
			if (i % mColumn != 0) {
				lp.addRule(RelativeLayout.RIGHT_OF,
						mGamepintuItems[i - 1].getId());
			}
			// 如果不是第一行
			if ((i + 1) > mColumn) {
				lp.topMargin = mMargin;
				lp.addRule(RelativeLayout.BELOW,
						mGamepintuItems[i - mColumn].getId());
			}
			addView(item, lp);

		}

	}

	/*
	 * 
	 * 获取多个参数的最小值
	 */
	private int min(int... params) {

		int min = params[0];
		for (int param : params) {
			if (param < min) {
				min = param;
			}

		}

		return min;
	}

	private ImageView mFirst;
	private ImageView mSecond;

	private boolean isAniming;

	@Override
	public void onClick(View v) {

		/*
		 * 
		 * 
		 * 防止正在动画的时候用户还在敲。。
		 */
		if (isAniming)
			return;
		// 两次点击同一个item
		if (mFirst == v) {
			mFirst.setColorFilter(null);
			mFirst = null;
			return;
		}

		if (mFirst == null) {

			mFirst = (ImageView) v;
			mFirst.setColorFilter(Color.parseColor("#55FF0000"));
		} else {
			/* 交换我们的item */
			mSecond = (ImageView) v;
			exchangeView();
		}

	}

	private void exchangeView() {
		// TODO Auto-generated method stub

		mFirst.setColorFilter(null);

		setUpAnimaLayout();

		ImageView first = new ImageView(getContext());
		final Bitmap firstBitmap1 = mItemBitmaps.get(
				getImageIdByTag((String) mFirst.getTag())).getBitmap();
		first.setImageBitmap(firstBitmap1);
		RelativeLayout.LayoutParams lp = new LayoutParams(mItemWidth,
				mItemWidth);
		lp.leftMargin = mFirst.getLeft() - mPadding;
		lp.topMargin = mFirst.getTop() - mPadding;
		first.setLayoutParams(lp);
		mAnimLayout.addView(first);

		ImageView second = new ImageView(getContext());
		final Bitmap secondBitmap1 = mItemBitmaps.get(
				getImageIdByTag((String) mSecond.getTag())).getBitmap();
		second.setImageBitmap(secondBitmap1);
		RelativeLayout.LayoutParams lp2 = new LayoutParams(mItemWidth,
				mItemWidth);
		lp2.leftMargin = mSecond.getLeft() - mPadding;
		lp2.topMargin = mSecond.getTop() - mPadding;
		second.setLayoutParams(lp2);
		mAnimLayout.addView(second);

		TranslateAnimation anim = new TranslateAnimation(0, mSecond.getLeft()
				- mFirst.getLeft(), 0, mSecond.getTop() - mFirst.getTop());
		anim.setDuration(300);
		anim.setFillAfter(true);
		first.startAnimation(anim);

		TranslateAnimation Secondanim = new TranslateAnimation(0,
				-mSecond.getLeft() + mFirst.getLeft(), 0, -mSecond.getTop()
						+ mFirst.getTop());
		Secondanim.setDuration(300);
		Secondanim.setFillAfter(true);
		second.startAnimation(Secondanim);

		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub

				String firstTag = (String) mFirst.getTag();
				String secondTag = (String) mSecond.getTag();
				// String[]firstParams=firstTag.split("_");
				// String[]secondParams=secondTag.split("_");

				// Bitmap
				// firstBitmap=mItemBitmaps.get(Integer.parseInt(firstParams[0])).getBitmap();
				// Bitmap
				// secondBitmap=mItemBitmaps.get(Integer.parseInt(secondParams[0])).getBitmap();

				mFirst.setImageBitmap(secondBitmap1);
				mSecond.setImageBitmap(firstBitmap1);
				mFirst.setTag(secondTag);
				mSecond.setTag(firstTag);
				mFirst.setVisibility(View.VISIBLE);
				mSecond.setVisibility(View.VISIBLE);

				mAnimLayout.removeAllViews();
				mFirst = mSecond = null;
				CheckSuccess();
				isAniming = false;

			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub
				mFirst.setVisibility(View.INVISIBLE);
				mSecond.setVisibility(View.INVISIBLE);
				isAniming = true;

			}

		});

	}

	/*
	 * 
	 * 每次移动完成判断下是不是已经ok了。
	 */
	private void CheckSuccess() {

		boolean isSuccess = true;
		for (int i = 0; i < mGamepintuItems.length; i++) {

			ImageView imageView = mGamepintuItems[i];
			if (getImageIdIndex((String) imageView.getTag()) != i) {
				// System.out.println("getid  "+
				// getImageIdByTag((String)imageView.getTag())+"i  " +i);
				isSuccess = false;
			}

		}

		/* System.out.println("EEEEEEEEEEEE"+isSuccess); */

		if (isSuccess) {
			
			Log.e("TAG", "SUCCESS");
            isGameSuccess=true;
			
			mhandler.removeMessages(TIME_CHANGED);
			
			
			
			/* System.out.println("ETTTTTTTTTTTTE"); */
			Toast.makeText(getContext(), "Success !!! LEVER UP",
					Toast.LENGTH_LONG).show();

			/*
			 * Toast.makeText(getContext(), "默认Toast样式",
			 * Toast.LENGTH_SHORT).show();
			 */

			mhandler.sendEmptyMessage(NEXT_LEVEL);
		}

	}

	/*
	 * 动画层
	 */
	private RelativeLayout mAnimLayout;

	/*
	 * 
	 * 构造我们的动画层
	 */
	private void setUpAnimaLayout() {
		// TODO Auto-generated method stub

		if (mAnimLayout == null) {
			mAnimLayout = new RelativeLayout(getContext());
			addView(mAnimLayout);

		}

	}

	/*
	 * 根据tag取出id
	 */
	public int getImageIdByTag(String tag) {

		String[] spilt = tag.split("_");
		return Integer.parseInt(spilt[0]);

	}

	public int getImageIdIndex(String tag) {

		String[] spilt = tag.split("_");
		return Integer.parseInt(spilt[1]);

	}

	public void nextLevel() {
		this.removeAllViews();
		mAnimLayout = null;
		mColumn++;
	
		isGameSuccess = false;
		// check 下时间是不是要换了该
		CheckTimeEnabled();
		initBitmap();
		initItem();
	}
      
	public void restart()
	{
		isGameOver=false;
		mColumn--;
		nextLevel();
	}
	private boolean isPause;
	
	public void pause()
	{
		isPause=true;
		mhandler.removeMessages(TIME_CHANGED);
	}
    public void resume()
    {
    	if(isPause)
    	{
    		isPause=false;
    		mhandler.sendEmptyMessage(TIME_CHANGED);
    	}
    }
	
	 
}

最终的xml

activity.main.xmal

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    
    >

    <com.innoc.game.view.GamepintuLayout
        
        android:id="@+id/id_gamepintu"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:padding="3dp"
      />
         <RelativeLayout
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:layout_above="@id/id_gamepintu"
          android:layout_margin="3dp"        
          >
          <TextView 
           android:id="@+id/id_level"
           android:layout_height="70dp"
           android:layout_width="70dp"   
           android:gravity="center"
           android:padding="4dp" 
           android:background="@drawable/textbg"  
           android:textSize="30sp"
           android:textStyle="bold"
           android:textColor="#EA7821"
           android:text="1"   
           />       
           
          <TextView 
           android:id="@+id/id_time"
           android:layout_alignParentRight="true" 
           android:textSize="30sp"
           android:textStyle="bold"
           android:textColor="#EA7821"
           android:layout_height="70dp"
           android:layout_width="70dp"   
           android:gravity="center"
           android:padding="4dp" 
           android:text="120"
           android:background="@drawable/textbg"
           />
          
          
          </RelativeLayout>

</RelativeLayout>

textbg.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval"
    
    >
    <!-- 边框线 -->
    <stroke  android:width="2px"   
        android:color="#1579DB"/>
    <!-- 背景色 -->
    <solid android:color="#B4CDE6"></solid>
    
    

</shape>



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值