This is the third and final part of the tutorial series on creating a Tic-Tac-Toe application. See part one about the interfaces and part two about implementing the game logic.
In a previous tutorial I described how you could create a custom view in Android that will take attributes and implement custom logic. This is the approach we will take for creating the full Tic Tac Toe application.
This custom view will be called the TicTacToeTileView. This class will extend an image view to take advantage of the ability of an ImageView to easily draw a graphic.
The constructor for the tile will take four boolean attributes, one for each border of the tile. If the boolean is set than that side of the tile, a black border will be drawn.
Listed below is the code for the constructor.
Since this class implements TicTacToeDrawable, the class is required to implement the setState method. This method will set the tile to one of three possible states - X,O, or blank.
In the TicTacToeTileView's onDraw method is where we will draw the borders. This code is highlighted below.
Now, we will build a layout for the application. In our layout, we will want to reference the custom view that we created in the first step.
We will also have our layout feature two buttons--one to play the "easy" AI and one to play the "hard" AI. We will also include a checkmark to select whether the user can go first or not, and a label that displays the status of the game.
The full code for the layout main.xml is listed below.
Lastly, we must create the GameActivity class. This class will be fairly straightforward. Since most of the logic is contained in the GameDriver package, the GameActivity class will mostly be responsible for listening for button clicks, and passing on the value of these button clicks to the game manager.
The code for the GameActivity class is listed below.
Thanks for taking the time to read through the Tic Tac Toe tutorial series. This is a simple version of the game that we created, but hopefully the tutorial was a great learning experience!
Thanks for your tutorial. Very useful.
Such a useful code for Android Game Development. Thanks for sharing this.