Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android骰子游戲案例

Android骰子游戲案例

編輯:關於Android編程

終於等到上班了(轉行業真不容易,淚奔),帶我的學長布置的第一個任務是做一個骰子的小游戲~~~~好吧,貌似不太難,我把寫好的源碼拿上來給大家分享下~

可以通過點擊按鈕或者搖一搖來改變骰子的點數~游戲裡有個小BUG,是因為一個參數的問題,我沒改,大家自己去發現吧~

既然是骰子游戲,肯定得有骰子類,按照一貫的慣例,注釋的很詳細,自己看去吧~

package com.syxy.dice;

import java.util.Random;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class Dice {
	private Bitmap diceBitmap;		//骰子的圖片引用
	private Bitmap tempBitmap;		//骰子的臨時引用
	int diceWidth;		//骰子的寬(6個面的骰子在一張圖上畫)
	int diceHeight;		//骰子的高
	int avgWidth;		//骰子圖片的平均寬度
//	int x, y;		//骰子顯示的坐標
	private int nowNum;		//骰子的當前值
	private Random random;		//獲取隨即對象
	Paint paint;		//畫筆的引用
	
	public Dice(Resources res){
		paint = new Paint();
		paint.setAntiAlias(true);	//消除畫筆的鋸齒
		initBitmap(res);		//初始化骰子圖片
		diceWidth = diceBitmap.getWidth();		//初始化圖片寬度
		diceHeight = diceBitmap.getHeight();		//初始化圖片高度
		avgWidth = diceWidth / 6;		//初始化平均寬度
		nowNum = -1;
		random = new Random();
		System.out.println("diceWidth=" + diceWidth +", diceHeight" + diceHeight + ", avgWidth" + avgWidth);
//		x = MySurfaceView.screen_width/2 - avgWidth/2;	
//		y = MySurfaceView.screen_height/3 - diceHeight/2;
	}
	
	public void initBitmap(Resources res){
		diceBitmap = BitmapFactory.decodeResource(res, R.drawable.dice);
	}
	
	 private Bitmap getbitmap()	{	        //根據序號截取大圖上相應骰子數圖片
		  return Bitmap.createBitmap(diceBitmap, avgWidth*(nowNum+1), 0, avgWidth, diceHeight);
	  }
	
	public void playDice(Canvas canvas, int x, int y){		//隨即繪制骰子
		nowNum = random.nextInt(5);	
		tempBitmap = getbitmap();
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(tempBitmap, x, y, paint);
	}
	
	public void DrawDice(Canvas canvas, int x, int y){		//繪制一個固定的骰子,即值為1的骰子,在投骰子的游戲開始前繪制
		tempBitmap = getbitmap();
		canvas.drawColor(Color.WHITE);
		System.out.println("----------------1-----------------");
		canvas.drawBitmap(tempBitmap,x, y, paint);
	}
}


既然是游戲,那麼游戲的視圖類總得有的~

package com.syxy.dice;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements Callback, Runnable {

	static int screen_width;		//設備屏幕的寬
	static int screen_height;		//設備屏幕的高
	int Dice_x;
	int Dice_y;
	SurfaceHolder holder;	//取得surfaceView的控制類的引用
	Thread th;		//取得線程類的引用
	boolean flag;		//線程執行的標志位
	boolean isRun;		//控制骰子的投擲
	Canvas canvas = null;
	Dice dice;	//骰子的引用
	private int sleepSpan = 150;		//線程休眠時間30
	int i;		//用於循環的
	Handler mHandler;
	
	public MySurfaceView(Context context,  AttributeSet attr) {
		super(context, attr);
		dice  = new Dice(this.getResources());
		holder = this.getHolder();		//取得控制類
		holder.addCallback(this);		//取得surfaceView的監視器
		th = new Thread(this);		//實例化線程
		// TODO Auto-generated constructor stub
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		screen_width = this.getWidth();		//取得屏幕寬度
		screen_height = this.getHeight();	//取得屏幕高度
		Dice_x =(int)screen_width/2 - (int)dice.avgWidth/2;		//計算骰子的X位置
		Dice_y =(int)screen_height/3 - (int)dice.diceHeight/2;		//計算骰子的Y位置
//		Dice_x = 300;
//		Dice_y =200;
		System.out.println("screen_width=" + screen_width + ", screen_height=" + screen_height + ", Dice_x=" + Dice_x + ", Dice_y=" + Dice_y);
		flag = true;	//給flag設置初始值
		th.start();	//啟動線程
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
	}	
	
	public void run(){	
		while(flag){
			if(isRun){	//用判斷語句控制是否進入骰子的投擲過程
				for(i = 1; i <= 10; i++){		//隨機取骰子值10次,完成投擲,建立此循環的目的是為了讓線程持續執行,讓投擲可控,
					canvas = holder.lockCanvas();		//取得surfaceView的canvas	
					dice.playDice(canvas, Dice_x, Dice_y);	//隨機投擲骰子
					if(canvas != null){
						holder.unlockCanvasAndPost(canvas);	//釋放holder的畫布
					}
				}
				isRun = false;
			}
		}
		try{
			Thread.sleep(sleepSpan);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

那麼我還需要一個主界面控制一下~

package com.syxy.dice;

import android.app.Activity;
import android.app.Service;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener,
	SensorEventListener{

	Button play, reset;
	MySurfaceView view;
	Dice dice;
	Canvas canvas;
	
	SensorManager sensorManager = null;		//傳感器管理器
	Vibrator vibrator = null;		//振動傳感器
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);		//取得傳感器管理器的實例
		vibrator = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
		
	    view = (MySurfaceView)findViewById(R.id.view);
		dice = new Dice(getResources());
		play = (Button)findViewById(R.id.play);
		reset = (Button)findViewById(R.id.reset);
		canvas = new Canvas();
		
		play.setOnClickListener(this);
		reset.setOnClickListener(this);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.out.println("-----10-----");
		sensorManager.unregisterListener(this);
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("-----11-----");
		sensorManager.registerListener(this, 
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
				SensorManager.SENSOR_DELAY_NORMAL);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == play){
			view.i = 1;
			view.isRun = true;
		}else if(v == reset){
			canvas = view.holder.lockCanvas();
			dice.DrawDice(canvas, view.Dice_x, view.Dice_y);
			view.holder.unlockCanvasAndPost(canvas);
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		System.out.println("-----12-----");
		int sensorType = event.sensor.getType();		//得到傳感器的類型
		//values的值,values[0]:X軸,values[1]:Y軸,values[2]:Z軸  
		System.out.println("-----13-----");
		float[] values = event.values;
		System.out.println("-----14-----");
		if(sensorType == Sensor.TYPE_ACCELEROMETER){		//如果傳感器類型是加速度計
			System.out.println("-----15-----");
			if(Math.abs(values[0])> 10
					|| Math.abs(values[1]) > 10
					|| Math.abs(values[2] )> 10){
				System.out.println("-----16-----");
				vibrator.vibrate(300);
				view.isRun = true;
				System.out.println("-----搖一搖-----");
			}
		}
	}
}


然後是主界面的界面XML



    

        

	     
        


完了,你們自己看去吧


對了,源碼在這:http://download.csdn.net/detail/lxtalx/6650763


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved