Java Tic Tac Toe Tutorial With Source Code

X And O Images For Tic Tac Toe Game

Save as "oicon.png"
Save as "oicon.png"
Save as "xicon.png"
Save as "xicon.png"

Getting Started

I'll write a tutorial on how I came up with this code later. For now, I want to share the source code for anyone who needs it. I noted each section for what it is and does, which should help you figure out how it works on your own. Feel free to drop any questions down in the comments section of the page.

Open up your favorite Java IDE or text editor and save the file as TicTacToe.java.

Make sure you save the X and O images in the same folder as where you code goes.

Java Tic-Tac-Toe Source Code

/*
Java Tic-Tac-Toe
By: Garrett Mickley
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe implements ActionListener 
{
        //Variables
        private int[][] winCombinations = new int[][] //Possible win combinations
        {
            {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //Horizontal
            {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //Vertical
            {0, 4, 8}, {2, 4, 6}             //Diagonal
        };
        private JFrame frame = new JFrame("Garrett's Tic Tac Toe Game");
        private JButton buttons[] = new JButton[9];
        private int count = 0;
        private int xscore = 0;
        private int oscore = 0;
        private String letter = "";
        private boolean win = false;
        private Icon xicon;
        private Icon oicon;

        //Game stuff starts here
        public H4_TicTacToe()
        {
        
            //Create window
            frame.setSize(500,500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new GridLayout(3,3));
            frame.setLocation(300,200);
            xicon = new ImageIcon(getClass().getResource("xicon.png"));
            oicon = new ImageIcon(getClass().getResource("oicon.png"));
        
            //Window buttons
            for(int i=0; i<=8; i++)
            {
                buttons[i] = new JButton();
                frame.add(buttons[i]);
                buttons[i].addActionListener(this);
            }
        
            //Window visiblity
            frame.setVisible(true);
        }
        
        //User input stuff starts here
        public void actionPerformed(ActionEvent a) 
        {
                count++;
                
                //Who's turn
                if(count % 2 == 0)
                {
                    letter = "O";
                    oscore++;
                }
                else 
                {
                    letter = "X";
                    xscore++;
                }

                //Change button to letter
                if(letter == "X")
                {
                    JButton pressedButton = (JButton)a.getSource();
                    pressedButton.setText(letter);
                    pressedButton.setIcon(xicon);
                    pressedButton.setEnabled(false);
                }
                else if(letter == "O")
                {
                    JButton pressedButton = (JButton)a.getSource();
                    pressedButton.setText(letter);
                    pressedButton.setIcon(oicon);
                    pressedButton.setEnabled(false);
                }
                
                //Who won
                for(int i=0; i<=7; i++)
                {
                    if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && 
                        buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && 
                        buttons[winCombinations[i][0]].getText() != "")
                    {
                        win = true;
                    }
                }
                
                //Dialog for end of game
                if(win == true)
                {
                    JOptionPane.showMessageDialog(null, letter + " wins the game! Player X made " + xscore + " moves and player O made " + oscore + " moves!");
                    System.exit(0);
                }
                else if(count == 9 && win == false)
                {
                    JOptionPane.showMessageDialog(null, "It's a tie! There is no winner. Player X made " + xscore + " moves and player O made " + oscore + " moves!");
                    System.exit(0);
                }               
        }
        
        public static void main(String[] args)
        {
            JOptionPane.showMessageDialog(null,"Welcome to Garrett's Tic Tac Toe Game! Player X is first.");
            H4_TicTacToe starter = new H4_TicTacToe();
        }
}

Please Take The Poll

Was this tutorial and source code helpful?

  • Yes
  • No
See results without voting

More by this Author


Please Leave A Comment With Any Questions Or Requests For Future Tutorials 1 comment

wjack2010 profile image

wjack2010 3 years ago from United Kingdom

This could help me look at how Java works, and the different functions and variables included, thank you very much ;)

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working