Coding a simple android maths game.

In this article you will be taught how to build a simple maths game for android. In this game we will be asked mathematics questions based on addition, subtraction, multiplication and finding the quotient. We will have to select the correct option from the given choices,  and our score will be calculated based on our correct answers. As we advance further in game, the questions become more tougher and more random, and involve bigger operands. If we answer a question wrong, our score is displayed. If the score is highest, it will start being displayed in highscore section of main menu. This project requires basic proficiency in android development.

First we will create a new project in android studio with MainActivity as starting activity and activity_main.xml as its layout. MainActivity will serve as main menu for game. Type the following code in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/img2"
tools:context="com.example.dell.mathmayhem.GameActivity"
android:theme="@style/AlertDialog.AppCompat">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="@+id/textPartA"
android:layout_alignTop="@+id/textOperator"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="55dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="*"
android:id="@+id/textOperator"
android:layout_alignTop="@+id/textPartB"
android:layout_centerHorizontal="true"
android:minHeight="30dp"
android:minWidth="30dp"
android:textSize="55dp"
android:textIsSelectable="false" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="@+id/textPartB"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="45dp"
android:textSize="55dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="="
android:id="@+id/textView2"
android:textSize="55dp"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/textOperator"
android:layout_alignStart="@+id/textOperator" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice1"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="101dp"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice2"
android:layout_alignTop="@+id/buttonChoice1"
android:layout_centerHorizontal="true"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice3"
android:layout_alignTop="@+id/buttonChoice2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: 0"
android:id="@+id/textScore"
android:minWidth="90dp"
android:minHeight="30dp"
android:textColor="@color/abc_primary_text_disable_only_material_dark"
android:layout_above="@+id/textPartA"
android:layout_toLeftOf="@+id/buttonChoice2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Level: 1"
android:id="@+id/textLevel"
android:minHeight="30dp"
android:minWidth="90dp"
android:layout_alignTop="@+id/textScore"
android:layout_alignRight="@+id/buttonChoice3"
android:layout_alignEnd="@+id/buttonChoice3"
android:layout_toRightOf="@+id/buttonChoice2"
android:layout_toEndOf="@+id/buttonChoice2"
android:textColor="@color/abc_primary_text_disable_only_material_dark" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/hint"
android:layout_marginTop="50dp"
android:layout_below="@+id/textOperator"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Edit the tools:context attribute according to your project name. The layout generated by above code looks like this:

Screenshot_2017-06-25-12-40-49.png

Now create a new activity called GameActivity with layout as activity_game.xml. It will represent the playing screen of the game. Enter the following code in activity_game.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/img2"
tools:context="com.example.dell.mathmayhem.GameActivity"
android:theme="@style/AlertDialog.AppCompat">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="@+id/textPartA"
android:layout_alignTop="@+id/textOperator"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="55dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="*"
android:id="@+id/textOperator"
android:layout_alignTop="@+id/textPartB"
android:layout_centerHorizontal="true"
android:minHeight="30dp"
android:minWidth="30dp"
android:textSize="55dp"
android:textIsSelectable="false" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="@+id/textPartB"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="45dp"
android:textSize="55dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="="
android:id="@+id/textView2"
android:textSize="55dp"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/textOperator"
android:layout_alignStart="@+id/textOperator" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice1"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="101dp"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice2"
android:layout_alignTop="@+id/buttonChoice1"
android:layout_centerHorizontal="true"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/buttonChoice3"
android:layout_alignTop="@+id/buttonChoice2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:minWidth="120dp"
android:minHeight="60dp"
android:textSize="40dp"
android:textColor="@android:color/holo_red_light"
android:backgroundTint="@color/highlighted_text_material_dark" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: 0"
android:id="@+id/textScore"
android:minWidth="90dp"
android:minHeight="30dp"
android:textColor="@color/abc_primary_text_disable_only_material_dark"
android:layout_above="@+id/textPartA"
android:layout_toLeftOf="@+id/buttonChoice2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Level: 1"
android:id="@+id/textLevel"
android:minHeight="30dp"
android:minWidth="90dp"
android:layout_alignTop="@+id/textScore"
android:layout_alignRight="@+id/buttonChoice3"
android:layout_alignEnd="@+id/buttonChoice3"
android:layout_toRightOf="@+id/buttonChoice2"
android:layout_toEndOf="@+id/buttonChoice2"
android:textColor="@color/abc_primary_text_disable_only_material_dark" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/hint"
android:layout_marginTop="50dp"
android:layout_below="@+id/textOperator"
android:layout_centerHorizontal="true" />

</RelativeLayout>

The layout will look like this:

Screenshot_2017-06-25-12-41-16
Now create two more activities named HscoreActivity and ScoreviewActivity. HscoreActivity will represent game over screen with final score in it, and ScoreviewActivity will represent highscore section of main menu.
Enter the following code in activity_hscore.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/unnamed"
tools:context=".HscoreActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/hsText"
android:textSize="40dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Menu"
android:id="@+id/hsButton"
android:layout_marginBottom="66dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:background="@color/accent_material_dark" />

<TextView
android:text="GAME OVER!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"
android:id="@+id/textView4"
android:textSize="55sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score"
android:id="@+id/hsHeader"
android:textSize="50sp"
android:textAlignment="center"
android:layout_below="@+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp" />
</RelativeLayout>

Layout looks like this:

Screenshot_2017-06-25-12-41-45
Now add the code below in activity_scoreview.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_scoreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/unnamed"
tools:context="com.example.dell.mathmayhem.ScoreviewActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/scoretext"
android:textSize="40sp"
android:textColor="#001111"
android:textAlignment="center"
android:text="0" />

<TextView
android:text="High Score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="@+id/textView5"
android:textSize="60sp"
android:textStyle="normal|bold"
android:textColor="#112299" />

<Button
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="54dp"
android:id="@+id/backbutton"
android:textSize="20sp"
android:background="@color/colorPrimaryDark" />
</RelativeLayout>

Layout screenshot:

Screenshot_2017-06-25-12-41-26

Now let us add the java codes:
MainActivity.java:

package com.example.dell.mathmayhem;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.app.Activity;
import android.content.Intent;

import com.example.dell.mathmayhem.R;

public class MainActivity extends Activity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttonPlay =
(Button)findViewById(R.id.buttonPlay);//associate button buttonPlay with thig having id buttonPlay
final Button buttonhscore =
(Button)findViewById(R.id.hscorebutton);
final Button buttonquit =
(Button)findViewById(R.id.quitbutton);

buttonPlay.setOnClickListener(this);//enable clicking on buttonPlay
buttonhscore.setOnClickListener(this);
buttonquit.setOnClickListener(this);
}
@Override
public void onClick(View view) {//click detecting method with input view of type View
switch (view.getId()){
case R.id.buttonPlay:
Intent i;//variable denoting some sort of activity
i = new Intent(this, GameActivity.class);//associate clicking of buttonPlay with launching of GameActivity class
startActivity(i);// start above activity
break;

case R.id.hscorebutton:
Intent j = new Intent(this, ScoreviewActivity.class);
startActivity(j);
finish();
break;
case R.id.quitbutton:
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
break;
}
}
}

Don’t forget to change the package name according to your own project.

GameActivity.java:

package com.example.dell.mathmayhem;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

public class GameActivity extends Activity implements View.OnClickListener {//GameActivity has things with clicking ability
int correctAnswer;
Button buttonObjectChoice1;
Button buttonObjectChoice2;
Button buttonObjectChoice3;
TextView textObjectPartA;
TextView textObjectPartB;
TextView operator;
TextView textObjectScore;
TextView textObjectLevel;
public static int currentScore = 0;
int currentLevel = 1;
int answerGiven;
int wrongAnswer1;
int wrongAnswer2;
TextView texthint;
boolean correctTrueOrFalse;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);

textObjectPartA =
(TextView) findViewById(R.id.textPartA);//associate variable textObjectPartA to "thing with id textPartA"
textObjectPartB =
(TextView) findViewById(R.id.textPartB);
operator =
(TextView) findViewById(R.id.textOperator);
texthint = (TextView) findViewById(R.id.hint);
textObjectScore = (TextView) findViewById(R.id.textScore);
textObjectLevel = (TextView) findViewById(R.id.textLevel);
buttonObjectChoice1 =
(Button) findViewById(R.id.buttonChoice1);//associate variable buttonObjectChoice1 to "thing with id buttonChoice1"
buttonObjectChoice2 =
(Button) findViewById(R.id.buttonChoice2);
buttonObjectChoice3 =
(Button) findViewById(R.id.buttonChoice3);

buttonObjectChoice1.setOnClickListener(this);//enable clicking on buttonObjectChoice1
buttonObjectChoice2.setOnClickListener(this);
buttonObjectChoice3.setOnClickListener(this);
setQuestion();

}

@Override
public void onClick(View view) {// method onClick with parameter view of type View
//declare a new int to be used in all the cases

switch (view.getId()) {//get id of clicked thing
case R.id.buttonChoice1:
//initialize a new int with the value contained in buttonObjectChoice1
//Remember we put it there ourselves previously
answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
break;
case R.id.buttonChoice2:
//same as previous case but using the next button
answerGiven = Integer.parseInt("" +
buttonObjectChoice2.getText());
break;
case R.id.buttonChoice3:
//same as previous case but using the next button
answerGiven = Integer.parseInt("" +
buttonObjectChoice3.getText());

break;

}
updateScoreAndLevel(answerGiven);
if (correctTrueOrFalse){
setQuestion();
}
else{
Intent myIntent = new Intent(GameActivity.this, HscoreActivity.class);
myIntent.putExtra("highscore", currentScore);
GameActivity.this.startActivity(myIntent);
finish();
}
}

