Skip to content

Instantly share code, notes, and snippets.

@xaviablaza-zz
Created October 6, 2012 12:39
Show Gist options
  • Save xaviablaza-zz/3844825 to your computer and use it in GitHub Desktop.
Save xaviablaza-zz/3844825 to your computer and use it in GitHub Desktop.
A simple Tic-Tac-Toe game.
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author MeneXia (Xavi Ablaza)
*
*/
public class TicTacToe {
static Scanner in;
static String[] board;
static String turn;
public static void main(String[] args) {
in = new Scanner(System.in);
board = new String[9];
turn = "X";
String winner = null;
populateEmptyBoard();
System.out.println("Welcome to 2 Player Tic Tac Toe.");
System.out.println("--------------------------------");
printBoard();
System.out.println("X's will play first. Enter a slot number to place X in:");
while (winner == null) {
int numInput;
try {
numInput = in.nextInt();
if (!(numInput > 0 && numInput <= 9)) {
System.out.println("Invalid input; re-enter slot number:");
continue;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input; re-enter slot number:");
continue;
}
if (board[numInput-1].equals(String.valueOf(numInput))) {
board[numInput-1] = turn;
if (turn.equals("X")) {
turn = "O";
} else {
turn = "X";
}
printBoard();
winner = checkWinner();
} else {
System.out.println("Slot already taken; re-enter slot number:");
continue;
}
}
if (winner.equalsIgnoreCase("draw")) {
System.out.println("It's a draw! Thanks for playing.");
} else {
System.out.println("Congratulations! " + winner + "'s have won! Thanks for playing.");
}
}
static String checkWinner() {
for (int a = 0; a < 8; a++) {
String line = null;
switch (a) {
case 0:
line = board[0] + board[1] + board[2];
break;
case 1:
line = board[3] + board[4] + board[5];
break;
case 2:
line = board[6] + board[7] + board[8];
break;
case 3:
line = board[0] + board[3] + board[6];
break;
case 4:
line = board[1] + board[4] + board[7];
break;
case 5:
line = board[2] + board[5] + board[8];
break;
case 6:
line = board[0] + board[4] + board[8];
break;
case 7:
line = board[2] + board[4] + board[6];
break;
}
if (line.equals("XXX")) {
return "X";
} else if (line.equals("OOO")) {
return "O";
}
}
for (int a = 0; a < 9; a++) {
if (Arrays.asList(board).contains(String.valueOf(a+1))) {
break;
}
else if (a == 8) return "draw";
}
System.out.println(turn + "'s turn; enter a slot number to place " + turn + " in:");
return null;
}
static void printBoard() {
System.out.println("/---|---|---\\");
System.out.println("| " + board[0] + " | " + board[1] + " | " + board[2] + " |");
System.out.println("|-----------|");
System.out.println("| " + board[3] + " | " + board[4] + " | " + board[5] + " |");
System.out.println("|-----------|");
System.out.println("| " + board[6] + " | " + board[7] + " | " + board[8] + " |");
System.out.println("/---|---|---\\");
}
static void populateEmptyBoard() {
for (int a = 0; a < 9; a++) {
board[a] = String.valueOf(a+1);
}
}
}
@jash2810
Copy link

jash2810 commented Oct 4, 2018

can you provide uml diagram for this code, please?

@ahh1539
Copy link

ahh1539 commented Oct 19, 2018

The UML diagram for this program would be useless @jash2810. It is a single class program, UML diagrams are more useful when you are examining class relations between multiple classes.

@debuchi12
Copy link

how to create flowchart with tictactoe? please help me

@amandaroos
Copy link

This has been the easiest to read tic tac toe solution I've found. Thanks!

@JhanviDeAwesome
Copy link

Uhhhh.... can we use the code in our own programs?

@JhanviDeAwesome
Copy link

Is it copyright or anything?

@dubeyji10
Copy link

thank you sir for making it so simple .

@D-Studios
Copy link

D-Studios commented Aug 5, 2019

import java.util.*;
import java.util.List;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//javax.swing.* is used to create JFrames. java.awt.* is used to create labels and buttons. java.awt.event.* is used to create functions for buttons. 
/**
 * 
 * @ original author MeneXia (Xavi Ablaza)--Created basic logic for the game
 * @ Making the GUI and creating other edits for the game--D-Studios(Devang Bhatnagar)
 *
 *
 */

//In this class, a Tic-Tac-Toe game is created.
public class TicTacToe extends JPanel{
    static String[] board;  
    static String turn;
    //A list of buttons is created and, when clicked, can change array values in board[]. This will be used to see if someone won or if a draw occurred. 
    static List<JButton> buttons=new ArrayList<JButton>();
    static JFrame frame=new JFrame();
    static int value=0;
    static String winner = null;
    static JLabel information=new JLabel("<html>Welcome to 2 Player Tic Tac Toe.<br/>X will play first.<br/> Click near the center of a slot to place X in:");
    
