Build a Simple Math Quiz Game in Android Studio: 9 Easy Steps for Success!

Are you eager to dive into Android app development and create an engaging game? Look no further! In this step-by-step guide, we will walk you through the process of building a Math Quiz Game in Android Studio. The focus keyword for this tutorial is “Math Quiz Game in Android Studio,” so let’s get started.

Math Quiz Game in Android Studio

Step 1: Set Up Your Project for Math Quiz Game in Android Studio

Begin by opening Android Studio and creating a new project. Choose an appropriate project name and set the package name. Select the “Phone and Tablet” template and choose “Empty Activity” for the project’s template.

Step 2: Add required styles in Themes.xml section.

In Step 2 of creating a Math Quiz Game in Android Studio, amplify the visual appeal by incorporating required styles in the Themes.xml section. Tailor your app’s appearance with precision, ensuring a sleek and intuitive design for an exceptional Math Quiz Game experience.

				
					<style name="CircularProgressBar" parent="Theme.AppCompat"><item name="colorAccent">@color/white</item>
        <item name="android:indeterminateOnly">false</item>
        <item name="android:progressDrawable">@drawable/circular_progress_bar</item></style>
				
			

Step 3: Define Essential Color Codes in colors.xml

In Step 3, define crucial color codes in colors.xml to enhance the visual appeal of your Math Quiz Game in Android Studio. Customize your app’s palette for a vibrant and cohesive user interface.

				
					
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="green">#8BC34A</color>
    <color name="correctColor">#4CAF50</color>
    <color name="incorrectColor">#F44336</color>
    <color name="defaultButtonColor">#50FFFFFF</color>
</resources>


				
			

Step 4: Design the Layout by Adding activity_main.xml Code.

