android簡單的答題遊戲

筆者最近開始淪陷於android,從開始入門到現在已經快半個月的時間,於是便寫一個較綜合,用到瞭數據庫,多線程操作,以及時鐘的添加和停止消除,activity之間的動畫轉換等,適用於初學者學以致用的小遊戲來鞏固自己的知識,有需要的讀者可以去我的資源庫中下載源碼。

   以下是主遊戲程序的部分代碼,帶有筆者的豐富註釋:

 

 

package com.example.pingping_game1;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.example.pingping_game1.Tools.JudgeAnswer;
import com.example.pingping_game1.Tools.MakeIntToString;
import com.example.pingping_game1.getsqldatabase.getquestion;
import com.example.pingping_game1.getsqldatabase.getsqldatabase;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.text.style.BulletSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity1 extends Activity implements OnClickListener {

	public GameActivity1() {
		// TODO Auto-generated constructor stub
	}

	private TextView stateView, stateprogressView, questionView; // 各種狀態信息
	private Button aswA, aswB, aswC, aswD; // 4個答案選項按鈕
	private ProgressBar timeprogress; // 時間進度條
	private int wr = 0; // 答錯的題數
	private int tr = 0; // 答對的題數
	private int qnumber = 1; // 當前題目的題號
	private int statenum = 1; // 當前關數
	private final static int sum = 5; // 總共需要答對的題數
	private final static int wrsum = 3; // 總共可答錯的次數
	private final static int LASTSTATE = 2; // 最終關數
	private final static int CHANGE_QUESTION = 1; // 變換遊戲界面題目的標識符
	private final static int SETPROGRESS = 2; // 表示設置時間進度條的標識符
	private final static int RESTARTGAME = 3; // 重新開始遊戲的標識符
	private static boolean OVERTIME = false; // 是否已經超時標識符
	// 用mainMap來存儲該題對應的信息
	private Map<String, String> mainMap = new HashMap<String, String>();
	private boolean flag = false; // 此題是否答對
	private int progressBarValue = 0; // 表示時間進度條的進度
	private final static int TOTALPROGRESS = 30; // 設置時間進度條的最大值
	private Timer timer; // 設置一個定時器
	private Random random = new Random(); // 設置一個隨機數來隨機抽取題目
	private int[] QuestionNum = new int[8]; // 每一關題目的序列號

	// 用線程和handler來處理消息
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CHANGE_QUESTION:
				mainMap = (Map<String, String>) msg.obj;
				stateView.setText("第" + statenum + "關");
				stateprogressView.setText(tr + "/" + sum + "\n" + wr + "/"
						+ wrsum);
				questionView.setText(qnumber + ":" + mainMap.get("questions"));
				aswA.setText("A." + mainMap.get("a"));
				aswB.setText("B." + mainMap.get("b"));
				aswC.setText("C." + mainMap.get("c"));
				aswD.setText("D." + mainMap.get("d"));
				break;
			case SETPROGRESS:
				int progress = (Integer) msg.obj;
				timeprogress.setProgress(progress);
				break;
			case RESTARTGAME:
				timer.cancel();
				OVERTIME = true; // 設置為超時
				new ShowTimeOverDialog().showdialog();
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ggg);
		stateView = (TextView) this.findViewById(R.id.statetext);
		stateprogressView = (TextView) this.findViewById(R.id.stateprogress);
		questionView = (TextView) this.findViewById(R.id.questiontext);
		aswA = (Button) this.findViewById(R.id.aswA);
		aswA.setAlpha((float) 0.5);
		aswA.setOnClickListener(this);
		aswB = (Button) this.findViewById(R.id.aswB);
		aswB.setAlpha((float) 0.5);
		aswB.setOnClickListener(this);
		aswC = (Button) this.findViewById(R.id.aswC);
		aswC.setAlpha((float) 0.5);
		aswC.setOnClickListener(this);
		aswD = (Button) this.findViewById(R.id.aswD);
		aswD.setAlpha((float) 0.5);
		aswD.setOnClickListener(this);
		timeprogress = (ProgressBar) this.findViewById(R.id.progressBar1);
		timeprogress.setMax(TOTALPROGRESS);
		InitialQNum(); // 初始化題號序列數組
		new Thread(new StartGame()).start();
		timer = new Timer(true);
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (progressBarValue == TOTALPROGRESS) {
					// 超出遊戲時間,彈出對話框提示玩傢
					handler.sendEmptyMessage(RESTARTGAME);
				} else {
					// 將信息傳送給handler來更新進度條
					Message message = Message.obtain();
					message.obj = progressBarValue;
					message.what = SETPROGRESS;
					handler.sendMessage(message);
					// 時間進度自增
					progressBarValue++;
				}
			}
		}, 0, 1000);
	}

	// 初始化QuestionNum數組,隨機抽取
	private void InitialQNum() {
		int count = 0;
		while (count < 8) {
			boolean flag1 = true; // 標志是否重復
			int cur = Math.abs(random.nextInt() % 8) + 1;
			for (int i = 0; i < count; i++) {
				if (cur == QuestionNum[i]) {
					flag1 = false;
					break;
				}
			}
			if (flag1) {
				QuestionNum[count] = cur;
				count++;
			}
		}
	}

	public class StartGame implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			getquestion getq = new getquestion(GameActivity1.this);
			Map<String, String> map = new HashMap<String, String>();
			// 用MakeIntToString工具類來轉換字符,並選擇對應題目
			String str = MakeIntToString.getString(QuestionNum[qnumber - 1]
					+ (statenum - 1) * 8);
			String str1 = String.valueOf(statenum);
			String[] strs = new String[] { str, str1 };
			map = getq.getquestionMap(strs);
			// 用message來向主線程傳遞信息並處理
			Message message = Message.obtain();
			message.obj = map; // 將map信息放入message中
			message.what = CHANGE_QUESTION; // 設定message的標示符
			handler.sendMessage(message); // 向主線程中的handler發送信息
		}

	}

	// 遊戲進入下一關
	private void GoToNextState() {
		if (OVERTIME) {
			return;
		}
		timer.cancel(); // 關閉時鐘
		statenum++; // 關數自增
		qnumber = 1; // 題號重置為1
		wr = 0; // 答錯重置
		tr = 0; // 答對重置
		InitialQNum(); // 重新抽取隨機數組為題目序列
		progressBarValue = 0; // 將時間進度重置為0
		Toast.makeText(GameActivity1.this, "恭喜你進入第" + statenum + "關!", 0)
				.show();
		new Thread(new StartGame()).start();
		timer = null;
		timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (progressBarValue == TOTALPROGRESS) {
					// 超出遊戲時間,彈出對話框提示玩傢
					handler.sendEmptyMessage(RESTARTGAME);
				} else {
					// 將信息傳送給handler來更新進度條
					Message message = Message.obtain();
					message.obj = progressBarValue;
					message.what = SETPROGRESS;
					handler.sendMessage(message);
					// 時間進度自增
					progressBarValue++;
				}
			}
		}, 0, 1000);
	}

	// 重新開始遊戲
	private class RestartGame {
		public RestartGame() {

		}

		public void restart() {
			statenum = 1;
			qnumber = 1; // 重置題號為1
			wr = 0;
			tr = 0;
			progressBarValue = 0;
			InitialQNum();
			timer = null;
			timer = new Timer(true);
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (progressBarValue == TOTALPROGRESS) {
						// 超出遊戲時間,彈出對話框提示玩傢
						handler.sendEmptyMessage(RESTARTGAME);
					} else {
						// 將信息傳送給handler來更新進度條
						Message message = Message.obtain();
						message.obj = progressBarValue;
						message.what = SETPROGRESS;
						handler.sendMessage(message);
						// 時間進度自增
						progressBarValue++;
					}
				}
			}, 0, 1000);
			new Thread(new StartGame()).start();
		}
	}

	// 遊戲超時彈出對話框
	public class ShowTimeOverDialog {
		public ShowTimeOverDialog() {

		}

		public void showdialog() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					GameActivity1.this);
			builder.setTitle("提示");
			builder.setMessage("對不起,你的智商太低,沒有在規定時間內完成答題!");
			builder.setPositiveButton("重新開始",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							OVERTIME = false; // 設置為不超時
							new RestartGame().restart();
						}
					});
			builder.setNegativeButton("主界面",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							GameActivity1.this.finish();
						}
					});
			builder.setCancelable(false);
			Dialog dialog = builder.create();
			dialog.show();

		}
	}

	// 遊戲失敗時彈出的對話框
	public class ShowGameOverDialog {

		public ShowGameOverDialog() {

		}

		public void showdialog() {
			timer.cancel();
			AlertDialog.Builder builder = new AlertDialog.Builder(
					GameActivity1.this);
			builder.setTitle("提示");
			builder.setMessage("對不起,愚蠢的人類,你闖關失敗瞭!");
			builder.setPositiveButton("重新闖關",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							new RestartGame().restart();
						}
					});
			builder.setNegativeButton("主界面",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							GameActivity1.this.finish();
						}
					});
			builder.setCancelable(false);
			Dialog dialog = builder.create();
			dialog.show();
		}
	}

	private void GoOverGame() {
		if (OVERTIME) {
			return;
		}
		timer.cancel();
		AlertDialog.Builder builder = new AlertDialog.Builder(
				GameActivity1.this);
		builder.setTitle("提示");
		builder.setMessage("恭喜您通關!!~您的智商真是高!");
		builder.setPositiveButton("謙讓謙讓",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						GameActivity1.this.finish();
					}
				});
		builder.setCancelable(false);
		Dialog dialog = builder.create();
		dialog.show();
	}

	@Override
	public void onBackPressed() { // 按返回鍵時觸發事件
		// TODO Auto-generated method stub
		super.onBackPressed();
		timer.cancel(); // 將時鐘取消並置空
		timer = null;
		GameActivity1.this.finish();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.aswA:
			// 返回當前是否答對
			flag = new JudgeAnswer(GameActivity1.this).judgeit("a", mainMap);
			if (flag) { // 如果答對,對應參數進行改變
				tr++;
				qnumber++;
				if (tr == sum) {
					if (statenum == LASTSTATE) {
						GoOverGame();
					} else {
						GoToNextState();
					}
				} else {
					new Thread(new StartGame()).start();
				}
			} else {
				wr++;
				qnumber++;
				if (wr == wrsum) { // 當錯誤題量達到上限,彈出遊戲結束對話框
					new ShowGameOverDialog().showdialog();
				} else { // 否則更換題目
					new Thread(new StartGame()).start();
				}
			}
			break;
		case R.id.aswB:
			flag = new JudgeAnswer(GameActivity1.this).judgeit("b", mainMap);
			if (flag) {
				tr++;
				qnumber++;
				if (tr == sum) {
					if (statenum == LASTSTATE) {
						GoOverGame();
					} else {
						GoToNextState();
					}
				} else {
					new Thread(new StartGame()).start();
				}
			} else {
				wr++;
				qnumber++;
				if (wr == wrsum) {
					new ShowGameOverDialog().showdialog();
				} else {
					new Thread(new StartGame()).start();
				}
			}
			break;
		case R.id.aswC:
			flag = new JudgeAnswer(GameActivity1.this).judgeit("c", mainMap);
			if (flag) {
				tr++;
				qnumber++;
				if (tr == sum) {
					if (statenum == LASTSTATE) {
						GoOverGame();
					} else {
						GoToNextState();
					}
				} else {
					new Thread(new StartGame()).start();
				}
			} else {
				wr++;
				qnumber++;
				if (wr == wrsum) {
					new ShowGameOverDialog().showdialog();
				} else {
					new Thread(new StartGame()).start();
				}
			}
			break;
		case R.id.aswD:
			flag = new JudgeAnswer(GameActivity1.this).judgeit("d", mainMap);
			if (flag) {
				tr++;
				qnumber++;
				if (tr == sum) {
					if (statenum == LASTSTATE) {
						GoOverGame();
					} else {
						GoToNextState();
					}
				} else {
					new Thread(new StartGame()).start();
				}
			} else {
				wr++;
				qnumber++;
				if (wr == wrsum) {
					new ShowGameOverDialog().showdialog();
				} else {
					new Thread(new StartGame()).start();
				}
			}
			break;
		}
	}
}

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *