Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005.
What we are going to build in this article?
In this game, a timer of 10 seconds will be running and we have to click on the ball image to increase our score if we are not able to click on it then our score remains zero. Here is a sample video of this game. Note that we are going to build this application using the Java language.
Step by Step Implementation
Step 1. Create a New Project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- Name the application as user_application.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Â
Step 2. Adding required dependencies
Navigate to Gradle scripts > build.gradle(module) and use the following dependencies in it-
implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.gridlayout:gridlayout:1.0.0'
Step 3. Working on activity_main.xml file-
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.Â
XML
| <?xmlversion="1.0"encoding="utf-8"?><!-- constraint layout as parent layout--><androidx.constraintlayout.widget.ConstraintLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"> Â    <!-- grid layout wo make grid of images-->    <androidx.gridlayout.widget.GridLayout        android:id="@+id/gridLayout"        android:layout_width="410dp"        android:layout_height="630dp"        android:layout_marginStart="1dp"        android:layout_marginEnd="1dp"        android:layout_marginTop="80dp"        android:layout_marginBottom="1dp"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintVertical_bias="0.0"        > Â        <ImageView            android:id="@+id/image_view1"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="0"            app:layout_row="1"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view2"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="1"            app:layout_row="1"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view3"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="2"            app:layout_row="1"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view4"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="0"            app:layout_row="2"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view5"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="1"            app:layout_row="2"            android:src="@drawable/ball"            /> Â        <ImageView            android:id="@+id/image_view6"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="2"            app:layout_row="2"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view7"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="2"            app:layout_row="3"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view8"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="1"            app:layout_row="3"            android:src="@drawable/ball"            />        <ImageView            android:id="@+id/image_view9"            android:layout_width="120dp"            android:layout_height="120dp"            android:onClick="increaseScore"            app:layout_column="0"            app:layout_row="3"            android:src="@drawable/ball"            />        <!--Textview for timer-->        <TextView            android:id="@+id/time"            android:layout_width="145dp"            android:height="58dp"            android:text="Time : 10"            android:gravity="center"            android:textStyle="bold"            android:textSize="24sp"            app:layout_column="1"            app:layout_row="0"            /> Â    </androidx.gridlayout.widget.GridLayout> Â    <!-- Text view for score-->    <TextView        android:id="@+id/score"        android:layout_width="144dp"        android:layout_height="52dp"        android:layout_marginEnd="111dp"        android:text="Score : 0"        android:textSize="24sp"        android:textStyle="bold"        android:textColor="#32cd32"        app:layout_constraintBottom_toBottomOf="@id/gridLayout"        app:layout_constraintEnd_toEndOf="parent"        /> Â</androidx.constraintlayout.widget.ConstraintLayout> | 
Â
Â
After executing the above code, the UI of the activity_main.xml file will look like-
Â
Â
Step 4. Working on Mainactivity.java file
Â
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Â
Java
| packagecom.example.coronavirusgame; Âimportandroidx.appcompat.app.AlertDialog;importandroidx.appcompat.app.AppCompatActivity; Âimportandroid.content.DialogInterface;importandroid.content.Intent;importandroid.media.Image;importandroid.os.Bundle;importandroid.os.CountDownTimer;importandroid.os.Handler;importandroid.os.Looper;importandroid.view.View;importandroid.view.Window;importandroid.widget.ImageView;importandroid.widget.TextView;importandroid.widget.Toast; Âimportjava.util.Random; ÂpublicclassMainActivity extendsAppCompatActivity { Â    // initialize variables    ImageView[] imageList;    Handler handler;    TextView scoring,killno;    intscore;    ImageView imageView,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9;    Runnable runnable; Â    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState); Â        // hiding Action bar        requestWindowFeature(Window.FEATURE_NO_TITLE);        getSupportActionBar().hide();        setContentView(R.layout.activity_main); Â        // assigning variables        scoring=findViewById(R.id.score);        killno=findViewById(R.id.time);        imageView=findViewById(R.id.image_view1);        imageView2=findViewById(R.id.image_view2);        imageView3=findViewById(R.id.image_view3);        imageView4=findViewById(R.id.image_view4);        imageView5=findViewById(R.id.image_view5);        imageView6=findViewById(R.id.image_view6);        imageView7=findViewById(R.id.image_view7);        imageView8=findViewById(R.id.image_view8);        imageView9=findViewById(R.id.image_view9); Â        imageList=newImageView[]{imageView,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9};        makeitgone(); Â        // setting timer to play game        newCountDownTimer(10000,1000)        { Â            // increasing time            @Override            publicvoidonTick(longl) {                killno.setText("Time : "+l/1000);            } Â            // When time is finished            @Override            publicvoidonFinish() {                killno.setText("Time Over");                handler.removeCallbacks(runnable);                 Â                // using for loop                for(ImageView image:imageList)                {                    image.setVisibility(View.INVISIBLE);                } Â                // dialog box to ask user's input                AlertDialog.Builder alert=newAlertDialog.Builder(MainActivity.this);                alert.setTitle("Try Again!");                alert.setMessage("Do you want to restart?");                 Â                // if user want to restart game                alert.setPositiveButton("Yes", newDialogInterface.OnClickListener() {                    @Override                    publicvoidonClick(DialogInterface dialogInterface, inti) {                        Intent intent=getIntent();                        finish();                        startActivity(intent);                    }                });               Â                // When user not want to play again                alert.setNegativeButton("No", newDialogInterface.OnClickListener() {                    @Override                    publicvoidonClick(DialogInterface dialogInterface, inti) {                        Toast.makeText(MainActivity.this, "Game Over!!!", Toast.LENGTH_SHORT).show();                    }                });                alert.show();            }        }.start();    } Â    privatevoidmakeitgone() {        handler=newHandler();        runnable=newRunnable() {            @Override            publicvoidrun() {                for(ImageView image:imageList)                {                    image.setImageResource(R.drawable.ball);                    finalHandler handler=newHandler(Looper.getMainLooper());                    handler.postDelayed(newRunnable() {                        @Override                        publicvoidrun() {                            image.setImageResource(R.drawable.ball);                        }                    },900);                    image.setVisibility(View.INVISIBLE);                } Â                // making image visible at random positions                Random random=newRandom();                inti=random.nextInt(9);                imageList[i].setVisibility(View.VISIBLE);                handler.postDelayed(this,600);            }        };        handler.post(runnable);    } Â    // increasing score    publicvoidincreaseScore(View view) {        score=score+1;        scoring.setText("Score : "+score);    }} | 
Â
Â
Our game is ready and here is the final output of our application.
Â
Output:
Â
Â


 
                                    








