A simple Android Number Matching Game Tutorial

In this tutorial, we are going learn how to create a simple Android Number Matching game by extending android default View class.

This is not a tutorial about Game Engine so everything is done with native android APIs.

The android game we will create is simple. When it starts, it will populate major part of the canvas with buttons in 8 by 8 pattern.

The bottom part of the game will contain a timer, the current display number to match and sound controls.

If you want to test the game before hand, you can download the game android apk file here. Feel free to modify the source code to suit your project requirement.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

Android number matching game

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidAdmob

Package: com.inducesmile.androidadmob

Select Blank Activity

Name your activity : GameActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it. In the ad_unit_id, make sure you add your admob id.

<string name="app_name">Android Game Example</string>
<resources>
    <string name="app_name">Android Game Example</string>
    <string name="score_count"> 200</string>
    <string name="score">Score : </string>
    <string name="menu"> Main Menu</string>
    <string name="game_score">Game Score</string>
    <string name="start_game">Start Game</string>
</resources>

 

Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
</resources>

 

Drawable Resources

I have added the images that are need for this application. You can download it from my website. You can as well recreate the images with your own color pattern and shape.

 

Raw folder

Right click on the res folder and choose the option to create a folder from the menu window. Name the directory raw. We are going to save our sound files in this folder. Add your own sound file or you can download the sound file used in this project.

 

GameActivity Class

Open the default Activity class created for us when we created the project in Android Studio. The activity class is name GameActivity.

Add the following code inside this class

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
public class GameActivity extends AppCompatActivity {
    private static GameView gameView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        gameView = new GameView(GameActivity.this);
        super.onCreate(savedInstanceState);
        setContentView(gameView);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
    }
    private void displayAlertDialogBox(){
        AlertDialog.Builder alertBox = new AlertDialog.Builder(this);
        alertBox.setTitle("Quit Maths Game");
        String messagebox = "You are sure you want to quit game";
        alertBox.setMessage(messagebox);
        //alertBox.setButton
        alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                gameView.countTimer.cancel();
                Intent mIntent = new Intent(GameActivity.this, MainActivity.class);
                startActivity(mIntent);
            }
        });
        alertBox.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        alertBox.show();
    }
}

You can see that there is little thing going on there. We will pay attention to this line of code

setContentView(gameView);

Here we are using the object of a View class as a parameter to setContentView() method of this class.

Next, let us create the GameView class which will inherit from the default Android View class.

GameView

