Empower Your Learning Journey: Develop a Math Quiz Game in Android Studio Kotlin with this Comprehensive 9 Step-by-Step Guide and Source Code

In this blog post, we’ll explore the development of a fun and interactive Math Quiz Game in android studio kotlin. Our app will not only help users sharpen their math skills but also keep them engaged with a range of exciting game features. Let’s dive into the key features that make our Math Quiz App stand out.

Key Features of Math Quiz Game in android studio kotlin:

FeatureDescription
Multiple OperationsUsers can choose from a variety of math operations, including addition, subtraction, multiplication, division, and a random operation mode for added challenge.
User-Friendly InterfaceThe app boasts an intuitive and user-friendly interface, making it accessible for users of all ages. Large buttons and clear text ensure a seamless gaming experience.
Dynamic Timer and Progress BarA dynamic countdown timer and progress bar add a sense of urgency to the game. Users must answer questions within the time limit, creating a thrilling and competitive atmosphere.
Sound EffectsImmersive sound effects enhance the gaming experience, including a ticking timer, celebratory cheers for correct answers, and a game over jingle.
Interactive Score DisplayThe app features a real-time score display that updates with each correct answer. Users can track their progress and strive to beat their previous high scores.
Randomly Generated QuestionsThe app generates a wide range of questions dynamically, ensuring that each game session is unique. This feature prevents users from memorizing answers and encourages continuous learning.
Adaptive DifficultyAs users progress through the game, the difficulty adapts to their skill level, ensuring a challenging experience for both beginners and advanced players.
Game Over Screen with Final ScoreWhen the game ends, a visually appealing game over screen displays the user’s final score, providing a sense of accomplishment and encouraging replay.
Exit Confirmation DialogTo prevent accidental exits, the app includes an exit confirmation dialog, ensuring users can exit intentionally to enhance the overall user experience.
Play Again OptionAfter completing a game, users can choose to play again with the same selected operation, encouraging repeated gameplay and focused skill improvement.

Discover the joy of creating a Math Quiz Game in android studio kotlin. Follow these simple steps to unleash your coding skills and craft an engaging educational experience. Let’s dive into the world of app development together!

Step 1: Create a new project with an empty activity and select Kotlin as the programming language.

In this step, you will initiate the development process by creating a new Android project. Opt for an empty activity to begin with a clean slate. Ensure that you choose Kotlin as the programming language, leveraging its concise syntax and powerful features for efficient Android app development of Math Quiz Game in android studio kotlin.

Step 2: Change Theme and Add Styles in Themes Section of Math Quiz Game in android studio kotlin

In this step, customize the visual appearance of your Android project by modifying the theme. Navigate to the Themes section and enhance the aesthetics by adding the following theme and styles to your themes.xml file. This step is crucial for shaping the overall look and feel of your application.

				
					<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="Base.Theme.Bhjerjerv" parent="Theme.AppCompat.DayNight.NoActionBar">Customize your light theme here. -->
        <!-- <item name="colorPrimary">@color/my_light_primary</item></style><style name="Theme.Bhjerjerv" parent="Base.Theme.Bhjerjerv" /><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></resources>
				
			

Step 3: Define Essential Color Codes in colors.xml

Open the colors.xml file and insert the following color codes. This step is essential for defining the color palette that will be utilized throughout your Android project, ensuring a harmonious and consistent visual experience. Simply copy and paste the provided color codes into the colors.xml file to integrate them seamlessly into your Math Quiz Game in android studio kotlin design.

				
					<?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>
    <color name="purple">#FF3700B3</color>
</resources>
				
			

Step 4: Add sound files in Raw folder

Within your Android project, create a ‘raw’ folder and populate it with the specified music files. This action facilitates seamless integration of audio components into your application. By organizing and placing these files appropriately, you ensure efficient access and utilization of these sound resources within your app.

Step 5: Add Files in Drawable folder.

Download the provided zip file and unzip its contents. After extracting the files, navigate to the ‘drawable’ folder in Android Studio. Copy all the files from the unzipped folder and paste them into the ‘drawable’ folder within your project. This step ensures the inclusion of visual assets in your Math Quiz Game in android studio kotlin, enhancing its overall appearance and user interface.