In Step 4, shape the layout by incorporating activity_main.xml code for your Math Quiz Game in Android Studio. Craft a visually appealing and user-friendly design, setting the foundation for an engaging and seamless gaming experience.

				
					<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/container"
    android:background="@drawable/bgm"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">


    <LinearLayout
        android:gravity="center"
        android:id="@+id/dashbord"
        android:background="@drawable/rounded_button_background"
        android:orientation="vertical"
        android:padding="20sp"
        android:layout_width="wrap_content"
        android:layout_height="300sp">


        <TextView
            android:id="@+id/title"
            android:text="MATH-QUIZ GAME"
            android:textColor="@color/white"
            android:textSize="30sp"
            android:textStyle="bold"
            android:padding="10sp"
            android:textAlignment="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>




        <Button
            android:id="@+id/start_button"
            android:layout_marginTop="20dp"
            android:layout_gravity="center"
            android:text=" Start Game "
            android:textColor="@color/white"
            android:background="#E00BF8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Button>

    </LinearLayout>





    <LinearLayout
        android:id="@+id/gamelayout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <TextView
            android:layout_gravity="center"
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Level 1"
            android:textSize="35sp"
            android:textStyle="bold"
            />


        <TextView
            android:id="@+id/scoreTextView"
            android:layout_gravity="right"
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Score: 0"
            android:textSize="18sp"
            android:layout_marginRight="20sp"
            />

        <RelativeLayout

            android:layout_marginBottom="20sp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <ProgressBar
                android:id="@+id/progressBar"
                style="@style/CircularProgressBar"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_centerInParent="true"
                android:layout_gravity="center"
                android:visibility="visible" />

            <TextView
                android:id="@+id/timerTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_gravity="center"
                android:layout_marginBottom="10sp"
                android:text="10"
                android:textColor="@color/white"
                android:textSize="35sp"
                android:textStyle="bold" />

        </RelativeLayout>



        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">



            <TextView
                android:layout_marginTop="20sp"
                android:background="@color/white"
                android:layout_width="match_parent"
                android:layout_height="5sp">
            </TextView>

            <TextView
                android:layout_marginTop="150sp"
                android:background="@color/white"
                android:layout_width="match_parent"
                android:layout_height="5sp">
            </TextView>


            <TextView
            android:id="@+id/questionTextView"
            android:textColor="@color/white"
            android:background="#7E000000"
            android:textStyle="bold"
            android:textAlignment="center"
            android:textSize="40sp"
            android:text="55 + 69 = ?"
            android:layout_marginTop="25sp"
            android:layout_marginBottom="20sp"
            android:layout_gravity="center"
            android:padding="35sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </TextView>


            <LinearLayout
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <Button
                    android:id="@+id/questionNumberTextView"
                    android:textSize="17sp"
                    android:text="   Question- 1/100   "
                    android:textColor="@color/white"
                    android:background="#D82BFF"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </Button>

            </LinearLayout>
            
        </RelativeLayout>


        <LinearLayout
            android:layout_marginTop="20sp"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

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

                <TextView
                    android:layout_marginTop="10sp"
                    android:layout_marginLeft="40sp"
                    android:textColor="@color/white"                    android:textSize="30sp"
                    android:text="  A:"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </TextView>

            <Button
                android:id="@+id/option1Button"
                android:textSize="30sp"
                android:text="134"
                android:textColor="@color/white"
                android:layout_marginRight="20sp"
                android:layout_marginLeft="20sp"
                android:layout_marginBottom="10sp"
                android:background="@drawable/rounded_button_background"
                android:layout_width="match_parent"
                android:layout_height="60sp">
            </Button>

            </RelativeLayout>

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

            <TextView
                android:layout_marginTop="10sp"
                android:layout_marginLeft="40sp"
                android:textColor="@color/white"
                android:textSize="30sp"
                android:text="  B:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </TextView>

            <Button
                android:id="@+id/option2Button"
                android:textSize="30sp"
                android:text="134"
                android:textColor="@color/white"
                android:layout_marginRight="20sp"
                android:layout_marginLeft="20sp"
                android:layout_marginBottom="10sp"
                android:background="@drawable/rounded_button_background"
                android:layout_width="match_parent"
                android:layout_height="60sp">
            </Button>
            </RelativeLayout>

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

            <TextView
                android:layout_marginTop="10sp"
                android:layout_marginLeft="40sp"
                android:textColor="@color/white"                    android:textSize="30sp"
                android:text="  C:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </TextView>


            <Button
                android:id="@+id/option3Button"
                android:textSize="30sp"
                android:text="134"
                android:textColor="@color/white"
                android:layout_marginRight="20sp"
                android:layout_marginLeft="20sp"
                android:layout_marginBottom="10sp"
                android:background="@drawable/rounded_button_background"
                android:layout_width="match_parent"
                android:layout_height="60sp">
            </Button>

            </RelativeLayout>

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

            <TextView
                android:layout_marginTop="10sp"
                android:layout_marginLeft="40sp"
                android:textColor="@color/white"          
                android:textSize="30sp"
                android:text="  D:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </TextView>

            <Button
                android:id="@+id/option4Button"
                android:textSize="30sp"
                android:text="134"
                android:textColor="@color/white"
                android:layout_marginRight="20sp"
                android:layout_marginLeft="20sp"
                android:layout_marginBottom="10sp"
                android:background="@drawable/rounded_button_background"
                android:layout_width="match_parent"
                android:layout_height="60sp">
            </Button>

            </RelativeLayout>


        </LinearLayout>

        <Space
            android:layout_width="match_parent"
            android:layout_height="70dp">

        </Space>

    </LinearLayout>

    </LinearLayout>






				
			

Step 5: Design a Custom Progress Bar by Creating circular_progress_bar.xml in the Drawable Folder and Add the Following Code.

In Step 5, enhance your Math Quiz Game’s aesthetics by designing a custom progress bar. Create circular_progress_bar.xml in the Drawable folder, and add the following code. Elevate the visual experience and provide users with a unique and engaging interface.

				
					
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    
    <item android:id="@android:id/progress">
        <rotate
            android:fromDegrees="0"
            android:toDegrees="360"
            android:pivotX="50%"
            android:pivotY="50%">
            <shape
                android:innerRadiusRatio="3"
                android:shape="ring"
                android:thicknessRatio="8.0">
                <gradient
                    android:centerColor="#FFEB3B"
                    android:endColor="#F44336"
                    android:startColor="#4CAF50"
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>

    
    <item android:id="@android:id/background">
        <rotate
            android:fromDegrees="0"
            android:toDegrees="360"
            android:pivotX="50%"
            android:pivotY="50%">
            <shape
                android:innerRadiusRatio="3"
                android:shape="ring"
                android:thicknessRatio="8.0">
                <solid android:color="@color/white"/>
            </shape>
        </rotate>
    </item>
</layer-list>

				
			

Step 6: Add rounded_button_background.xml in the Drawable Folder to Enhance Button Aesthetics.

				
					<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp"
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp" />
    <solid android:color="#50FFFFFF" />
    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />
</shape>

				
			

Step 7: Incorporate bgm.jpg as the Game Background Image. Download and add in the drawable folder.