In the package folder, right click and select new and then choose Java class. Name the file GameView. Open the file and add the below code in it.

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class GameView extends View {
        private int blockWidth;
        private int blockHeight;
        private int mWidth;
        private int mHeight;
        private Paint backgroundPaint;
        private Paint foreground;
        @SuppressWarnings("unused")
        private List<ButtonClass> myListButton;
        private Bitmap skyBitmap;
        private Bitmap purpleBitmap;
        private Bitmap blueBitmap;
        private Bitmap overlayer;
        private Bitmap backgroundOverlayer;
        private Bitmap sound;
        private Bitmap soundmute;
        private Bitmap pauseButton;
        private Bitmap createBitmap;
        private Context context;
        private Canvas newCanvas;
        private Paint paint;
        private Paint mForeground;
        private Bitmap sky;
        private Bitmap purple;
        private Bitmap blue;
        @SuppressWarnings("unused")
        private int[][] buttonValues;
        private boolean touching = false;
        @SuppressWarnings("unused")
        private ArrayList<String> allTouched = new ArrayList<String>();
        private int numberGenerated = -1;
        @SuppressWarnings("unused")
        private ButtonClass clickObject;
        @SuppressWarnings("unused")
        private Bitmap[][] mBackgroundBitmap;
        private ButtonClass[][] boardGame;
        private int currentGamePoint = 0;
        private boolean changeQuestion;
        private int startCount = 0;
        private Rect headerRect;
        private Rect soundRect;
        private Rect questionRect;
        private Paint mPaint;
        private Rect pauseRect;
        private SoundPool makeSound;
        private int soundPoolId;
        private boolean isSoundLoaded = false;
        private boolean soundOn;
        public MyCountDownTimer countTimer;
        private final long startTime = 120 * 1000;
        private final long interval = 1000;
        private long gameTimer;
        @SuppressWarnings("unused")
        private boolean controlTimer = false;
        private boolean pauseTimer = false;
        private long initTimer = -1;
        public GameView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            init(context);
        }
        public GameView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context);
        }
    private void init(Context context){
        setFocusable(true);
        soundOn = true;
        myListButton = new ArrayList<ButtonClass>();
        countTimer = new MyCountDownTimer(startTime, interval);
        countTimer.start();
        makeSound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundPoolId = makeSound.load(context, R.raw.clickone, 1);
        makeSound.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener(){
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                // TODO Auto-generated method stub
                isSoundLoaded = true;
            }
        });
        this.context = context;
        this.backgroundPaint = new Paint();
        this.backgroundPaint.setColor(Color.parseColor("#D6DCB8"));
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#99bdbd"));
        paint = new Paint();
        paint.setColor(Color.BLUE);
        skyBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.buttonon);
        purpleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.buttontw);
        blueBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.buttonthre);
        overlayer = BitmapFactory.decodeResource(getResources(), R.drawable.overlayer);
        backgroundOverlayer = BitmapFactory.decodeResource(getResources(), R.drawable.backgroundoverlayer);
        pauseButton = BitmapFactory.decodeResource(getResources(), R.drawable.pause);
        sound = BitmapFactory.decodeResource(getResources(), R.drawable.sound);
        soundmute = BitmapFactory.decodeResource(getResources(), R.drawable.soundmute);
        mForeground = new Paint(Paint.ANTI_ALIAS_FLAG);
        mForeground.setColor(Color.parseColor("#41266b"));
        mForeground.setStrokeWidth(2);
        mForeground.setStyle(Paint.Style.FILL_AND_STROKE);
        // Draw the numbers...
        // Define color and style for numbers
        foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
        foreground.setColor(Color.BLACK);
        foreground.setStyle(Paint.Style.FILL);
        foreground.setTextAlign(Paint.Align.CENTER);
        // generate and store all text contents
        buttonValues =  getWrittenValues();
        // generate a new question
        numberGenerated = generateBasicMathsNumber(17, 3);
    }
    /* (non-Javadoc)
     * @see android.view.View#onDraw(android.graphics.Canvas)
     */
    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        gameOver();
        newCanvas.drawColor(Color.TRANSPARENT);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawColor(Color.parseColor("#9fb711"));
        newCanvas.drawColor(Color.parseColor("#9fb711"));
        foreground.setTextSize(blockHeight * 0.5f);
        Paint.FontMetrics fm = foreground.getFontMetrics();
        // draw the header of the game here before the main game
        /*canvas.drawRect(headerRect, mPaint);
        canvas.drawText("Maths Trick", 60, 30, foreground);
        canvas.drawText("Score : " + String.valueOf(currentGamePoint), mWidth - 60, 30, foreground);
        newCanvas.drawRect(headerRect, paint);*/
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                    newCanvas.drawBitmap(overlayer, null, gameSquareObject.getCoordinate(), paint);
                }
                else if(gameSquareObject.getSelected() && gameSquareObject.getAnswer()){
                    newCanvas.drawBitmap(backgroundOverlayer, null, gameSquareObject.getCoordinate(), paint);
                }
                else{
                    newCanvas.drawBitmap(gameSquareObject.getButtonBitmap(), null, gameSquareObject.getCoordinate(), paint);
                }
            }
        }
        //Draw Button fonts and values of the bitmap
        int x = blockHeight / 2;
        float y = blockHeight / 2 - (fm.ascent + fm.descent) / 2;
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getAnswer()){
                    //newCanvas.drawText(String.valueOf(gameSquareObject.getWrittenNumber()), i * blockHeight + x, j * blockHeight + y, foreground);
                }else{
                    newCanvas.drawText(String.valueOf(gameSquareObject.getWrittenNumber()), i * blockHeight + x, j * blockHeight + y, foreground);
                }
            }
        }
        newCanvas.drawLine(0, newCanvas.getHeight(), mWidth, newCanvas.getHeight(), mForeground);
        canvas.drawBitmap(createBitmap, 0, 50, null);
        //check if a number is click and check if a result has been acheived
        foreground.setTextSize(blockHeight);
        if(startCount == 0){
            String numberString = String.valueOf(numberGenerated);
            canvas.drawRect(questionRect, backgroundPaint);
            int xs = (30 + questionRect.left + questionRect.width()) / 2;
            int ys = questionRect.top + 15 + (questionRect.height() / 2) ;
            canvas.drawText(numberString, xs, ys, foreground);
        }
        if(soundOn){
            canvas.drawBitmap(sound, null, soundRect, backgroundPaint);
        }else{
            canvas.drawBitmap(soundmute, null, soundRect, backgroundPaint);
        }
        canvas.drawBitmap(pauseButton, null, pauseRect, backgroundPaint);
        canvas.drawText(String.valueOf(gameTimer), mWidth / 2, mHeight - 50, foreground);
        if(touching){
        }
        else{
            System.out.println("It is not touching");
            if(changeQuestion){
                //display the question to be asked
                String numberString = String.valueOf(numberGenerated);
                canvas.drawRect(questionRect, backgroundPaint);
                int xs = ((questionRect.left + questionRect.width()) / 2);
                int ys = questionRect.top + 15 + (questionRect.height() / 2) ;
                foreground.setTextSize(blockHeight);
                canvas.drawText(numberString, xs, ys, foreground);
            }
        }
    }
    // get all the bitmap for each object
    private Bitmap[][] returnDrawBitmap(){
        Bitmap[] buttonBitmap = new Bitmap[3];
        buttonBitmap[0] = sky;
        buttonBitmap[1] = purple;
        buttonBitmap[2] = blue;
        Bitmap[][] allTiless = new Bitmap[8][8];
        for(int i = 0; i < allTiless.length; i++){
            for(int j = 0; j < allTiless.length; j++){
                int index = generateBasicMathsNumber(2, 0);
                Bitmap mBitmap = buttonBitmap[index];
                allTiless[i][j] = mBitmap;
            }
        }
        return allTiless;
    }
    //get all the rectangle in the object class
    private Rect[][] returnRect(){
        Rect[][] allRect = new Rect[8][8];
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                allRect[i][j] = new Rect(i * blockWidth - 1, j * blockWidth - 1, (1 + i) * blockWidth, (1 + j) * blockWidth);
            }
        }
        return allRect;
    }
    // Get all the written text in the button
    private int[][] getWrittenValues(){
        int[][] textValues = new int[8][8];
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                int newValue = generateBasicMathsNumber(9, 1);
                textValues[i][j] = newValue;
            }
        }
        return textValues;
    }
    // Get all selection
    private boolean[][] getSelecedButtons(){
        boolean[][] textValues = new boolean[8][8];
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                textValues[i][j] = false;
            }
        }
        return textValues;
    }
    // Get all answer
    private boolean[][] getAnswers(){
        boolean[][] textValues = new boolean[8][8];
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                textValues[i][j] = false;
            }
        }
        return textValues;
    }
    private ButtonClass[][] mathBoardValues(){
        Bitmap[][] buttonImage = returnDrawBitmap();
        int[][] text = getWrittenValues();
        Rect[][] mRect = returnRect();
        boolean[][] selected =  getSelecedButtons();
        boolean[][] answered = getAnswers();
        ButtonClass[][] mGameBoard = new ButtonClass[8][8];
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                Bitmap bObject = buttonImage[i][j];
                int mText = text[i][j];
                Rect rect = mRect[i][j];
                boolean select = selected[i][j];
                boolean answer = answered[i][j];
                ButtonClass mButtonClass = new ButtonClass(bObject, mText, rect, select, answer);
                mGameBoard[i][j] = mButtonClass;
            }
        }
        return mGameBoard;
    }
    private static int generateBasicMathsNumber(int max, int min){
        Random r = new Random();
        int i = r.nextInt(max - min + 1) + min;
        return i;
    }
    /* (non-Javadoc)
     * @see android.view.View#onSizeChanged(int, int, int, int)
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        blockWidth = (int) (w / 8f);
        blockHeight = blockWidth;
        mWidth = w;
        mHeight = h;
        sky = Bitmap.createScaledBitmap(skyBitmap, blockWidth, blockWidth, false);
        purple = Bitmap.createScaledBitmap(purpleBitmap, blockWidth, blockWidth, false);
        blue = Bitmap.createScaledBitmap(blueBitmap, blockWidth, blockWidth, false);
        overlayer = Bitmap.createScaledBitmap(overlayer, blockWidth, blockWidth, false);
        backgroundOverlayer = Bitmap.createScaledBitmap(backgroundOverlayer, blockWidth, blockWidth, false);
        sound = Bitmap.createScaledBitmap(sound, 50, 40, false);
        soundmute = Bitmap.createScaledBitmap(soundmute, 50, 40, false);
        pauseButton = Bitmap.createScaledBitmap(pauseButton, 50, 50, false);
        mBackgroundBitmap = returnDrawBitmap();
        boardGame = mathBoardValues();
        createBitmap = Bitmap.createBitmap(mWidth, blockWidth * 8, Bitmap.Config.ARGB_8888);
        newCanvas = new Canvas(createBitmap);
        headerRect = new Rect(0, 0, mWidth, 80);
        soundRect = new Rect(w - 60, h - 80, w - 10, h - 40);
        pauseRect = new Rect(w - 120, h - 85, w - 70, h - 35);
        questionRect = new Rect(10, mHeight - 20, 110,  mHeight - 100);
        super.onSizeChanged(w, h, oldw, oldh);
    }
    /* (non-Javadoc)
     * @see android.view.View#onMeasure(int, int)
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //Get size requested and size mode
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int width, height = 0;
        //Determine Width
        switch(widthMode){
            case MeasureSpec.EXACTLY:
                width = widthSize;
                break;
            case MeasureSpec.AT_MOST:
                width = Math.min(widthSize, widthSize);
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                width = widthSize;
                break;
        }
        //Determine Height
        switch(heightMode){
            case MeasureSpec.EXACTLY:
                height = heightSize;
                break;
            case MeasureSpec.AT_MOST:
                height = Math.min(heightSize, heightSize);
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                height = heightSize;
                break;
        }
        setMeasuredDimension(width, height);
    }
    /* (non-Javadoc)
     * @see android.view.View#onTouchEvent(android.view.MotionEvent)
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        final int action = event.getAction();
        int x = (int)event.getX();
        int y = (int)event.getY();
        turnSoundOffOn(x, y);
        System.out.println("The coordinates are " + "Y " + y + " x " + x);
        if (action==MotionEvent.ACTION_DOWN) {
            checkCollision(x, y);
            checkSelectedAnswers();
            togglePause(x, y);
            touching = true;
            // check if there is collision
        }
        if(action == MotionEvent.ACTION_UP){
            touching = false;
        }
        invalidate();
        return true;
    }
    private void checkCollision(int x, int y){
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getCoordinate().contains(x, y - 50)){
                    //System.out.println("Pointers  " + y + " " + x);
                    if(gameSquareObject.getSelected() && gameSquareObject.getAnswer()){
                        return;
                    }
                    if(gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                        gameSquareObject.setSelected(false);
                    }else{
                        gameSquareObject.setSelected(true);
                    }
                }
            }
        }
    }
    private void checkSelectedAnswers(){
        int mAnswers = 0;
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                    mAnswers += gameSquareObject.getWrittenNumber();
                }
            }
        }
        if(mAnswers > numberGenerated){
            // reset all the selected columns
            resetAllSelectedAnswers();
        }
        if(mAnswers == numberGenerated){
            //Assign a game point
            currentGamePoint += 100;
            playSound();
            // delete all the current selected buttons
            System.out.println("Remaining values " + checkNumberofButtonRemaining());
            if(assignFinalNumber()){
                numberGenerated = checkNumberofButtonRemaining();
            }else{
                numberGenerated = questionNumberGeneration();
            }
            startCount = 1;
            markButtonForDeleted();
            changeQuestion = true;
        }
    }
    private void resetAllSelectedAnswers(){
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                    gameSquareObject.setSelected(false);
                }
            }
        }
    }
    private void markButtonForDeleted(){
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(gameSquareObject.getSelected()){
                    gameSquareObject.setAnswer(true);
                }
            }
        }
    }
    private void playSound(){
        if(isSoundLoaded && soundOn){
            makeSound.play(soundPoolId, 1, 1, 0, 0, 1);
        }
    }
    private void turnSoundOffOn(int x, int y){
        if(soundRect.contains(x, y)){
            if(soundOn){
                soundOn = false;
            }else{
                soundOn = true;
            }
        }
    }
    private void togglePause(int x, int y){
        if(pauseRect.contains(x, y)){
            if(pauseTimer){
                pauseTimer = false;
                if(initTimer == -1){
                    countTimer = new MyCountDownTimer(startTime, interval);
                    countTimer.start();
                }
                else{
                    countTimer = new MyCountDownTimer(initTimer, interval);
                    countTimer.start();
                }
            }else{
                pauseTimer = true;
                countTimer.cancel();
            }
        }
    }
    // countdowntimer class for display game timer
    public class MyCountDownTimer extends CountDownTimerPausable {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void onFinish() {
            // Game Over Code goes here
            Intent intent = new Intent(context, GameScoreActivity.class);
            intent.putExtra("GAME SCORE", currentGamePoint);
            context.startActivity(intent);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            initTimer = millisUntilFinished;
            gameTimer = millisUntilFinished / 1000;
            invalidate();
        }
    }
    private int checkNumberofButtonRemaining(){
        int numRemaining = 0;
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(!gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                    numRemaining += gameSquareObject.getWrittenNumber();
                }
            }
        }
        return numRemaining;
    }
    private int questionNumberGeneration(){
        int returnValue = 0;
        List<String> data = new ArrayList<String>();
        for(int i = 0; i < 8; i++){
            for(int j = 0; j < 8; j++){
                ButtonClass gameSquareObject = boardGame[i][j];
                if(!gameSquareObject.getSelected() && !gameSquareObject.getAnswer()){
                    String values = String.valueOf(gameSquareObject.getWrittenNumber());
                    data.add(values);
                }
            }
        }
        Collections.shuffle(data);
        returnValue = Integer.parseInt(data.get(0)) + Integer.parseInt(data.get(0));
        return returnValue;
    }
    private boolean assignFinalNumber(){
        int numLeft = checkNumberofButtonRemaining();
        if(numLeft <= 10){
            return true;
        }
        return false;
    }
    private void gameOver(){
        if(numberGenerated == 0){
            Intent intent = new Intent(context, GameScoreActivity.class);
            intent.putExtra("GAME SCORE", currentGamePoint);
            context.startActivity(intent);
        }
    }
//End of the game class
}

We will create a game score activity where we will see the score we got after the game is over.

 

Fragment_game_score.xml

Open the game score layout file and add the below code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <RelativeLayout 
        android:id="@+id/header_region"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="10dp">
        
         <TextView
           android:id="@+id/mtitle"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_alignParentTop="true" 
           android:layout_alignParentLeft="true"
           android:layout_marginLeft="10dp"
           android:layout_marginRight="10dp"
           android:textSize="16sp"
           android:text="@string/game_score"
           android:textColor="@color/colorBlack"/>
          
    </RelativeLayout>
   <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/header_region"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/score"
            android:textSize="20sp"
            android:textColor="@color/colorBlack"
            android:textStyle="bold" />
        
        <TextView
           android:id="@+id/score"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_toRightOf="@+id/textView1"
           android:layout_alignBaseline="@+id/textView1"
           android:text="@string/score_count"
           android:layout_marginLeft="10dp"
           android:textSize="20sp"
           android:textColor="@color/colorBlack"
           android:textStyle="bold" />
    </RelativeLayout>
    <Button
        android:id="@+id/menu"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/relativeLayout1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
        android:textColor="@color/colorBlack"
        android:text="@string/menu" />
</RelativeLayout>

 

GameScoreActivity Class

For the GameScoreActivity class, open the file and add below code to it.

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class GameScoreActivity extends AppCompatActivity{
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE); 
      this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
      
      setContentView(R.layout.activity_game_score);
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      if (savedInstanceState == null) {
         getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
      }
   }
   /**
    * A placeholder fragment containing a simple view.
    */
   public static class PlaceholderFragment extends Fragment {
      public PlaceholderFragment() {
      }
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.fragment_game_score, container, false);
         
         TextView mScore = (TextView)rootView.findViewById(R.id.score);
         int score = ((GameScoreActivity) getActivity()).getGameScore();
         if(score >= 0){
            mScore.setText(String.valueOf(score));
         }        
         
         Button menu = (Button)rootView.findViewById(R.id.menu);          
      
         menu.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
               // TODO Auto-generated method stub
               Intent intent = new Intent(getActivity(), MainActivity.class);
               startActivity(intent);
            }           
         });
         
         return rootView;
      }
   }
   
    private int getGameScore(){
      
      int newIntentValue = -1;
      Intent mIntent = getIntent();
      Bundle mBundle = mIntent.getExtras();
      if(mBundle != null){
         
         newIntentValue = mBundle.getInt("GAME SCORE");
      }
      return newIntentValue;
   }
   /* (non-Javadoc)
    * @see android.support.v7.app.ActionBarActivity#onBackPressed()
    */
   @Override
   public void onBackPressed() {
      
      Intent mIntent = new Intent(GameScoreActivity.this, MainActivity.class);
      startActivity(mIntent);
   }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app to see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

5 Comments

Add a Comment