    //In the main function, a JFrame window is being created and the lines from the paintComponent function are drawn. Then, populateEmptyBoard is called.
    public static void main(String[] args) {
    	  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          TicTacToe ticTacToe=new TicTacToe();
          frame.add(ticTacToe);
          frame.setContentPane(ticTacToe);
 
          frame.setVisible(true);
        board = new String[9];
        turn = "X";
       
        populateEmptyBoard();
       
    }
    //In winningText, checkWinner is called to see if a player has won. If the player won or a draw occurred, the label on the window is updated to show it.
    static void winningText() {
    	winner=checkWinner();
    	if(winner!=null) {
        if (winner.equalsIgnoreCase("draw")) {
        	information.setText("<html>It's a draw!<br/> Thanks for playing.");
        } else {
        	information.setText("<html>Congratulations!<br/> "+ winner+ " has won!<br/> Thanks for playing.");
        }
    	}
    }
//In this function, the board array is used to see if there is a winner or if a draw occurred. If both of these conditions are false, the game continues.
    static String checkWinner() {
        for (int a = 0; a < 8; a++) {
            String line = null;
            switch (a) {
            case 0:
                line = board[0] + board[1] + board[2];
                break;
            case 1:
                line = board[3] + board[4] + board[5];
                break;
            case 2:
                line = board[6] + board[7] + board[8];
                break;
            case 3:
                line = board[0] + board[3] + board[6];
                break;
            case 4:
                line = board[1] + board[4] + board[7];
                break;
            case 5:
                line = board[2] + board[5] + board[8];
                break;
            case 6:
                line = board[0] + board[4] + board[8];
                break;
            case 7:
                line = board[2] + board[4] + board[6];
                break;
            }
            if (line.equals("XXX")) {
                return "X";
            } else if (line.equals("OOO")) {
                return "O";
            }
        }

        for (int a = 0; a < 9; a++) {
            if (Arrays.asList(board).contains("Empty")){
                break;
            }
            else if (a == 8) return "draw";
        }
        information.setText("<html>"+turn+"'s turn.<br/> Click near the center of a slot to place "+turn+" in.");
        return null;
    }
    
    
//In this function, buttons are created for the player to put his/her/their turns in. Every time a player clicks on an applicable button, the board array is updated.
    static void populateEmptyBoard() {
    	frame.setLayout(null);
    	information.setBounds(10,160, 400, 400);   
        frame.add(information);
        int xIncrease=0; 
        int yIncrease=-100;
        
        for(int i=0; i<9; i++) board[i]="Empty";
        
        for(int y=0; y<3; y++){
         
        	xIncrease=0;
        	yIncrease+=100;
            for (int x = 0; x < 3; x++) {
                buttons.add(new JButton(""));
                buttons.get(value).setBounds(xIncrease, yIncrease, 100, 100);
                buttons.get(value).setOpaque(false);
                buttons.get(value).setContentAreaFilled(false);
                buttons.get(value).setBorderPainted(false);
                frame.add(buttons.get(value));
               buttons.get(value).addActionListener(new ActionListener() {
            	   int val=value;
            	   public void actionPerformed(ActionEvent e) {
            		   if(winner==null && board[val]=="Empty") {
            		  board[val]=turn;
            		   buttons.get(val).setText(turn);
          
            		   if (turn.equals("X")) {
                           turn = "O";
                       } else {
                           turn = "X";
                       }
            		 winningText();
            		   }
            		   else if(winner!=null) information.setText("The game has already been finished!");
            		   else information.setText("<html>The slot is already taken!<br/> Pick another slot!");
            	   }
               });
                value++;
                xIncrease+=100;
            }
            frame.setSize(300,450);
          frame.setResizable(false);
          }
        
        
        
        
    }
//In this in-built function, three black vertical lines and two black horizontal lines are created to separate the buttons in a Tic-Tac-Toe fashion. 
	 public void paintComponent(Graphics g) {
	    	super.paintComponent(g);
	    	int x=100;
	    	g.setColor(Color.BLACK);
	    	for(int i=0; i<2; i++) {
	    	g.drawLine(0, 0+x, 300,0+x);
	    	if(i==2) break;
	    	g.drawLine(0+x,0,0+x, 300);
	    	x+=100;
	    	}
	    	
	    }
    
    
}

I enhanced Xavi Ablaza's code. I created a GUI for the player to play the game on, instead of on the console window. I also made other edits as well. @xaviablaza-zz, thank you for the original code.

@philihp
Copy link

philihp commented Jan 8, 2020

is there a SLA on support for this? my organization would like to use it for enterprise.

@Rudrarokaya
Copy link

Hey, could you please explain this piece of code. I am just a beginner. Please Help.
Thanks in advance.

if (board[numInput-1].equals(String.valueOf(numInput))) {
board[numInput-1] = turn;
if (turn.equals("X")) {
turn = "O";
} else {
turn = "X";
}
printBoard();
winner = checkWinner();
} else {
System.out.println("Slot already taken; re-enter slot number:");
continue;
}

@Luidpopgaming
Copy link

github people can you make a solution to a khan academy challenge the name is tic-tac-toe

@s698667
Copy link

s698667 commented Jun 19, 2020

this is epic :) nice stuff

