关闭

Android骰子游戏案例

标签: 骰子游戏android游戏
1674人阅读 评论(0) 收藏 举报
分类:

终于等到上班了(转行业真不容易,泪奔),带我的学长布置的第一个任务是做一个骰子的小游戏~~~~好吧,貌似不太难,我把写好的源码拿上来给大家分享下~

可以通过点击按钮或者摇一摇来改变骰子的点数~游戏里有个小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

<LinearLayout 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"
    android:orientation="vertical"
>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <com.syxy.dice.MySurfaceView
            android:id="@+id/view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

	<LinearLayout android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_centerInParent="true"
	    android:orientation="horizontal">     
        <Button
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Play" />

        <Button
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="reset" />
	</LinearLayout>   
    </RelativeLayout>

</LinearLayout>


完了,你们自己看去吧


对了,源码在这:http://download.csdn.net/detail/lxtalx/6650763


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30248次
    • 积分:486
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:4篇
    • 译文:0篇
    • 评论:3条
    最新评论