Learning Java by creating a Tic-Tac-Toe game
Starting out learning java can be a daunting task even if you have prior programming experience. Java is a fundamental language for Software Engineers and object oriented programming in general. This project will focus on a simple game of creating a GUI to display a Tic-Tac-Toe game built with a MVC architecture. Although I cannot share source code I will walk through the role of the model, view & controller and post an executable jar file.
The model is in charge of storing and manipulating the data. The model in this case would have two variables, an Enum type player and a board array of length 3x3. The models constructor will create an instance of the board and set the players turn to X. From there we will write the methods; move, getTurn, isGameOver, getWinner, getBoard, getMarkAt, validateRowCol and a toString. These methods will hold, manipulate and give data to both the controller and view. We create a read only interface of the model as well so that the view can take in a read only model as one of its fields to display data from the game to the user.
Next, the controller is the link between the model and the view. The controller will take inputs from the user & the view, handle them as valid or invalid and pass a command to the model to execute. The controller is slightly simpler and only has two methods; playGame and a private method to handle a cell click. The driver file will call the playGame method to start the view and carry out the actions of the game from there. The handle cell click method will determine if the mouse click is in a valid location and execute the move if it is. If that move is deemed invalid, then the move is not executed and the view does not change.
Finally, we have the view class. The view takes in user inputs and determines where and when to display the models read only data. The view constructor takes in a read only model and creates the view using a BorderLayout and other components of the java swing library. As seen in the image below I created a board with a JLabel on the bottom of the game state.
The view interface has public methods; refresh and addClickListener as well as an imbedded class that extends the JPanel and overrides the paint component method. Each time a user clicks on the screen, the views click listener passes the coordinates of the click to the controller and determines if the click is valid. After a successful click, the view is refreshed and the paint component method searches through locations on the grid to paint an X or O depending on the cell values.
After the game is over the tic tac toe GUI example would like the image below.
There is the framework for the MVC software structure that can be applied and expanded to more complicated games or challenges.
The link to a README.md and executable jar file can be found here: https://github.com/colaso96/TicTacToe/blob/main/tictactoe.jar