ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Tic Tac Toe Tutorial With Source Code

Updated on November 26, 2012

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?

See results

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

    0 of 8192 characters used
    Post Comment

    • wjack2010 profile image

      Jack 

      5 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 ;)

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)