Home
2018年3月26日 星期一

[程式] Android Studio : Simple True False Game II

Android Studio : Simple True False Game II

簡單的益智問答遊戲第二版,整合了第一版Simple True False Quiz Game的主題,加上Simple High Score Screen排行榜(Leaderboard)的功能,另外結束遊戲是採用Simple Quiz Game的AlertDialog,相關網頁如下:


[程式] Android Studio : Simple True False Quiz Game
[程式] Android Studio : Simple Quiz Game
[程式] Android Studio : Simple High Score Screen


相關資訊圖片:

Simple True False Game II View1 (activity_main.xml)畫面
Simple True False Game II View1 (activity_main.xml)畫面


Simple True False Game II View2 (activity_best.xml)畫面
Simple True False Game II View2 (activity_best.xml)畫面


初始畫面
初始畫面


排行榜 與 結束畫面
排行榜 與 結束畫面


Source Code:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tw.idv.wenyen.simpletruefalsegameii.MainActivity">

    <Button
        android:id="@+id/b_false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="FALSE" />

    <Button
        android:id="@+id/b_ture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/b_false"
        android:layout_centerHorizontal="true"
        android:text="TRUE" />

    <TextView
        android:id="@+id/tv_question"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/b_ture"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="" />

</RelativeLayout>

activity_best.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:id="@+id/tv_score"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="" />

</LinearLayout>

MainActivity.java
package tw.idv.wenyen.simpletruefalsegameii;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    TextView tv_question;
    Button b_true, b_false;

    Questions mQuestions;
    int questionsLength;

ArrayList<Item> = questionsList; int currentQuestion = 0; boolean winner = false; int score = 0; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //init stuff tv_question = findViewById(R.id.tv_question); b_true = findViewById(R.id.b_ture); b_false = findViewById(R.id.b_false); mQuestions = new Questions(); questionsLength = mQuestions.mQuestions.length; Log.d(TAG, "questionsLength=" + questionsLength); questionsList = new ArrayList<>(); //save all the questions in the list for(int i = 0; i < questionsLength; i++) { questionsList.add(new Item(mQuestions.getQuestion(i), mQuestions.getAnswer(i))); Log.d(TAG, "questionsList[" + i + "," + mQuestions.getQuestion(i) + "," + mQuestions.getAnswer(i) + "]"); } //shuffle the questions Collections.shuffle(questionsList); //start the questions setQuestion(currentQuestion); b_true.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* if (checkQuestion(currentQuestion)) { //current - the game continues currentQuestion++; score++; if (currentQuestion < questionsLength) { setQuestion(currentQuestion); } else { //game over - winner winner = true; endGame(); } } else { //wrong - the game ends endGame(); }*/ Log.d(TAG, "currentQuestion True=" + currentQuestion); Log.d(TAG, "Answer = " + checkQuestion(currentQuestion)); // 若答案正確,就加 1 分 if (checkQuestion(currentQuestion)) { Log.d(TAG, "Answer=O"); score++; } // 下一題的號碼 currentQuestion++; // 若所有問題問完後,就結束遊戲,否則繼續遊戲 if (currentQuestion < questionsLength) { // 取得問題 setQuestion(currentQuestion); } else { // 題目已經問完,結束遊戲 endGame(); } Log.d(TAG, "score = " + score); } }); b_false.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* if (!checkQuestion(currentQuestion)) { //current - the game continues currentQuestion++; score++; if (currentQuestion < questionsLength) { setQuestion(currentQuestion); } else { //game over - winner winner = true; endGame(); } } else { //wrong - the game ends endGame(); }*/ Log.d(TAG, "currentQuestion False=" + currentQuestion); Log.d(TAG, "Answer = " + checkQuestion(currentQuestion)); // 若答案正確,就加 1 分 if (!checkQuestion(currentQuestion)) { Log.d(TAG, "Answer=O"); score++; } // 下一題的號碼 currentQuestion++; // 若所有問題問完後,就結束遊戲,否則繼續遊戲 if (currentQuestion < questionsLength) { // 取得問題 setQuestion(currentQuestion); } else { // 題目已經問完,結束遊戲 endGame(); } Log.d(TAG, "score = " + score); } }); } //show question on the screen private void setQuestion(int number) { Log.d(TAG, "setQuestion(int number)"); tv_question.setText(questionsList.get(number).getQuestion()); } //check if the answer is right private boolean checkQuestion(int number) { Log.d(TAG, "checkQuestion(int number)"); String answer = questionsList.get(number).getAnswer(); return answer.equals("true"); } //game over private void endGame() { Log.d(TAG, "endGame()"); /* if (winner) { Toast.makeText(this, "Game Over! You win!", Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(this, "Game Over! You lose!", Toast.LENGTH_SHORT).show(); finish(); }*/ //save score in SharedPreferences SharedPreferences preferences = getSharedPreferences("PREFS", 0); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("lastScore", score); editor.apply(); //go to BestActivity Intent intent = new Intent(getApplicationContext(), BestActivity.class); startActivity(intent); finish(); } }


