Java || Simple Tic Tac Toe Game Sample Code GUI
The following is another homework assignment which was presented in an intro to Java class. This program was used to provide more practice creating a graphical user interface.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
JFrame
JMenu
JButtons
JPanel
JOptionPane
How To Play Tic-Tac-Toe
Special Fonts For This Game - Click Here To Download
Executable .Jar File - Click Here To Download & Play
This program features a graphical user interface (GUI) which has nine buttons arranged in a square. A user plays the game by clicking the mouse in a available button. The game then places a symbol on the clicked button alternating between the letters “X” and an “O.”
The game begins by clicking on the “New Game” button. This action will clear away any text on the 9 game buttons. The 9 game buttons are still disabled, but the radio button is enabled. This means someone must select who plays first: “X” or “O.” After selecting the starting player then the 9 game buttons become enabled.
When a player clicks on one of the 9 available game buttons, the text on that button will change into an “X” or an “O.” The game stops when one of the two players has 3 identical symbols in a row, a column, or a diagonal. When there is such a winner, the symbol of the winner is displayed to the screen. Sometimes all 9 game buttons have been clicked on but there is still no winner. In that case the text “Tie” is displayed to the screen.
The two buttons “New Game” and “Quit” remain enabled at all times. Clicking on “Quit” will close the window.
This program was implemented into 3 different files, so the code for this program will be broken up into 3 sections. The three-file solution always has one file (the driver) which contains the “main” function. Another file contains the implementation of the graphical user interface (GUI), and the last file contains logic, which in this case is the game algorithms.
==== File #1 – TicTacToe.java ====
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// ============================================================================ // Author: Kenneth Perkins // Date: July 8, 2013 // Taken From: http://programmingnotes.org/ // File: TicTacToe.java // Description: This is the driver program for a three-file solution // which implements the game of tic tac toe. The driver program // always contains the method main. // ============================================================================ import javax.swing.*; public class TicTacToe { public static void main(String[] args) { // display message to the screen JOptionPane.showMessageDialog(null, "Game created by Kenneth Perkins for " + "use on the website 'My Programming Notes'" + "\n Visit: http://programmingnotes.org/", "Starting Game..", JOptionPane.INFORMATION_MESSAGE); // start game new GUI(); }// End of main }// http://programmingnotes.org/ |
==== File #2 – GUI.java ====
This is the GUI (graphical user interface) class for a three-file solution which implements the game of tic tac toe. The sole purpose of this source code is to define the GUI and call methods in the BusinessLogic class when needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
// ============================================================================ // Author: Kenneth Perkins // Date: July 8, 2013 // Taken From: http://programmingnotes.org/ // File: GUI.java // Description: This is the GUI (graphical user interface) class // for a three-file solution which implements the game of tic tac toe. // The sole purpose of this source code is to define the GUI // and call methods in the BusinessLogic class when needed. // ============================================================================ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GUI extends JFrame implements ActionListener { // setting up ALL the variables JFrame window = new JFrame("Kenneth's Tic Tac Toe Game"); JMenuBar mnuMain = new JMenuBar(); JMenuItem mnuNewGame = new JMenuItem(" New Game"), mnuGameTitle = new JMenuItem("|Tic Tac Toe| "), mnuStartingPlayer = new JMenuItem(" Starting Player"), mnuExit = new JMenuItem(" Quit"); JButton btnEmpty[] = new JButton[10]; JPanel pnlNewGame = new JPanel(), pnlNorth = new JPanel(), pnlSouth = new JPanel(), pnlTop = new JPanel(), pnlBottom = new JPanel(), pnlPlayingField = new JPanel(); JPanel radioPanel = new JPanel(); private JRadioButton SelectX = new JRadioButton("User Plays X", false); private JRadioButton SelectO = new JRadioButton("User Plays O", false); private ButtonGroup radioGroup; private String startingPlayer= ""; final int X = 800, Y = 480, color = 190; // size of the game window private boolean inGame = false; private boolean win = false; private boolean btnEmptyClicked = false; private boolean setTableEnabled = false; private String message; private Font font = new Font("Rufscript", Font.BOLD, 100); private int remainingMoves = 1; private int wonNumber1 = 1, wonNumber2 = 1, wonNumber3 = 1; final int winCombo[][] = new int[][] { {1, 2, 3}, {1, 4, 7}, {1, 5, 9}, {4, 5, 6}, {2, 5, 8}, {3, 5, 7}, {7, 8, 9}, {3, 6, 9} /*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/ }; //end array //=============================== GUI ========================================// public GUI() //This is the constructor { //Setting window properties: window.setSize(X, Y); window.setLocation(300, 180); window.setResizable(true); window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //------------ Sets up Panels and text fields ------------------------// // setting Panel layouts and properties pnlNorth.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlNorth.setBackground(new Color(70, 70, 70)); pnlSouth.setBackground(new Color(color, color, color)); pnlTop.setBackground(new Color(color, color, color)); pnlBottom.setBackground(new Color(color, color, color)); pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER)); radioPanel.setBackground(new Color(color, color, color)); pnlBottom.setBackground(new Color(color, color, color)); radioPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Who Goes First?")); // adding menu items to menu bar mnuMain.add(mnuGameTitle); mnuGameTitle.setEnabled(false); mnuGameTitle.setFont(new Font("Purisa",Font.BOLD,18)); mnuMain.add(mnuNewGame); mnuNewGame.setFont(new Font("Purisa",Font.BOLD,18)); mnuMain.add(mnuStartingPlayer); mnuStartingPlayer.setFont(new Font("Purisa",Font.BOLD,18)); mnuMain.add(mnuExit); mnuExit.setFont(new Font("Purisa",Font.BOLD,18));//---->Menu Bar Complete // adding X & O options to menu SelectX.setFont(new Font("Purisa",Font.BOLD,18)); SelectO.setFont(new Font("Purisa",Font.BOLD,18)); radioGroup = new ButtonGroup(); // create ButtonGroup radioGroup.add(SelectX); // add plain to group radioGroup.add(SelectO); radioPanel.add(SelectX); radioPanel.add(SelectO); // adding Action Listener to all the Buttons and Menu Items mnuNewGame.addActionListener(this); mnuExit.addActionListener(this); mnuStartingPlayer.addActionListener(this); // setting up the playing field pnlPlayingField.setLayout(new GridLayout(3, 3, 2, 2)); pnlPlayingField.setBackground(Color.black); for(int x=1; x <= 9; ++x) { btnEmpty[x] = new JButton(); btnEmpty[x].setBackground(new Color(220, 220, 220)); btnEmpty[x].addActionListener(this); pnlPlayingField.add(btnEmpty[x]); btnEmpty[x].setEnabled(setTableEnabled); } // adding everything needed to pnlNorth and pnlSouth pnlNorth.add(mnuMain); BusinessLogic.ShowGame(pnlSouth,pnlPlayingField); // adding to window and Showing window window.add(pnlNorth, BorderLayout.NORTH); window.add(pnlSouth, BorderLayout.CENTER); window.setVisible(true); }// End GUI // =========== Start Action Performed ===============// public void actionPerformed(ActionEvent click) { // get the mouse click from the user Object source = click.getSource(); // check if a button was clicked on the gameboard for(int currentMove=1; currentMove <= 9; ++currentMove) { if(source == btnEmpty[currentMove] && remainingMoves < 10) { btnEmptyClicked = true; BusinessLogic.GetMove(currentMove, remainingMoves, font, btnEmpty, startingPlayer); btnEmpty[currentMove].setEnabled(false); pnlPlayingField.requestFocus(); ++remainingMoves; } } // if a button was clicked on the gameboard, check for a winner if(btnEmptyClicked) { inGame = true; CheckWin(); btnEmptyClicked = false; } // check if the user clicks on a menu item if(source == mnuNewGame) { System.out.println(startingPlayer); BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame, pnlPlayingField,pnlBottom,radioPanel); if(startingPlayer.equals("")) { JOptionPane.showMessageDialog(null, "Please Select a Starting Player", "Oops..", JOptionPane.ERROR_MESSAGE); BusinessLogic.ShowGame(pnlSouth,pnlPlayingField); } else { if(inGame) { int option = JOptionPane.showConfirmDialog(null, "If you start a new game," + " your current game will be lost..." + "n" +"Are you sure you want to continue?" , "New Game?" ,JOptionPane.YES_NO_OPTION); if(option == JOptionPane.YES_OPTION) { inGame = false; startingPlayer = ""; setTableEnabled = false; } else { BusinessLogic.ShowGame(pnlSouth,pnlPlayingField); } } // redraw the gameboard to its initial state if(!inGame) { RedrawGameBoard(); } } } // exit button else if(source == mnuExit) { int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Quit" ,JOptionPane.YES_NO_OPTION); if(option == JOptionPane.YES_OPTION) { System.exit(0); } } // select X or O player else if(source == mnuStartingPlayer) { if(inGame) { JOptionPane.showMessageDialog(null, "Cannot select a new Starting "+ "Player at this time.nFinish the current game, or select a New Game "+ "to continue", "Game In Session..", JOptionPane.INFORMATION_MESSAGE); BusinessLogic.ShowGame(pnlSouth,pnlPlayingField); } else { setTableEnabled = true; BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame, pnlPlayingField,pnlBottom,radioPanel); SelectX.addActionListener(new RadioListener()); SelectO.addActionListener(new RadioListener()); radioPanel.setLayout(new GridLayout(2,1)); radioPanel.add(SelectX); radioPanel.add(SelectO); pnlSouth.setLayout(new GridLayout(2, 1, 2, 1)); pnlSouth.add(radioPanel); pnlSouth.add(pnlBottom); } } pnlSouth.setVisible(false); pnlSouth.setVisible(true); }// End Action Performed // =========== Start RadioListener ===============// private class RadioListener implements ActionListener { public void actionPerformed(ActionEvent event) { JRadioButton theButton = (JRadioButton)event.getSource(); if(theButton.getText().equals("User Plays X")) { startingPlayer = "X"; } if(theButton.getText().equals("User Plays O")) { startingPlayer = "O"; } // redisplay the gameboard to the screen pnlSouth.setVisible(false); pnlSouth.setVisible(true); RedrawGameBoard(); } }// End RadioListener /* ---------------------------------- Start of all the other methods. | ---------------------------------- */ private void RedrawGameBoard() { BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame, pnlPlayingField,pnlBottom,radioPanel); BusinessLogic.ShowGame(pnlSouth,pnlPlayingField); btnEmpty[wonNumber1].setBackground(new Color(220, 220, 220)); btnEmpty[wonNumber2].setBackground(new Color(220, 220, 220)); btnEmpty[wonNumber3].setBackground(new Color(220, 220, 220)); remainingMoves = 1; for(int x=1; x <= 9; ++x) { btnEmpty[x].setText(""); btnEmpty[x].setEnabled(setTableEnabled); } win = false; } private void CheckWin() { for(int x=0; x < 8; ++x) { if(!btnEmpty[winCombo[x][0]].getText().equals("") && btnEmpty[winCombo[x][0]].getText().equals(btnEmpty[winCombo[x][1]].getText()) && btnEmpty[winCombo[x][1]].getText().equals(btnEmpty[winCombo[x][2]].getText()) /* The way this checks the if someone won is: First: it checks if the btnEmpty[x] is not equal to an empty string- x being the array number inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number] Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number] y being winCombo[each set the same as x][the second number] (So basically checks if the first and second number in each set is equal to each other) Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being winCombo[each set as y][the third number] Conclusion: So basically it checks if it is equal to the btnEmpty is equal to each set of numbers */ ) { win = true; wonNumber1 = winCombo[x][0]; wonNumber2 = winCombo[x][1]; wonNumber3 = winCombo[x][2]; btnEmpty[wonNumber1].setBackground(Color.white); btnEmpty[wonNumber2].setBackground(Color.white); btnEmpty[wonNumber3].setBackground(Color.white); break; } } if(win || (!win && remainingMoves > 9)) { if(win) { if(startingPlayer.equals("X")) { if(remainingMoves % 2 == 0) message = " X has won!"; else message = " O has won!"; } else { if(remainingMoves % 2 == 0) message = " O has won!"; else message = " X has won!"; } JOptionPane.showMessageDialog(null, message, "Congrats!", JOptionPane.INFORMATION_MESSAGE); } else if(!win && remainingMoves > 9) { message = "Both players have tied!"; JOptionPane.showMessageDialog(null, message, "Tie Game!", JOptionPane.WARNING_MESSAGE); } for(int x=1; x <= 9; ++x) { btnEmpty[x].setEnabled(false); } win = false; inGame = false; startingPlayer = ""; } }// End of CheckWin }// http://programmingnotes.org/ |
==== File #3 – BusinessLogic.java ====
This is the BusinessLogic class for a three-file solution which implements the game of tic tac toe. The is the class containing algorithms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
// ============================================================================ // Author: Kenneth Perkins // Date: July 8, 2013 // Taken From: http://programmingnotes.org/ // File: BusinessLogic.java // Description: This is the BusinessLogic class for a three-file solution // which implements the game of tic tac toe. The is the class // containing algorithms. // ============================================================================ import javax.swing.*; import java.awt.*; public class BusinessLogic { public static void GetMove(int currentMove, int remainingMoves, Font font, JButton btnEmpty[], String startingPlayer) {// gets the current move "X" or "O" for the user & displays to screen btnEmpty[currentMove].setFont(font); if(startingPlayer.equals("X")) { if(remainingMoves % 2 != 0) { btnEmpty[currentMove].setText("X"); } else { btnEmpty[currentMove].setText("O"); } } else { if(remainingMoves % 2 != 0) { btnEmpty[currentMove].setText("O"); } else { btnEmpty[currentMove].setText("X"); } } }// End of GetMove public static void ShowGame(JPanel pnlSouth, JPanel pnlPlayingField) {// shows the Playing Field pnlSouth.setLayout(new BorderLayout()); pnlSouth.add(pnlPlayingField, BorderLayout.CENTER); pnlPlayingField.requestFocus(); }// End of ShowGame public static void ClearPanelSouth(JPanel pnlSouth, JPanel pnlTop, JPanel pnlNewGame, JPanel pnlPlayingField, JPanel pnlBottom, JPanel radioPanel) {// clears any posible panals on screen pnlSouth.remove(pnlTop); pnlSouth.remove(pnlBottom); pnlSouth.remove(pnlPlayingField); pnlTop.remove(pnlNewGame); pnlSouth.remove(radioPanel); }// End of ClearPanelSouth }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
This program uses custom fonts. To obtain those fonts, click here!
Click here to download & play the executable .jar file.
Leave a Reply