Tic Tac Toe Game in Java [source code included]

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Tic-Tac-Toe is a simple classic famous game which is played mostly by kids. The java tic tac toe game also helps to improve the concentration of the kids.

The objective of this tic-tac-toe game java project is to build a tic-tac-toe game so anyone can play it without wasting paper. The Tic-Tac-Toe game is also called the X and O game. The player who succeeds in placing their marks in a diagonal, horizontal, or vertical row is the winner.

Java Tic Tac Toe – Project Details

The interesting java project will be build using the AWT and Swings libraries. We will be explaining all the steps as well as methods that are used in this project. Swings is a popular java library that is used to develop beautiful GUI applications.

Tic Tac Toe Project Prerequisites:

  • IDE Used: NetBeans 11.2.
  • Java should be installed on the machine.
  • To build a tic-tac-toe game using java we require basic knowledge of java.
  • Abstract Window Toolkit (AWT) & Swing packages are standard graphical user interfaces used to render graphics. By default, these packages are installed by java.

Download Tic Tac Toe Project Code

Please download the full source code of tic-tac-toe java project: Tic Tac Toe Java Project

Step to build Tic-Tac-Toe game using java:

  1. Import packages
  2. Initialize User Interface
  3. Adding Actions to buttons
  4. Function to check the winner

1. Import packages

In this step, we will import AWT & Swing required packages

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

2. Initialize User Interface:

In this step, we basically create the user interface (UI) of our tic-tac-toe game, for that we use frames, panels, buttons, labels, etc.

