筆者最近開始淪陷於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() {@Overridepublic 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;}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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() {@Overridepublic void run() {// TODO Auto-generated method stubif (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 {@Overridepublic void run() {// TODO Auto-generated method stubgetquestion 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; // 題號重設為1wr = 0; // 答錯重設tr = 0; // 答對重設InitialQNum(); // 重新抽取隨機數組為題目序列progressBarValue = 0; // 將時間進度重設為0Toast.makeText(GameActivity1.this, "恭喜你進入第" + statenum + "關!", 0).show();new Thread(new StartGame()).start();timer = null;timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif (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; // 重設題號為1wr = 0;tr = 0;progressBarValue = 0;InitialQNum();timer = null;timer = new Timer(true);timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif (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() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubOVERTIME = false; // 設定為不逾時new RestartGame().restart();}});builder.setNegativeButton("主介面",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubGameActivity1.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() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubnew RestartGame().restart();}});builder.setNegativeButton("主介面",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubGameActivity1.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() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubGameActivity1.this.finish();}});builder.setCancelable(false);Dialog dialog = builder.create();dialog.show();}@Overridepublic void onBackPressed() { // 按返回鍵時觸發事件// TODO Auto-generated method stubsuper.onBackPressed();timer.cancel(); // 將時鐘取消共置空timer = null;GameActivity1.this.finish();}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (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;}}}