In Step 7, enhance the ambiance of your Math Quiz Game in Android Studio by seamlessly integrating bgm.jpg as the captivating game background image. Download and add this visual asset to the drawable folder, ensuring an immersive and engaging experience for players. Elevate the overall aesthetic of your Math Quiz Game with this carefully chosen background.

Step 8: Elevate the gaming experience by adding essential logic and functionality in MainActivity.kt.

In Step 8, elevate the gaming experience of your Math Quiz Game in Android Studio by incorporating essential logic and functionality in MainActivity.kt. Enhance the core mechanics, ensuring a seamless and enjoyable gameplay journey. Elevate your Math Quiz Game to new heights with thoughtful implementation in the main activity file.

				
					import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import java.util.Random

class MainActivity : AppCompatActivity() {

    private lateinit var startButton: Button
    private lateinit var gamelayout: LinearLayout
    private lateinit var dashbord: LinearLayout
    private lateinit var questionTextView: TextView
    private lateinit var option1Button: Button
    private lateinit var option2Button: Button
    private lateinit var option3Button: Button
    private lateinit var option4Button: Button
    private lateinit var timerTextView: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var questionNumberTextView: Button
    private var currentQuestionNumber: Int = 1

    private val random = Random()
    private var score = 0
    private var currentQuestionIndex = 0
    private lateinit var currentQuestion: Question
    private var timer: CountDownTimer? = null

    private lateinit var scoreTextView: TextView
    private lateinit var title: TextView
    private val correctColor: Int by lazy { ContextCompat.getColor(this, R.color.correctColor) }
    private val incorrectColor: Int by lazy { ContextCompat.getColor(this, R.color.incorrectColor) }



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        

        startButton = findViewById(R.id.start_button)
         gamelayout = findViewById(R.id.gamelayout)
        dashbord = findViewById(R.id.dashbord)
        progressBar = findViewById(R.id.progressBar)
        timerTextView = findViewById(R.id.timerTextView)
        scoreTextView = findViewById(R.id.scoreTextView)
        title = findViewById(R.id.title)
        questionNumberTextView = findViewById(R.id.questionNumberTextView)



        gamelayout.visibility = View.GONE
        
        startButton.setOnClickListener {
            
            val durationInMillis: Long = 10000
            val intervalInMillis: Long = 100

            object : CountDownTimer(durationInMillis, intervalInMillis) {

                override fun onTick(millisUntilFinished: Long) {
                    val progress = (millisUntilFinished * 100 / durationInMillis).toInt()
                    progressBar.progress = progress

                    val secondsRemaining = (millisUntilFinished / 1000).toInt()
                    timerTextView.text = secondsRemaining.toString()
                }

                override fun onFinish() {
                    timerTextView.text = "0"
                }
            }.start()

        }

        

        questionTextView = findViewById(R.id.questionTextView)
        option1Button = findViewById(R.id.option1Button)
        option2Button = findViewById(R.id.option2Button)
        option3Button = findViewById(R.id.option3Button)
        option4Button = findViewById(R.id.option4Button)
        timerTextView = findViewById(R.id.timerTextView)
        progressBar = findViewById(R.id.progressBar)

        startButton.setOnClickListener {
            startGame()
        }