Functions Definitions:

  • setBackground(new Color(255,255,255)): This function will set the background color of the UI component.
  • setLayout(layout): This function will set the layout of the frame or panel. Layout can be grid, flow, gridbag, etc
  • setText(“your text”): This function will set the text of the label, button, etc
  • setVisible(true): This function will set the frame/window to be visible to the user. By default, it is false.
  • setBorder(BorderFactory.createLineBorder(Color.decode(“#2C6791”))): This function will set the border around the buttons, frames, panels, etc.
  • setSize(int width, int height): This function is used to set the size of frame, panel, etc. It takes two parameters such as width and height.
  • setIconImage(icon): This function is used to set the icon of the frame/window.
  • add(obj): This function is used to add the component object in frame or panel.
 private void initUI(){
          
   //Setting up panels layout
   //Creating 3*3=9 grid for game
   board.setLayout(new GridLayout(3,3));
   //panel layout for printing winner of game
   panel.setLayout(new FlowLayout());

   //Setting up buttons background color
   btn1.setBackground(new Color(255,255,255));
   btn2.setBackground(new Color(255,255,255));
   btn3.setBackground(new Color(255,255,255));
   btn4.setBackground(new Color(255,255,255));
   btn5.setBackground(new Color(255,255,255));
   btn6.setBackground(new Color(255,255,255));
   btn7.setBackground(new Color(255,255,255));
   btn8.setBackground(new Color(255,255,255));
   btn9.setBackground(new Color(255,255,255));
   btn10.setBackground(new Color(255,255,255));
   
    //Setting up panel background color
   panel.setBackground(new Color(255,255,255));
   
   //Setting up button label text
   btn10.setText("RESET");
   
   //Setting up buttons border
   btn1.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn2.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn3.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn4.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn5.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn6.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn7.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn8.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
   btn9.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));

   //Adding all buttons in board layout
   board.add(btn1);
   board.add(btn2);
   board.add(btn3);
   board.add(btn4);
   board.add(btn5);
   board.add(btn6);
   board.add(btn7);
   board.add(btn8);
   board.add(btn9);
   
   panel.add(btn10);
   panel.add(lbl);
   
   //Frame is parent of all every panel
   //panels are added in frame
   f.add(board,BorderLayout.CENTER);
   f.add(panel,BorderLayout.SOUTH);
   
   //Setting up icon for frame
   f.setIconImage(icon);    
   
   f.setVisible(true);
   f.setSize(550,550);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

3. Adding Actions to buttons:

  • In this step, we will put actions to each button. We will specify what will happen when a button is clicked.
  • In our scenario, when Player X presses a button on the grid, “X” will be printed and that button will be disabled for Player “O”.
  • Similarly, when Player O presses a button on the grid, “O” will be printed and that button will be disabled for Player “X”.
  • If a “RESET‘ Button was clicked then the whole grid board will be cleared.

Adding actions on button code:

 public void addActionEvents() {
 
   //registering action listener to buttons
   //Adding action listener for what will happen when player clicks on buttons
   btn1.addActionListener(this);
   btn2.addActionListener(this);
   btn3.addActionListener(this);
   btn4.addActionListener(this);
   btn5.addActionListener(this);
   btn6.addActionListener(this);
   btn7.addActionListener(this);
   btn8.addActionListener(this);
   btn9.addActionListener(this);
   btn10.addActionListener(this);
      
}

Performing actions on click of button Code:

@Override
public void actionPerformed(ActionEvent a) {
  count++;
  if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
    letter = "X";
  } else if(count == 2 || count == 4 || count == 6 || count == 8 ){
    letter = "O";
  }

  if(a.getSource() == btn1){
    btn1.setText(letter);
    btn1.setEnabled(false);
  }else if(a.getSource() == btn2){
    btn2.setText(letter);
    btn2.setEnabled(false);
  } else if(a.getSource() == btn3){
    btn3.setText(letter);
    btn3.setEnabled(false);
  } else if(a.getSource() == btn4){
    btn4.setEnabled(false);
    btn4.setText(letter);
  } else if(a.getSource() == btn5){
    btn5.setText(letter);
    btn5.setEnabled(false);
  } else if(a.getSource() == btn6){
    btn6.setText(letter);
    btn6.setEnabled(false);
  } else if(a.getSource() == btn7){
    btn7.setEnabled(false);
    btn7.setText(letter);
  } else if(a.getSource() == btn8){
    btn8.setEnabled(false);
    btn8.setText(letter);
  } else if(a.getSource() == btn9){
    btn9.setText(letter);
    btn9.setEnabled(false);
  }
  else if(a.getSource() == btn10){
      
    //btn10 is for reset
    //Re-setting whole game
    
    letter = "";
    count = 0;
     
    btn1.setEnabled(true);
    btn2.setEnabled(true);
    btn3.setEnabled(true);
    btn4.setEnabled(true); 
    btn5.setEnabled(true);
    btn6.setEnabled(true);
    btn7.setEnabled(true);
    btn8.setEnabled(true);
    btn9.setEnabled(true);
    
    btn1.setText("");
    btn2.setText("");
    btn3.setText("");
    btn4.setText("");
    btn5.setText("");
    btn6.setText("");
    btn7.setText("");
    btn8.setText("");
    btn9.setText("");
    btn9.setText("");

    lbl.setText("");
    
    win = false;
  
  }

  //Calling checkWinner() method for to check who is the winner
  checkWinner();
}

4. Function to check the winner:

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

In this step, we basically check who is the winner of the game.

For that we must know what are the rules of the winning of the game:

  • If Player X or Player O cuts the grid in vertically , horizontally & diagonally then that player will win the game.
  • So, the 3 x 3 by grid has 8 combinations that can win the game.
  • Vertically: {{1,2,3},{4,5,6},{7,8,9}}
  • Horizontally: {{1,4,7},{2,5,8},{3,6,9}}
  • Diagonally: {{1,5,9},{3,5,7}}
private void checkWinner() {
  //Checking every condition of tic-tac-toe game
  //Check Horizontally
  if (btn1.getText() == btn2.getText() && btn2.getText() == btn3.getText() && btn1.getText() != "" && btn2.getText() != "" && btn3.getText() != "") {
    win = true;
  }

  //Check Horizontally
  else if (btn4.getText() == btn5.getText() && btn5.getText() == btn6.getText() && btn4.getText() != "" && btn5.getText() != "" && btn6.getText() != "") {
    win = true;
  }

  //Check Horizontally
  else if (btn7.getText() == btn8.getText() && btn8.getText() == btn9.getText() && btn7.getText() != "" && btn8.getText() != "" && btn9.getText() != "") {
    win = true;
  }

  //Check Vertically
  else if (btn1.getText() == btn4.getText() && btn4.getText() == btn7.getText() && btn1.getText() != "" && btn4.getText() != "" && btn7.getText() != "") {
    win = true;
  }

  //Check Vertically
  else if (btn2.getText() == btn5.getText() && btn5.getText() == btn8.getText() && btn2.getText() != "" && btn5.getText() != "" && btn8.getText() != "") {
    win = true;
  } else if (btn3.getText() == btn6.getText() && btn6.getText() == btn9.getText() && btn3.getText() != "" && btn6.getText() != "" && btn9.getText() != "") {
    win = true;
  }

  //Check Diagonally
  else if (btn1.getText() == btn5.getText() && btn5.getText() == btn9.getText() && btn1.getText() != "" && btn5.getText() != "" && btn9.getText() != "") {
    win = true;
  }

  //Check Diagonally
  else if (btn3.getText() == btn5.getText() && btn5.getText() == btn7.getText() && btn3.getText() != "" && btn5.getText() != "" && btn7.getText() != "") {
    win = true;
  } else {
    win = false;
  }

  if (win) {
    lbl.setText("Hurray! Player " + letter + " wins!");
    btn1.setEnabled(false);
    btn2.setEnabled(false);
    btn3.setEnabled(false);
    btn4.setEnabled(false);
    btn5.setEnabled(false);
    btn6.setEnabled(false);
    btn7.setEnabled(false);
    btn8.setEnabled(false);
    btn9.setEnabled(false);

  } else if (!win && count == 9) {
    lbl.setText("The game ended in a tie.");
    btn1.setEnabled(false);
    btn2.setEnabled(false);
    btn3.setEnabled(false);
    btn4.setEnabled(false);
    btn5.setEnabled(false);
    btn6.setEnabled(false);
    btn7.setEnabled(false);
    btn8.setEnabled(false);
    btn9.setEnabled(false);
  }
}

Java Tic Tac Toe Output

tic tac toe java output

Summary

Yay! we have successfully developed a simple tic tac toe game in java!

In this tic-tac-toe java project we learned: how to create a basic game and also we saw how to create user interface components such as frames, panels, buttons, labels, etc with the help of AWT and Swing packages.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *