BUILD A TIC TAC TOE GAME
BUILD A TIC TAC TOE GAME
Tic Tac Toe is a classic paper-and-pencil game for two players who take turns marking X’s and O’s in a 3×3 grid. The objective of the game is to be the first player to get three of their marks in a row, either horizontally, vertically, or diagonally.
In an Android version of Tic Tac Toe, the game is played on the screen of a mobile device. The player can touch the cells on the screen to place their mark (either X or O) on the board. The game logic checks for winning conditions after each turn and determines if the game has been won, lost, or tied.
Creating a tic tac toe game in Android is a fun and engaging way to learn about Android programming. Tic tac toe, also known as noughts and crosses or Xs and Os, is a simple game that can be played with pencil and paper. In this tutorial, we will explore how to create a tic tac toe game in Android using Java and the Android Studio development environment.
Before we dive into the code, let’s first understand the rules of the game. Tic tac toe is played on a 3×3 grid, and the objective of the game is to place three of your symbols (either X or O) in a row, column, or diagonal. The game can be played by two players, or a single player can play against the computer.
CREATE A NEW ANDROID PROJECT
To create a new Android project, open Android Studio and click on “Start a new Android Studio project” on the welcome screen. In the “Create New Project” dialog, give your project a name, select the minimum SDK version, and choose an activity template. For this tutorial, we will choose the “Empty Activity” template. Click “Finish” to create the project.
XML LAYOUT USER INTERFACE
The user interface of our tic tac toe game will consist of a 3×3 grid of buttons, a reset button, and a text view to display the game result. To add these UI elements, open the activity_main.xml file located in the res/layout folder. Replace the contents of the file with the following code:
<?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/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/result_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tic Tac Toe Game" android:textSize="24sp" android:layout_centerHorizontal="true" android:layout_marginTop="32dp"/> <GridLayout android:id="@+id/grid_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/result_text_view" android:layout_marginTop="32dp" android:columnCount="3" android:rowCount="3" android:alignmentMode="alignMargins" android:columnOrderPreserved="false"> <Button android:id="@+id/button1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="0,0" android:onClick="onButtonClick"/> <Button android:id="@+id/button2" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="0,1" android:onClick="onButtonClick"/> <Button android:id="@+id/button3" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="0,2" android:onClick="onButtonClick"/> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="1,0" android:onClick="onButtonClick"/> <Button android:id="@+id/button5" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="1,1" android:onClick="onButtonClick"/> <Button android:id="@+id/button6" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="1,2" android:onClick="onButtonClick"/> <Button android:id="@+id/button7" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="2,0" android:onClick="onButtonClick"/> <Button android:id="@+id/button8" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="2,1" android:onClick="onButtonClick"/> <Button android:id="@+id/button9" android:layout_width="0dp" android:layout_height="wrap_content" android:text="" android:layout_columnWeight="1" android:layout_rowWeight="1" android:tag="2,2" android:onClick="onButtonClick"/> </GridLayout> <Button android:id="@+id/reset_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Reset" android:layout_below="@id/grid_layout" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:onClick="onResetButtonClick"/> </RelativeLayout>
In this code snippet, we have added a TextView to display the game result, a GridLayout to display the 3×3 grid of buttons, and a Reset button to reset the game. The GridLayout contains nine buttons, one for each cell of the grid. The buttons have a tag attribute that stores the row and column index of the cell, which will be used later to determine which cell was clicked.
CREATE THE MAIN ACTIVITY CLASS
Now that we have created the user interface, let’s create the MainActivity class that will handle the game logic. Open the MainActivity.java file located in the app/java/com.example.tictactoe folder and replace the contents of the file with the following code:
package com.panrum.tictactoe; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private int[][] board = new int[3][3]; private int currentPlayer = 1; private boolean gameEnded = false; private TextView resultTextView; private Button[][] buttons = new Button[3][3]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setContentView(R.layout.activity_main); resultTextView = findViewById(R.id.result_text_view); resetBoard(); } public void onButtonClick(View view) { if (gameEnded) { return; } Button button = (Button) view; String tag = (String) button.getTag(); int row = Integer.parseInt(tag.substring(0, 1)); int col = Integer.parseInt(tag.substring(2, 3)); if (board[row][col] != 0) { return; } board[row][col] = currentPlayer; button.setText(currentPlayer == 1 ? "X" : "O"); button.setBackgroundResource(currentPlayer == 1 ? R.drawable.x_button : R.drawable.o_button); if (checkForWinner()) { resultTextView.setText(currentPlayer == 1 ? "X wins!" : "O wins!"); gameEnded = true; return; } if (checkForDraw()) { resultTextView.setText("Draw!"); gameEnded = true; return; } currentPlayer = currentPlayer == 1 ? 2 : 1; resultTextView.setText(currentPlayer == 1 ? "Player X's turn" : "Player O's turn"); } public void onResetButtonClick(View view) { resetBoard(); } private boolean checkForDraw() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == 0) { // there is an empty cell, game is not yet draw return false; } } } // all cells are occupied, game is draw return true; } private void resetBoard() { gameEnded = false; currentPlayer = 1; resultTextView.setText("Player X's turn"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = 0; buttons[i][j] = findViewById(getResources().getIdentifier("button" + i + j, "id", getPackageName())); buttons[i][j].setText(""); buttons[i][j].setBackgroundResource(android.R.drawable.btn_default); } } } private boolean checkForWinner() { for (int i = 0; i < 3; i++) { if (board[i][0] != 0 && board[i][0] == board[i][1] && board[i][0] == board[i][2]) { return true; } } for (int i = 0; i < 3; i++) { if (board[0][i] != 0 && board[0][i] == board[1][i] && board[0][i] == board[2][i]) { return true; } } if (board[0][0] != 0 && board[0][0] == board[1][1] && board[0][0] == board[2][2]) { return true; } if (board[0][2] != 0 && board[0][2] == board[1][1] && board[0][2] == board[2][0]) { return true; } return false; } }
CONCLUSION:
In conclusion, we have successfully built a Tic Tac Toe game using Java and XML in Android. The game allows two players to select between X and O, and take turns making moves on a 3×3 grid. The goal is to get three consecutive X or O in a horizontal, vertical, or diagonal direction. We have implemented the game logic using a two-dimensional array, and added functionality to check for winning positions, reset the game, and display the status of the game. This project serves as a great introduction to Android app development, and provides a solid foundation for more complex game development in the future.