Step 6: Add following code in activity_main.xml of Math Quiz Game in android studio kotlin game

				
					<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">



    <RelativeLayout
        android:id="@+id/dashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


    <View
        android:id="@+id/view"
        android:layout_below="@id/title"
        android:background="@drawable/background_view"
        android:layout_width="match_parent"
        android:layout_height="245sp">
    </View>


    <RelativeLayout
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#673AB7">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:gravity="center"
            android:text="Maths-Quiz"
            android:textColor="@color/white"
            android:textSize="50sp"
            android:textStyle="bold">

        </TextView>


    </RelativeLayout>
    
    <GridLayout
        android:id="@+id/grid_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/title"
        android:rowCount="3"
        android:columnCount="2"
        android:layout_margin="24dp">



        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="0"
            android:layout_column="0"
            android:layout_margin="12dp">


            <LinearLayout
                android:id="@+id/addition_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                
                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/baseline_add_24" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Addition"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>



        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="0"
            android:layout_column="1"
            android:layout_margin="12dp">


            <LinearLayout
                android:id="@+id/subtract_button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/baseline_remove_24" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Subtract"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>



        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="1"
            android:layout_column="0"
            android:layout_margin="12dp">


            <LinearLayout
                android:id="@+id/multiply_button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/multiply" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Multiply"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>


        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="1"
            android:layout_column="1"
            android:layout_margin="12dp">



            <LinearLayout
                android:id="@+id/division_button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/baseline_vertical_align_center_24" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Division"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>






        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="2"
            android:layout_column="0"
            android:layout_margin="12dp">



            <LinearLayout
                android:id="@+id/random_button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/baseline_auto_mode_24" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Random"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>


        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardElevation="12dp"
            app:cardCornerRadius="15dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_row="2"
            android:layout_column="1"
            android:layout_margin="12dp">



            <LinearLayout
                android:id="@+id/exit"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:src="@drawable/baseline_exit_to_app_24" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Exit"
                    android:textColor="@color/black"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

        </androidx.cardview.widget.CardView>

    </GridLayout>

    </RelativeLayout>




    <LinearLayout
        android:visibility="gone"
        android:id="@+id/gamelayout"
        android:orientation="vertical"
        android:background="@drawable/bgm"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <TextView
            android:layout_marginTop="20sp"
            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>
        
    </LinearLayout>

    
    <RelativeLayout
        android:visibility="gone"
        android:background="@color/white"
        android:id="@+id/gameoverscreen"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        
    <View
        android:background="@drawable/background_view"
        android:layout_width="match_parent"
        android:layout_height="245sp">
    </View>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#673AB7">

        <TextView
            android:id="@+id/gmtv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="90sp"
            android:gravity="center"
            android:text="Game Over!"
            android:textColor="#D50000"
            android:textSize="60sp"
            android:textStyle="bold">

        </TextView>

    </RelativeLayout>




        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerHorizontal="true"
            android:layout_marginEnd="60dp"
            android:layout_marginTop="200dp"
            android:background="#FFFFFF"
            android:gravity="center"
            android:orientation="vertical"
            android:padding="10sp">


            <LinearLayout
                android:layout_alignParentEnd="true"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="10dp"
                android:background="#673AB7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">



            <TextView
                android:id="@+id/final_score"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:padding="10dp"
                android:background="@drawable/rounded_button_background"
                android:gravity="center"
                android:text="score: 50"
                android:textColor="@color/white"
                android:textSize="40sp"
                android:layout_marginTop="15dp"
                android:textStyle="bold"
                >
            </TextView>


            <Button
                android:id="@+id/play_again"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:background="@drawable/rounded_button_background"
                android:padding="10dp"
                android:text="Try again"
                android:textColor="@color/white"
                android:textSize="20dp"></Button>

            <Button
                android:id="@+id/gotohome"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_marginTop="15dp"
                android:background="@drawable/rounded_button_background"
                android:padding="10dp"
                android:text="Home"
                android:textColor="@color/white"
                android:textSize="20dp"></Button>

            <Button
                android:id="@+id/exitbutton"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_marginTop="15dp"
                android:background="@drawable/rounded_button_background"
                android:padding="10dp"
                android:text="Exit"
                android:layout_marginBottom="20sp"
                android:textColor="@color/white"
                android:textSize="20dp"></Button>

        </LinearLayout>


        </LinearLayout>

        <TextView
            android:textSize="30dp"
            android:gravity="center"
            android:textAlignment="center"
            android:text="Space For Ad."
            android:layout_marginBottom="5dp"
            android:layout_alignParentBottom="true"
            android:background="@color/black"
            android:textColor="@color/white"
            android:layout_width="match_parent"
            android:layout_height="60sp">
        </TextView>


    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


				
			

Step 7: Create new kotlin class file, name it "SoundManager" and add following code to it.

				
					import android.content.Context
import android.media.MediaPlayer

class SoundManager(private val context: Context) {