@BowlOfSalad
Copy link

Hey, could you please explain this piece of code. I am just a beginner. Please Help.
Thanks in advance.

if (board[numInput-1].equals(String.valueOf(numInput))) {
board[numInput-1] = turn;
if (turn.equals("X")) {
turn = "O";
} else {
turn = "X";
}
printBoard();
winner = checkWinner();
} else {
System.out.println("Slot already taken; re-enter slot number:");
continue;
}

Sorry for being quite late to the party but ill still break it down for you, somethings i'll explain but I wont use the correct terms, whoever is reading this and knows any of the correct terms, feel free to correct them. If you have any specific questions ask them.

if (board[numInput-1].equals(String.valueOf(numInput))) {

Lets start out with this line, this line of code is the beginning of an if statement, an if statement allows you to put something inside the following parenthesis and if everything inside of them is true then whatever is in the curly brackets are run. Inside the parenthesis can be simplified when explaining, board[numInput-1] == String.valueOf(numInput), the beginning part is calling an array, you call an array by naming the variable and then putting brackets, inside the brackets is the index of which point in the array you want to call. What they're calling is numInput-1, numInput is a variable and there is a -1 because arrays start at 0 and work their way up, i would believe numInput would start at 1 instead of 0 to make debugging easier for you to read. The following function .equals() just checks if the argument you put into the function is equal to the variable it is being used to. String.valueOf() is another function, I haven't used this function so I don't know exactly what it does, my best guess is it turns a float/int into a string.

board[numInput-1] = turn;

This line is simply making whatever point on the array we are at, and making that the character of whoever's turn it is.

if (turn.equals("X")) {
turn = "O";
} else {
turn = "X";
}

This if statement is just there to change who's turn it is. If it was X's turn its now O's turn and vice versa.

printBoard();

This just calls the function printBoard() that was made within the script.

winner = checkWinner();

This sets the winner variable to the output of the checkWinner() function.

System.out.println("Slot already taken; re-enter slot number:");

This is a function within java that writes to the console, anything that is inside the parenthesis will be written to the console, this includes floats, integers, characters, and strings.

continue;

I don't know what this line of code is supposed to do either, if someone could help me out with this one that would be much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment