Saturday 4 November 2017

Computer Thinks - Android Game Development


Computer Thinks

Welcome to the world of mobile games development. The name of the game we shall be creating today is known as Computer Thinks. I choose this to be my first game because it is easy, friendly and contain the basic of what is needed to develop a fully advance game. Computer thinks is all about generating random numbers which the player will try as much as possible to guess the random numbers.
You will be learning how to use your mathematics skills, Java and putting finishing touches with android. We are going to create a simple guessing game where the player is allowed to guess a certain number base on the given range. If the player guesses too high, a text message will be display to tell the player that his guess is higher than what the computer is thinking likewise, too low and correct. I called this game “Computer Thinks”. To keep things simple, we shall choose our range of number to be between 0 and 10. You can choose yours to be between 0 and 100 but let’s face the fact that I am just a human trying to know what the computer thinks. Therefore we keep it simple.

Procedures
1. An edit text for inputting data
2. A button to get answers
3. A textview for displaying answer if wrong or right
4. The player input a number ranging from 0 to 10.
5. The player click on the button to know what the computer is thinking
6. The computer tells the player if the number inputted is right or wrong (and tells if it is smaller than what the computer is thinking or bigger than it).
7. If the players wins, a second activity with an image is shown on the screen
I
Clearly, from the above procedures, we shall be dealing with the BET classes. BET stands for Button, EditText and TextView.  To keep things interesting, our game will be generating random number between 0 and 10.

activity_main
1. Create a new project in android studio and name it Guessing Game. Under the activity_main.java, populate it with the following code snippet
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="unycorperation.computerthinks.MainActivity">

    <
TextView
       
android:id="@+id/textView"
        android:textSize="45dp"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.631"

        android:layout_below="@+id/button"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="67dp" />



    <EditText

        android:id="@+id/editText"

        android:layout_width="368dp"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="61dp"

        android:ems="10"

        android:hint="Only Numbers are allowed."

        android:inputType="number"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        tools:layout_editor_absoluteY="112dp" />



    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Button"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        tools:layout_editor_absoluteY="208dp"

        android:layout_below="@+id/editText"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="68dp" />



</RelativeLayout>

activity_another.xml
2. Create another layout file and name it activity_another. Under activity_another, populate it with the following statement.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent">



    <ImageView

        android:id="@+id/imageView"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_weight="1"

        app:srcCompat="@android:drawable/sym_def_app_icon" />

</LinearLayout>

MainActivity.java
3. In your MainActivity.java populate the following statement
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
    Button button;
    EditText ed;
    TextView tv;
    int guesesRemaining = 3;
    int guessMade = 0;
    String gameState;
    boolean gameWonBoolean = false;
    private Random ran;
    private int computerThink;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        ed = (EditText) findViewById(R.id.editText);
        tv = (TextView) findViewById(R.id.textView);
        ran = new Random();
         computerThink = ran.nextInt(11);
        //Toast.makeText(getApplicationContext(), "Computer think " + //computerThink, Toast.LENGTH_LONG).show();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guesesRemaining = guesesRemaining - 1;
                guessMade = guessMade + 1;
                gameState = "Gueses Remaining: " + guesesRemaining + ", "
                        + "Guesses Made: " + guessMade;
                Toast.makeText(getApplicationContext(), "Game State: " + gameState, Toast.LENGTH_LONG).show();
                int input = Integer.parseInt(ed.getText().toString());
                if(guesesRemaining<1){
                    gameWonBoolean = false;
                    endGame();
                }
                if (input > computerThink) {
                    Toast.makeText(getApplicationContext(), "Number is too big " + gameState, Toast.LENGTH_SHORT).show();
                    tv.setTextColor(Color.RED);
                    tv.setText("Number is too big " + gameState);
                } else if (input < computerThink) {
                    Toast.makeText(getApplicationContext(), "Number is too small " + gameState, Toast.LENGTH_SHORT).show();
                    tv.setTextColor(Color.BLUE);
                    tv.setText("Number is too Small " + gameState);
                } else if (input == computerThink) {
                    gameWonBoolean = true;
                    endGame();
                }
            }
        });
    }
    public void endGame() {
        if (gameWonBoolean == true) {
            tv.setTextColor(Color.GREEN);
            tv.setText("You are Right");
            Intent i = new Intent(getApplicationContext(), AnotherActivity.class);
            startActivity(i);
            button.setClickable(false);
        } else {
            Toast.makeText(getApplicationContext(), "You have exaulted your gueses. you have " + gameState, Toast.LENGTH_SHORT).show();
        button.setClickable(false);
        }
    }
}

AnotherActivity.java
4. Create another class called AnotherActivity.java. Populate the class with the following statement
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by user on 03-Nov-17.
 */

public class AnotherActivity extends AppCompatActivity {

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

AndroidManifest.xml
5. Input the following statement in bold to your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="unycorperation.computerthinks">



    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <activity android:name=".AnotherActivity"></activity>

    </application>



</manifest>

6. Click on shift + f10 on your keyboard to run the program































  
How it works
The main purpose of the game is to input a certain number in the edit text box. If the number corresponds to the random number generated by the computer then you win else continue playing. The truth is this; the game doesn’t have an end. It continues until you get it right. To avoid that complexity, the variable guessesRemaining was instantiated to 3. This means that the user has only 3 times to play the end after which either he wins or lose. Another variable known as guessMade is used to count how many guesses the player has taken. The gameState variable gives the total information about the game. The Boolean variable shows if the player is in a winning state or losing state.
int guesesRemaining = 3;
   
int guessMade = 0;
    String
gameState;
   
boolean gameWonBoolean = false;
At this point, it should be well noted that variable control certain things that goes on in a game. They act as game object where they are used to represent quantities or shape. The random class from java helps to create random number within a certain range usually from 0 to whatever value.
private Random ran;
   
private int computerThink;
ran = new Random();
        
computerThink = ran.nextInt(11);
Here, the computer is allowed to generate number between 0 and 10 making it eleven numbers if counted from 0. It the expression is written in form of ran.nextInt(101) The computer will be allowed to generate numbers between 0 and 100. If counted from 0 the total number is 101. At this point, it should be well noted that the random number generated is place in the onCreate() method and not the button click method. Placing  the random number on a button click method enables the computer to generate random number each time the button is clicked. Also, we use the private keyword to protect the random class. This is to avoid error when the game is running.
guesesRemaining = guesesRemaining - 1;
               
guessMade = guessMade + 1;
               
gameState = "Gueses Remaining: " + guesesRemaining + ", "
                       
+ "Guesses Made: " + guessMade;
When the button is click, 1 is minus from the guess remaining. In the actual world the guess remaining is instantiated to 3. Therefore, we have 3 – 1 = 2. Also the guess made is 0 making it 0 + 1 = 1. If the button is click for the second time,
Guess remaining = 2 – 1 = 1
Guesss made = 1 + 1 = 2
If the button is click for the third time,
Guess remaining will be 1 – 1 = 0 and
Guess made will be 2 + 1 = 3
The game state gives the total information of our game regarding the guesseRemaining and guessMade.
int input = Integer.parseInt(ed.getText().toString());
               
if(guesesRemaining<1){
                   
gameWonBoolean = false;
                    endGame();
                }
Most times, characters enter in the edit text is always treated as strings. To convert a string to an integer we used the Integer.parseInt(ed.getText().toString()) This enable every character enters in the edit text to be treated as an integer. The only time we can get our guessesRemaining to be 0 is when the the button is click three times. We use an if statement to check if the guesesRemaining is 0 and called it an end game using the endGame() function. Also our Boolean variable is set to false indicating the game has not be won.
At this point, it should be well noted that Boolean statement takes just two values which are true or false, right or wrong, 0’s or 1’s, on or off etc.
if (input > computerThink) {
                    Toast.makeText(getApplicationContext(),
"Number is too big " + gameState, Toast.LENGTH_SHORT).show();
                   
tv.setTextColor(Color.RED);
                   
tv.setText("Number is too big " + gameState);
                }
else if (input < computerThink) {
                    Toast.makeText(getApplicationContext(),
"Number is too small " + gameState, Toast.LENGTH_SHORT).show();
                   
tv.setTextColor(Color.BLUE);
                   
tv.setText("Number is too Small " + gameState);
                }
else if (input == computerThink) {
                   
gameWonBoolean = true;
                    endGame();
We check for if numbers inputted is greater than the number generated by the computer. We show the game state in a toast message and a textview. Likewise, we check if the number inputted is less than the generated number. Finally, we check if the number is equal to the number generated by the computer. The Boolean statement is set to true and the endGame() function is called.
At this point, it should be well noted that function allows you to jump between statements. It enables you to gain access even when it is impossible. Put simply as, functions control everything about a game.
public void endGame() {

        if (gameWonBoolean == true) {

            tv.setTextColor(Color.GREEN);

            tv.setText("You are Right");

            Intent i = new Intent(getApplicationContext(), AnotherActivity.class);

            startActivity(i);

            button.setClickable(false);

        } else {

            Toast.makeText(getApplicationContext(), "You have exahausted your gueses. you have " + gameState, Toast.LENGTH_SHORT).show();

        button.setClickable(false);

        }

    }

}

The endGame() method is declared. We use the Boolean statement to check if the game has been set to true. If yes, display the “you are right” text in the textview and navigate you to a new class using intent.
If found that the true value is not true, it means that you have exhausted your guesses and we set the button clickable to false meaning that you will be able to click on the button.
In the activity_main.xml, it should be well noted that we used the android attribute inputType=”number” to allow only numbers to be inserted in the edit text box.
android:hint="Only Numbers are allowed."
       
android:inputType="number"
Therefore, it will be impossible for a player to enter string values since in this game we don’t need to use string. The activity_another.xml has only an ImageView. This is to notify players that they won. Meaning a change of content in a screen indicate you win. Also, we include the <activity android:name=".AnotherActivity"></activity> in our AndroidManifest.xml. This will make the navigation to another activity possible if the game has been won.
Conclusion:

The computer think game generates a number between 0 and 10. This can be achieved through the java random class. Variable is used in representing certain object, quantities and shape. A function controls almost everything about a game. The Boolean statement gives your game more controls on how it behaves. When number are entered in the edit text field, the computer checks if the number is greater than, less than or equal to the number it generate. If the number is equal to the number generated by the computer then the player wins as the player lose. The player has three chances to get it right or else game over. This example is Signed, Sealed, Saved and Delivered. SEE YOU IN THE NEXT TUTORIAL.


















THE ANDROID MANAGER

Buy THE ANDROID MANAGER Now

No comments:

Post a Comment