Open In App

Ball Tapping Game in Android

Improve
Improve
Like Article
Like
Save
Share
Report

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




<?xml version="1.0" encoding="utf-8"?>
<!-- constraint layout as parent layout-->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    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




package com.example.coronavirusgame;
  
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
  
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
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.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import java.util.Random;
  
public class MainActivity extends AppCompatActivity {
  
    // initialize variables
    ImageView[] imageList;
    Handler handler;
    TextView scoring,killno;
    int score;
    ImageView imageView,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9;
    Runnable runnable;
  
    @Override
    protected void onCreate(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=new ImageView[]{imageView,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9};
        makeitgone();
  
        // setting timer to play game
        new CountDownTimer(10000,1000)
        {
  
            // increasing time
            @Override
            public void onTick(long l) {
                killno.setText("Time : "+l/1000);
            }
  
            // When time is finished
            @Override
            public void onFinish() {
                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=new AlertDialog.Builder(MainActivity.this);
                alert.setTitle("Try Again!");
                alert.setMessage("Do you want to restart?");
                  
                // if user want to restart game
                alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent=getIntent();
                        finish();
                        startActivity(intent);
                    }
                });
                
                // When user not want to play again
                alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(MainActivity.this, "Game Over!!!", Toast.LENGTH_SHORT).show();
                    }
                });
                alert.show();
            }
        }.start();
    }
  
    private void makeitgone() {
        handler=new Handler();
        runnable=new Runnable() {
            @Override
            public void run() {
                for(ImageView image:imageList)
                {
                    image.setImageResource(R.drawable.ball);
                    final Handler handler=new Handler(Looper.getMainLooper());
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            image.setImageResource(R.drawable.ball);
                        }
                    },900);
                    image.setVisibility(View.INVISIBLE);
                }
  
                // making image visible at random positions
                Random random=new Random();
                int i=random.nextInt(9);
                imageList[i].setVisibility(View.VISIBLE);
                handler.postDelayed(this,600);
            }
        };
        handler.post(runnable);
    }
  
    // increasing score
    public void increaseScore(View view) {
        score=score+1;
        scoring.setText("Score : "+score);
    }
}


 

 

Our game is ready and here is the final output of our application.

 

Output:

 

 



Last Updated : 25 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads