![]() |
VOOZH | about |
In this article, we will be building a Tic Tac Toe Game Project using Java and XML in Android. The Tic Tac Toe Game is based on a two-player game. Each player chooses between X and O. The Player plays one move at a time simultaneously. In a move, a player can choose any position from a 3x3 grid. The goal here is to get three consecutive X or O in a horizontal, vertical, or diagonal direction. There will be a single activity in this application. This activity will show a 3x3 grid. The status of the game will be displayed at the bottom.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Add Images: All the images are listed below. Save them in your drawable folder in resources. Go to the app > res > drawable and paste the following files:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
Add fonts to be used in the application: refer to How to Add Custom Fonts in Android.
The XML codes are used to build the structure of the activity as well as its styling part. It contains a TextView at the very top of the activity to display the title. Then it contains an ImageView of the grid and in each box, there is an ImageView. At the bottom of the activity, there is a TextView to display the status of the game.
Below is the code for the activity_main.xml file.
Main Activity is the one which we will first access while opening the application. So, let us add Functionalities to the Start Button and Maintain the Score of Player A and Player B with it.
After going through that main Activity we will start with our game. And the game Activity java is mentioned below:
We will create a two-dimensional array that will store all the winning positions. We will create a function that will run when a box inside the grid is clicked. Inside this function, we will first check if the box selected is empty or not. After that, we will set the image of X if the last move was of O or we will set the image of O if the last move was of X. Then we will check if the move has reached the move position and then reset the game. Below is the code for the Game.java file. Comments are added inside the code to understand the code in more detail.
We Need to make certain changes in the dimensions, string and colors so use the layouts mentioned above without any error
Note: The Application we have created is like a template for your Notes Application you can make changes in it as you want.
The GitHub Link for the Application is : Click Here to access the Complete Code for Tic Tac Toe Android Application