    private var mediaPlayer: MediaPlayer? = null

    fun playSound(resourceId: Int) {
        // Release any existing MediaPlayer instance
        mediaPlayer?.release()

        // Create a new MediaPlayer instance for the specified sound resource
        mediaPlayer = MediaPlayer.create(context, resourceId)

        // Start playing the sound
        mediaPlayer?.start()

        // Release the MediaPlayer resources when the sound playback is complete
        mediaPlayer?.setOnCompletionListener {
            mediaPlayer?.release()
            mediaPlayer = null
        }
    }

    fun stopSound() {
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}

				
			

Step 8: Create new kotlin class file, name it "Question" and add following code to it.

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

Step 9: Add following code in MainActivity.kt file

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

class MainActivity : AppCompatActivity() {

    private val soundManager = SoundManager(this)

    private var selectedOperation: Int = ADDITION  // Default to ADDITION


    companion object {
        const val ADDITION = 0
        const val SUBTRACTION = 1
        const val MULTIPLICATION = 2
        const val DIVISION = 3
        const val RANDOM = 4
    }

    private lateinit var startButton: LinearLayout
    private lateinit var subtractButton: LinearLayout
    private lateinit var multiplyButton: LinearLayout
    private lateinit var divisionButton: LinearLayout
    private lateinit var randomButton: LinearLayout
    private lateinit var gamelayout: LinearLayout
    private lateinit var dashbord: RelativeLayout
    private lateinit var gameover: RelativeLayout
    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 exitButton: Button
    private lateinit var gotohome: Button
    private lateinit var finalscoretv: TextView
    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 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)


        val exitLayout: LinearLayout = findViewById(R.id.exit)

        val exitButton : Button = findViewById(R.id.exitbutton)
        val gotohome : Button = findViewById(R.id.gotohome)
        

        val exitClickListener = View.OnClickListener {
            val builder = AlertDialog.Builder(this)

            builder.setTitle("Exit")
                .setMessage("Are you sure you want to exit the app?")

            builder.setPositiveButton("Yes") { dialog, which ->
                finish()
            }

            builder.setNegativeButton("No") { dialog, which ->
                dialog.dismiss()
            }

            val dialog: AlertDialog = builder.create()
            dialog.show()
        }

        exitLayout.setOnClickListener(exitClickListener)
        exitButton.setOnClickListener(exitClickListener)

        startButton = findViewById(R.id.addition_layout)
        subtractButton = findViewById(R.id.subtract_button)
        multiplyButton = findViewById(R.id.multiply_button)
        divisionButton = findViewById(R.id.division_button)
        randomButton = findViewById(R.id.random_button)
        gamelayout = findViewById(R.id.gamelayout)
        dashbord = findViewById(R.id.dashboard)
        gameover = findViewById(R.id.gameoverscreen)
        progressBar = findViewById(R.id.progressBar)
        timerTextView = findViewById(R.id.timerTextView)
        scoreTextView = findViewById(R.id.scoreTextView)
        finalscoretv = findViewById(R.id.final_score)
        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 {
            // Default to addition if the user starts the game without selecting an operation
            startGame(ADDITION)
        }

        subtractButton.setOnClickListener {
            selectedOperation = SUBTRACTION
            startGame(SUBTRACTION)
        }

        multiplyButton.setOnClickListener {
            selectedOperation = MULTIPLICATION
            startGame(MULTIPLICATION)
        }

        divisionButton.setOnClickListener {
            selectedOperation = DIVISION
            startGame(DIVISION)
        }

        randomButton.setOnClickListener {
            selectedOperation = RANDOM
            startGame(RANDOM)
        }

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

        changeStatusBarColor("#673AB7") // Replace with your desired color code


        gotohome.setOnClickListener {
            gameover.visibility = View.GONE
            dashbord.visibility = View.VISIBLE
        }

        val playagain =  findViewById<Button>(R.id.play_again)