BestActivity.java
package tw.idv.wenyen.simpletruefalsegameii;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
 * Created by kingbow on 2018/3/25.
 */

public class BestActivity extends AppCompatActivity {

    TextView tv_score;

    int lastScore;
    int best1, best2, best3;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_best);

        tv_score = findViewById(R.id.tv_score);

        // load old score
        SharedPreferences preferences = getSharedPreferences("PREFS", 0);
        lastScore = preferences.getInt("lastScore", 0);
        best1 = preferences.getInt("best1", 0);
        best2 = preferences.getInt("best2", 0);
        best3 = preferences.getInt("best3", 0);

        // replace if there is a high score
        // ex : init status
        // best1(5), best2(3), best3(1), lastScore(6)
        if (lastScore > best3) {
            best3 = lastScore;
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("best3", best3);
            editor.apply();
        }
        // best1(5), best2(3), best3(6), lastScore(6)
        if (lastScore > best2) {
            int temp = best2;
            best2 = lastScore;
            best3 = temp;
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("best3", best3);
            editor.putInt("best2", best2);
            editor.apply();
        }
        // best1(5), best2(6), best3(3), lastScore(6)
        if (lastScore > best1) {
            int temp = best1;
            best1 = lastScore;
            best2 = temp;
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("best2", best2);
            editor.putInt("best1", best1);
            editor.apply();
        }
        // final status
        // best1(6), best2(5), best3(3), lastScore(6)

        // display score
        tv_score.setText("LAST SCORE: " + lastScore + "\n" +
                "BEST1: " + best1 + "\n" +
                "BEST2: " + best2 + "\n" +
                "BEST3: " + best3);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BestActivity.this);
        alertDialogBuilder
                .setMessage("Game Over! Your score is " + lastScore + " Points.")
                .setCancelable(false)
                .setPositiveButton("New Game", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(getApplicationContext(), MainActivity.class));
                    }
                })
                .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    public void onBackPressed() {
        // go to MainActivity
        // 因為用了AlertDialog,因此將onBackPressed()取消
        // 有興趣的可以先不註解掉,看會有什麼狀況。
/* Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish();*/ } }

Item.java
package tw.idv.wenyen.simpletruefalsegameii;

/**
 * Created by kingbow on 2018/3/25.
 */

public class Item {

    private String question, answer;

    public Item(String question, String answer) {
        this.question = question;
        this.answer = answer;
    }

    public String getQuestion() {
        return question;
    }

    public String getAnswer() {
        return answer;
    }
}

Questions.java
package tw.idv.wenyen.simpletruefalsegameii;

/**
 * Created by kingbow on 2018/3/25.
 */

public class Questions {

    public String mQuestions[] = {
            "Mercury is the first planet in the Solar System",
            "Venus is the third planet in the Solar System",
            "Earth is the fourth planet in the Solar System",
            "Mars is the first planet in the Solar System",
            "Jupiter is the seventh planet in the Solar System",
            "Saturn is the fifth planet in the Solar System",
            "Uranus is the seventh planet in the Solar System",
            "Neptune is the eight planet in the Solar System",
            "Pluto is the ninth planet in the Solar System"
    };

    public String mAnswers[] = {
            "true",
            "false",
            "false",
            "false",
            "false",
            "false",
            "true",
            "true",
            "true"
    };

    public String getQuestion(int number) {
        return  mQuestions[number];
    };

    public String getAnswer(int number) {
        return  mAnswers[number];
    };
}


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tw.idv.wenyen.simpletruefalsegameii">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--新增activity-->
        <activity android:name=".BestActivity" />
    </application>

</manifest>

實作心得:

程式修改幅度不大,重點是在於如何整合,是Android上手不錯的練習,與第一版的差異主要在於下列四項
  • 答錯還是可以繼續遊戲。
  • 有幾個題目就要回答幾次。
  • 遊戲結束有排行榜。
  • 若要離開遊戲,須按鍵確認,避免主動跳出遊戲。'
前兩項是依據遊戲的設計概念,單就趣味性來說,第二版的設計比較好,不過因為只是練習程式用,就不在此討論,後兩項的加入,有基本的遊戲架構了,若增加背景音樂後,就算是個完整的遊戲,當然後續還有過場動畫,題庫新增...等,用來增加遊戲的豐富度,就再來研究。
下次的益智問答遊戲改版會以四選一的遊戲為主,再加上音樂、音效,希望能做個完基本元素都完備的遊戲。

0 意見:

張貼留言