In this article, we are gonna make a basic 2 player Tic-Tac-Toe game using java swing.
Create a new class TicTacToe.java where we will make the interface to play the game. This is what we are gonna do.
1. Declare a final variable SIZE and set it to 3, to represent row and column of 3X3 grid for tic-tac-toe.
2. Declare controls to be added to GUI.
3. Initial Conditions -
Create a new class TicTacToe.java where we will make the interface to play the game. This is what we are gonna do.
1. Declare a final variable SIZE and set it to 3, to represent row and column of 3X3 grid for tic-tac-toe.
2. Declare controls to be added to GUI.
3. Initial Conditions -
- Set player1 to true and player2 to false.
- Set gameOver to false, and gameDraw to false as well.
- Set player1Symbol to "X".
- Set player2Symbol to "O".
4. Create a default constructor where all the controls will be initialized.
5. Use setBounds(x,y,width,height) on each controls to set it's location on a panel or frame.
6. We will create a method to set symbol "X" or "O" when player plays it's turn.
7. We will create a method to check if any player won. This method will be called after every turn.
8. After game over, user will be asked if they want to play again.
9. We will create a method to reset the game.
Create a new driver class TicTacToeDriver.java . This class will only have main method to create a frame and run the program.
COMPLETE CODE-
TicTacToe.java
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class TicTacToe extends JFrame implements ActionListener { public final static int SIZE = 3; // Button array which contains 9 buttons for 3X3 grid of tic-tac-toe static JButton buttonArray[][]; // This is a label to denote player's turn static JLabel playerLabel; // Initial Conditions static boolean player1 = true; static boolean player2 = false; static boolean gameOver = false; static boolean gameDraw = false; String player1Symbol = "X"; String player2Symbol = "O"; // X,Y to set controls on proper location int X = 10, Y = 10; // Constructor to initialize controls public TicTacToe() { // Create a panel where all controls will be added // And then this panel will be added to JFrame // Set panel's location and it's layout as null JPanel panel = new JPanel(); panel.setBounds(50, 40, 200, 400); panel.setLayout(null); buttonArray = new JButton[SIZE][SIZE]; // Set playerLabel with text Player 1 and set it's location playerLabel = new JLabel("Player 1"); playerLabel.setBounds(120, 10, 100, 30); // Create nested loop , to initialize 9 JButtons // Set their location // Add ActionListener to them to handle click events // Then add buttons to panel for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { buttonArray[i][j] = new JButton(); buttonArray[i][j].addActionListener(this); buttonArray[i][j].setBounds(X, Y, 50, 50); X += 60; // If 3 buttons are added // Increment Y to set buttons to next line if (j == SIZE - 1) { Y += 60; X = 10; } panel.add(buttonArray[i][j]); } } // Set layout of frame to be null // Add playerLabel to frame // Add panel to frame setLayout(null); add(playerLabel); add(panel); } // This method handles click events of buttons @Override public void actionPerformed(ActionEvent e) { // If game is not over yet if (gameOver == false) { // If it was player1 chance // Set player1 to false, player2 to true (For next chance) // Call setSymbol and pass- // the button which was clicked, player1Symbol and "Player 2" // Call checkWin function to see if player 1 won if (player1) { player1 = false; player2 = true; setSymbol((JButton) e.getSource(), player1Symbol, "Player 2"); checkWin("Player 1"); } // Else it was player2 chance // Set player2 to false, player1 to true (For next chance) // Call setSymbol and pass- // the button which was clicked, player2Symbol and "Player 1" // Call checkWin function to see if player 2 won else { player2 = false; player1 = true; setSymbol((JButton) e.getSource(), player2Symbol, "Player 1"); checkWin("Player 2"); } } } public static void setSymbol(JButton button, String symbol, String labelText) { // Set text on button // Disable the button // set text on label button.setText(symbol); button.setEnabled(false); playerLabel.setText(labelText); } public static void checkWin(String currentPlayer) { // Get text of all 9 buttons String valueAt00 = buttonArray[0][0].getText(); String valueAt01 = buttonArray[0][1].getText(); String valueAt02 = buttonArray[0][2].getText(); String valueAt10 = buttonArray[1][0].getText(); String valueAt11 = buttonArray[1][1].getText(); String valueAt12 = buttonArray[1][2].getText(); String valueAt20 = buttonArray[2][0].getText(); String valueAt21 = buttonArray[2][1].getText(); String valueAt22 = buttonArray[2][2].getText(); // Set gameOver to true, if any of the below conditions is true // If row 1 matched if (valueAt00 == valueAt01 && valueAt01 == valueAt02 && valueAt00 != "") { gameOver = true; } // If row 2 matched else if (valueAt10 == valueAt11 && valueAt11 == valueAt12 && valueAt10 != "") { gameOver = true; } // If row 3 matched else if (valueAt20 == valueAt21 && valueAt21 == valueAt22 && valueAt20 != "") { gameOver = true; } // If column 1 matched else if (valueAt00 == valueAt10 && valueAt10 == valueAt20 && valueAt00 != "") { gameOver = true; } // If column 2 matched else if (valueAt01 == valueAt11 && valueAt11 == valueAt21 && valueAt01 != "") { gameOver = true; } // If column 3 matched else if (valueAt02 == valueAt12 && valueAt12 == valueAt22 && valueAt02 != "") { gameOver = true; } // If diagonal elements matched else if (valueAt00 == valueAt11 && valueAt11 == valueAt22 && valueAt00 != "") { gameOver = true; } // If diagonal elements matched else if (valueAt02 == valueAt11 && valueAt11 == valueAt20 && valueAt02 != "") { gameOver = true; } // When all buttons are clicked but no one won - draw condition // Set gameDraw to true as well else if (valueAt00 != "" && valueAt01 != "" && valueAt02 != "" && valueAt10 != "" && valueAt11 != "" && valueAt12 != "" && valueAt20 != "" && valueAt21 != "" && valueAt22 != "") { gameOver = true; gameDraw = true; } // If game is over if (gameOver) { int result = -1; // If draw, display message "GAME DRAW" // Ask user if they want to play again if (gameDraw) { result = JOptionPane.showConfirmDialog(null, "GAME DRAW\nDo you want to play Again ?", "Game Over", JOptionPane.YES_NO_OPTION); } // Else, display who won // Ask user if they want to play again else { result = JOptionPane.showConfirmDialog(null, currentPlayer + " wins!!\nDo you want to play Again ?", "Game Over", JOptionPane.YES_NO_OPTION); } // If result == 0, means user clicked YES on dialog box // Reset game, else exit game if (result == 0) { resetGame(); } else { System.exit(0); } } } public static void resetGame() { // Re-set gameOver and gameDraw to false gameOver = false; gameDraw = false; // Enable all buttons and set text = "" for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { buttonArray[i][j].setText(""); buttonArray[i][j].setEnabled(true); } } // Re-set playerLabel to Player 1 playerLabel.setText("Player 1"); // Re-set player1 to true and player2 to false player1 = true; player2 = false; } }
TicTacToeDriver.java
import javax.swing.JFrame; public class TicTacToeDriver { public static void main(String[] args) { // Create a frame of type TicTacToe JFrame frame = new TicTacToe(); // Set the title of frame and it's size frame.setTitle("Tic Tac Toe"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Output-
Comments
Post a Comment