void setQuestion() {
//generate the parts of the question
int numberRange = currentLevel * 3;
Random randInt = new Random();
int partA = (numberRange - 3) + randInt.nextInt(6);
partA++;//don't want a zero value
int partB = randInt.nextInt(numberRange);
partB++;//don't want a zero value

int symbol = randInt.nextInt(4);
if (symbol == 0) {
operator.setText("+");
texthint.setText("");
correctAnswer = partA + partB;
}
if (symbol == 1) {
operator.setText("-");
texthint.setText("");
correctAnswer = partA - partB;
}
if (symbol == 2) {
operator.setText("*");
texthint.setText("");
correctAnswer = partA * partB;
}
if (symbol == 3) {
operator.setText("/");
texthint.setText(" find quotient");
correctAnswer = partA / partB;
}

do {
wrongAnswer1 = randInt.nextInt(10) + (correctAnswer - 5);
wrongAnswer2 = randInt.nextInt(10) + (correctAnswer - 5);
}
while (wrongAnswer1 == wrongAnswer2 || wrongAnswer1 == correctAnswer || wrongAnswer2 == correctAnswer);

textObjectPartA.setText("" + partA);
textObjectPartB.setText("" + partB);
//A number between 0 and 2
int buttonLayout = randInt.nextInt(3);
switch (buttonLayout) {
case 0:
buttonObjectChoice1.setText("" + correctAnswer);
buttonObjectChoice2.setText("" + wrongAnswer1);
buttonObjectChoice3.setText("" + wrongAnswer2);
break;
case 1:
buttonObjectChoice2.setText("" + correctAnswer);
buttonObjectChoice3.setText("" + wrongAnswer1);
buttonObjectChoice1.setText("" + wrongAnswer2);
break;
case 2:
buttonObjectChoice3.setText("" + correctAnswer);
buttonObjectChoice1.setText("" + wrongAnswer1);
buttonObjectChoice2.setText("" + wrongAnswer2);
break;
}
}

void updateScoreAndLevel(int answerGiven) {
if (isCorrect(answerGiven)) {
for (int i = 1; i <= currentLevel; i++) {
currentScore = currentScore + i;
}
currentLevel++;
}

textObjectScore.setText("score: " + currentScore);
textObjectLevel.setText("level: " + currentLevel);
}

boolean isCorrect(int answerGiven) {
if (answerGiven == correctAnswer) {//YAY!
Toast.makeText(getApplicationContext(), "Well done!",
Toast.LENGTH_SHORT).show();
correctTrueOrFalse = true;
} else {//Uh-oh!
correctTrueOrFalse = false;
}
return correctTrueOrFalse;
}
}

HscoreActivity.java:

package com.example.dell.mathmayhem;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.dell.mathmayhem.ScoreviewActivity;

public class HscoreActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_hscore);
TextView hshead= (TextView) findViewById(R.id.hsHeader);
TextView hsscore= (TextView) findViewById(R.id.hsText);
Intent intent = getIntent();
int hs = intent.getIntExtra("highscore", 0);
super.onCreate(savedInstanceState);
hshead.setText("Score");
hsscore.setText(""+hs);
ScoreviewActivity instance=new ScoreviewActivity();
if (instance.curhscore<hs){
SharedPreferences mPrefs = getSharedPreferences("hsvalue", 0);
//Give any name for //preference as I have given "hsvalue" and value 0.
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("hskey", hs);
// give key value as "hskey" you mentioned and value what you want to store
editor.commit();
}
final Button mainmenu =
(Button)findViewById(R.id.hsButton);
mainmenu.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mainmenuintent= new Intent(HscoreActivity.this, MainActivity.class);
HscoreActivity.this.startActivity(mainmenuintent);
finish();
}
});

}

}

ScoreviewActivity.java:

package com.example.dell.mathmayhem;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ScoreviewActivity extends AppCompatActivity {
public int curhscore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scoreview);
TextView textscore=(TextView) findViewById(R.id.scoretext);

SharedPreferences mPrefs = getSharedPreferences("hsvalue",0);
int x = mPrefs.getInt("hskey", 0);
textscore.setText(""+String.valueOf(x));

curhscore=Integer.parseInt("" + textscore.getText());
final Button back= (Button) findViewById(R.id.backbutton);
back.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent backintent= new Intent(ScoreviewActivity.this, MainActivity.class);
ScoreviewActivity.this.startActivity(backintent);
finish();
}
});
}
}

Now run the code on an android device. It runs smoothly. You can add more features to it like saving game state on pausing, resuming etc. retry button in game, list of top 5 scores created by you instead of a single highscore etc.

Leave a Reply

Your email address will not be published. Required fields are marked *