        playagain.setOnClickListener {
            startGame(selectedOperation)
            gameover.visibility = View.GONE


        }

    }


    private fun changeStatusBarColor(color: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window: Window = window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = android.graphics.Color.parseColor(color)
        }
    }



    private fun startGame(selectedOperation: Int) {
        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(selectedOperation)
        score = 0
        updateScoreDisplay()
    }

    private fun showNextQuestion(selectedOperation: Int) {
        currentQuestion = generateRandomQuestion(selectedOperation)
        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()

        soundManager.stopSound()
        soundManager.playSound(R.raw.timer)



    }

    private fun generateRandomQuestion(operation: Int): Question {
        val num1 = random.nextInt(100)
        val num2 = when (operation) {
            ADDITION, SUBTRACTION, MULTIPLICATION -> random.nextInt(100) + 1 // Adjust the range as needed
            DIVISION -> generateRandomDivisor(num1)
            else -> random.nextInt(100) + 1 // Adjust the range as needed for other cases
        }

        val question: String
        val correctAnswer: Int

        when (operation) {
            ADDITION -> {
                question = "$num1 + $num2?"
                correctAnswer = num1 + num2
            }
            SUBTRACTION -> {
                question = "$num1 - $num2?"
                correctAnswer = num1 - num2
            }
            MULTIPLICATION -> {
                question = "$num1 * $num2?"
                correctAnswer = num1 * num2
            }
            DIVISION -> {
                question = "$num1 / $num2?"
                correctAnswer = num1 / num2
            }
            RANDOM -> {
                // Randomly choose an operation for the RANDOM case
                val randomOperation = random.nextInt(4)
                return generateRandomQuestion(randomOperation)
            }
            else -> {
                // Default to addition for any other case
                question = "$num1 + $num2?"
                correctAnswer = num1 + num2
            }
        }

        val options = generateOptions(correctAnswer)

        return Question(question, options, options.indexOf(correctAnswer.toString()))
    }


    

    private fun generateRandomDivisor(dividend: Int): Int {
        // Generate a random divisor that evenly divides the dividend
        val possibleDivisors = (1..dividend).filter { dividend % it == 0 }
        return possibleDivisors.random()
    }


    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()
        finalscoretv.setText("Score $score")

        soundManager.stopSound()
        soundManager.playSound(R.raw.gameover)

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

        timer?.cancel()
        currentQuestionNumber = 1
    }

    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)
            soundManager.stopSound()
            soundManager.playSound(R.raw.correctanswer)

        } 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(selectedOperation)  // <-- Pass selectedOperation here
        }, 1000)

    }

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

				
			

Step 10: All done. Now Go and Run your game.

Congratulations! You’ve completed all the necessary steps. It’s time to see your efforts in action. Click on the “Run” button in Android Studio to launch and experience your Math Quiz Game in android studio kotlin. This final step brings your project to life, allowing you to interact with and enjoy the results of your work.

Conclusion:

Congratulations! You’ve successfully built your very own Math Quiz Game in android studio kotlin. Our Math Quiz App offers a rich and engaging experience for users seeking to enhance their math abilities. With a combination of dynamic features, adaptive difficulty, and an intuitive interface, the app provides a stimulating environment for learning and fun. Whether you’re a student looking to practice math or someone wanting to challenge your mental agility, this app is designed to cater to all math enthusiasts. Download it now and embark on an exciting journey of mathematical discovery! This project not only enhances your Android development skills but also provides a valuable, educational resource for users.

    • FAQs: Building a Math Quiz Game in Android Studio Kotlin

      1. What is the significance of creating a Math Quiz Game in Android Studio Kotlin?

        Building a Math Quiz Game in Android Studio Kotlin allows you to enhance your programming skills while creating an engaging and educational mobile app.

      2. How do I get started with developing a Math Quiz Game in Android Studio Kotlin?

        To start creating your Math Quiz Game in Android Studio Kotlin, follow our step-by-step guide for a seamless development experience.

      3. Can I customize the features of my Math Quiz Game in Android Studio Kotlin?

        Absolutely! Android Studio Kotlin provides a flexible environment, allowing you to customize and tailor your Math Quiz Game according to your preferences.

      4. Are there any prerequisites for building a Math Quiz Game in Android Studio Kotlin?

        Basic knowledge of Kotlin and Android Studio is recommended. Our tutorial will guide you through the process, making it accessible for developers at various skill levels.

      5. What makes a Math Quiz Game in Android Studio Kotlin a valuable addition to educational apps?

        By creating a Math Quiz Game in Android Studio Kotlin, you contribute to the educational app landscape, offering users an interactive and enjoyable way to enhance their math skills.

      6. Is it possible to integrate multiplayer functionality into my Math Quiz Game using Android Studio and Kotlin?

        Yes, Android Studio Kotlin provides the tools and capabilities to implement multiplayer features, enhancing the collaborative and competitive aspects of your Math Quiz Game.

      7. Are there resources available for troubleshooting common issues during the development of a Math Quiz Game in Android Studio Kotlin?

        Certainly! Our comprehensive guide includes troubleshooting tips and links to resources that can assist you in overcoming challenges you may encounter while building your Math Quiz Game in android studio kotlin.

Leave a comment