        option1Button.setOnClickListener { onOptionSelected(it) }
        option2Button.setOnClickListener { onOptionSelected(it) }
        option3Button.setOnClickListener { onOptionSelected(it) }
        option4Button.setOnClickListener { onOptionSelected(it) }

    }

    private fun startGame() {

        option1Button.setBackgroundResource(R.drawable.rounded_button_background)
        option2Button.setBackgroundResource(R.drawable.rounded_button_background)
        option3Button.setBackgroundResource(R.drawable.rounded_button_background)
        option4Button.setBackgroundResource(R.drawable.rounded_button_background)

        dashbord.visibility = View.GONE
        gamelayout.visibility = View.VISIBLE
        score = 0
        currentQuestionIndex = 0
        showNextQuestion()
        score = 0
        updateScoreDisplay()

    }

    private fun showNextQuestion() {
        currentQuestion = generateRandomQuestion()
        updateQuestionUI()
        startTimer()
        questionNumberTextView.text = "    Question $currentQuestionNumber/50    "
        currentQuestionNumber++
    }

    private fun updateQuestionUI() {
        questionTextView.text = currentQuestion.question
        val options = currentQuestion.options
        option1Button.text = options[0]
        option2Button.text = options[1]
        option3Button.text = options[2]
        option4Button.text = options[3]
    }

    private fun startTimer() {

        timer?.cancel()
        var timeLeft = 10000L
        progressBar.progress = 100
        val duration = 10000L // Total duration of the timer in milliseconds
        val interval = 50L // Update interval in milliseconds

        timer = object : CountDownTimer(duration, interval) {
            override fun onTick(millisUntilFinished: Long) {
                val progress = ((duration - millisUntilFinished) * 100 / duration).toInt()
                progressBar.progress = progress
                timeLeft = millisUntilFinished
                timerTextView.text = "${millisUntilFinished / 1000}"
            }

            override fun onFinish() {
                progressBar.progress = 100
                timerTextView.text = "Time's up!"
                endGame()
            }
        }.start()
    }

    private fun generateRandomQuestion(): Question {
        val num1 = random.nextInt(100)
        val num2 = random.nextInt(100)
        val correctAnswer = num1 + num2
        val options = generateOptions(correctAnswer)

        return Question("$num1 + $num2?", options, options.indexOf(correctAnswer.toString()))
    }

    private fun generateOptions(correctAnswer: Int): List<String> {
        val options = mutableListOf<String>()
        options.add(correctAnswer.toString())

        while (options.size < 4) {
            val wrongAnswer = correctAnswer + random.nextInt(20) - 10
            if (wrongAnswer != correctAnswer && !options.contains(wrongAnswer.toString())) {
                options.add(wrongAnswer.toString())
            }
        }

        return options.shuffled()
    }

    private fun endGame() {
        Toast.makeText(this, "Game Over! Your score: $score", Toast.LENGTH_SHORT).show()


        Handler(Looper.getMainLooper()).postDelayed({
            dashbord.visibility = View.VISIBLE
            gamelayout.visibility = View.GONE
        }, 1000)

        timer?.cancel()
        currentQuestionNumber = 1
        title.setText("  Game Over!  \n\n Score: $score ")
        startButton.setText("    Play Again     ")

    }

    fun onOptionSelected(view: View) {
        val selectedOption = when (view.id) {
            R.id.option1Button -> 0
            R.id.option2Button -> 1
            R.id.option3Button -> 2
            R.id.option4Button -> 3
            else -> -1
        }

        if (selectedOption == currentQuestion.correctOption) {
            score += 10  // Increase the score by 10
            updateScoreDisplay()
            view.setBackgroundColor(correctColor)
          //  Toast.makeText(this, "Correct! Score +1", Toast.LENGTH_SHORT).show()
        } else {
            view.setBackgroundColor(incorrectColor)
            Toast.makeText(this, "Wrong! Game Over.", Toast.LENGTH_SHORT).show()
            endGame()
            return
        }

        Handler(Looper.getMainLooper()).postDelayed({
            view.setBackgroundResource(R.drawable.rounded_button_background)

            currentQuestionIndex++
            showNextQuestion()
        }, 1000)




    }

    private fun updateScoreDisplay() {
        scoreTextView.text = "Score: $score"
    }

}

				
			

Step 9: Culminate your Math Quiz Game by creating the Question.kt file. Incorporate the following code to lay the foundation for an interactive and fully-functional game.

In Step 9, culminate the development of your Math Quiz Game in Android Studio by creating the Question.kt file. Integrate the following code to establish the foundation for an interactive and fully-functional gaming experience. This crucial step marks the completion of your game’s structure, bringing it to life with engaging questions and responsive functionality.

				
					data class Question(
    val question: String,
    val options: List<String>,
    val correctOption: Int
)

				
			

All done. Run and check your Math Quiz Game in Android Studio to see the culmination of your efforts. Witness the engaging Math Quiz Game come to life as you navigate through the intricacies you’ve meticulously crafted. This is the moment to experience the fruition of your hard work and creative input. Enjoy the game and take pride in what you’ve accomplished!

In conclusion, the creation of a Math Quiz Game in Android Studio has been a fulfilling journey. Following the step-by-step guide honed your Kotlin programming and UI/UX design skills, resulting in an engaging and visually appealing gaming experience. Running the game unveils the culmination of your efforts—a testament to your creativity and commitment to app development. Whether you’re a novice or an experienced developer, this project marks a significant achievement in the dynamic realm of Android game development. Congratulations on crafting an exceptional Math Quiz Game in Android Studio!

also visit our youtube channel for more stuffs like this.

1 thought on “Build a Simple Math Quiz Game in Android Studio: 9 Easy Steps for Success!”

  1. Hello, is there a version of the math game program in Kotlin language that we wrote translated into Java language or where can we get it?

    Reply

Leave a comment