Tic Tac Toe Problem

I need help on a Tic Tac Toe game I am making for a class. I had finished a "2 Player" version and my instructor wants me to simulate a computer "AI" now. I cannot figure out what I'm doing wrong. The order of precedence is this:
1. X moves first (the player)
2. Computer moves to win.
3. If it can't win, it moves to block a win
4. If it can't block a win, it moves to the best possible spot to set up a win.
I think my problems are with several methods, but I cannot figure out what I'm doing wrong. Every time I look at my code, it just makes "sense". I think my problems could probably be found in 4 methods, setButtonText(), findOpen(), findBestOpen() and tempCheck(). I would like hints or maybe if I could get a second look at it for me.
public class VangTicTacToe extends javax.swing.JFrame {
    private boolean isX;
    private int turnCount;
    private boolean gameWon;
    private boolean isTemp;
    /** Creates new form VangTicTacToe */
    public VangTicTacToe() {
        initComponents();
        resetGame();
        isX = true;
        turnCount = 0;
    private void checkWinner(String pressedButton){
        //an multi-dimensional array of winning combinations
        JButton[][] winningCombos = {{oneJButton, twoJButton,
        threeJButton}, {oneJButton, fourJButton,
        sevenJButton}, {oneJButton, fiveJButton, nineJButton},
        {twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
        nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
        eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
        String buttonPressed = pressedButton;
        //loops and determines if any of the possible winning combinations have been
        //met for X and displays output accordingly
        for(JButton[] row : winningCombos){
            for(JButton button : row){
                if(button.getText().equals(buttonPressed)){
                    gameWon = true;
                else{
                    gameWon = false;
                    break;
            }//end inner for
            if(gameWon == true && isTemp == false){
                for(JButton button : row){
                    button.setBackground(Color.green);
                }//end inner for
                if(pressedButton.equals("X"))
                    outputJLabel.setText("Congratulations! Player 1 (\"X\") Wins!");
                else
                    outputJLabel.setText("Sorry, computer wins.");
                disableButtons();
                break;
            }//end if
            else{
                continue;//go to next outer loop and keep searching
        }//end outer for
    }//end method checkWinner
    private void setButtonText(JButton buttonPressed){
        if(isX == true){
            buttonPressed.setText("X");
            isX = false;
            checkWinner("X");
            outputJLabel.setText("Computer's turn");
            isTemp = true; //sets isTemp to true so that the test is temporary
            findOpen();//calls findOpen to start computer move
        //disable the button so it cannot be pressed again
        buttonPressed.setEnabled(false);
        //increment the turn count number
        turnCount++;
        if(turnCount == 9)
            outputJLabel.setText("Cats Game! You both are losers!");
    }//end method setText
    //the following 3 methods are for a computer move
     //find next open space
    private void findOpen(){
        //array of buttons
        JButton[] buttons = {oneJButton, twoJButton, threeJButton, fourJButton,
        fiveJButton, sixJButton, sevenJButton, eightJButton, nineJButton};
        //moves through array of buttons and looks for empty.  If empty,
        //it calls temporary select method.
        for (int count = 0; count < buttons.length; count++){
            if(buttons[count].getText().isEmpty())
                tempCheck(buttons[count]);
        }//end for loop
        //if gameWon is false, call findBestButton to find the best open spot
        if(gameWon == false){
            findBestButton();
    }//end method findOpen
    private void findBestButton(){
        //an multi-dimensional array of winning combinations
        JButton[][] winningCombos = {{oneJButton, twoJButton,
        threeJButton}, {oneJButton, fourJButton,
        sevenJButton}, {oneJButton, fiveJButton, nineJButton},
        {twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
        nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
        eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
        boolean placeO = false;
        int buttonCount = 0;
        for(JButton[] row : winningCombos){
            for(JButton button : row){
                if(button.getText().equals("O") || button.getText().equals("")){
                    placeO = true;
                else{
                    placeO = false;
                    buttonCount = 0;
                if(placeO == true){
                    ++buttonCount;
                else{
                    break;
                if(buttonCount == 3 && placeO == true){
                    button.setText("O");
            }//end inner for
            if(placeO == true){
                isX = true;
                break;
            else{
                continue;
        }//end outer for
    }//end method findBestButton
    //checks if temp move would win
    private void tempCheck(JButton tempButton){
        //temporarily assigns "O" to a square and checks if it wins
        tempButton.setText("O");
        checkWinner("O");
        if(gameWon == true){//if it wins then set temp to false and call
            isTemp = false;//checkWinner();
            checkWinner("0");
        else{
            tempButton.setText("");//else, set buttonText to empty
        }//end if
        if(gameWon == false){//if gameWon is false, check if "X" would win
            tempButton.setText("X");
            isTemp = true;
            checkWinner("X");
            if(gameWon == true){//if x is going to win,
                tempButton.setText("O");//block the player from winning
            else{
                tempButton.setText("X");
    }//end method tempCheck()
}

touandcim wrote:
I click to make "X"'s (the player's move). X appears but O never does, although a button is highlighted. If I keep pressing the buttons, all X's appear until the last move, when an "O" appears.I don't know if it's the problem, but
checkWinner("0");looks suspicious. (2nd invocation in your tempCheck() method).
Your program seems awfully brittle. How would you do it if you had a 4 x 4 board? Or 5 x 5?
Also, your 'winningCombos' array is repeated everywhere it's used. There's no need for that; just make it an instance variable/constant.
Winston

Similar Messages

  • Tic tac toe problem please help

    hi,
    My program consists of 4 classes but working bit by bit and currently using 2 classes. I've managed to get an 'X' to appear on the grid but I'm having problems arranging it like a tic tac toe grid and another number appears under the number selected by the player next to the grid, how do i get rid of it?? the output is like this.........
    // output
    Enter player's Name:
    Name:
    dave
    dave to play
    Enter move by selecting number from grid, or 0 to draw
    Move entered:
    1
    1 0X23456789
    it also says "String index out of range:-1 any ideas what this means?????
    heres my source code for the program....
    //Main program
    public class TheTest1
         public static void main( String [] args)
         TheTest TT = new TheTest();
         TT.gridSheet("0123456789", true);
    // TheTest
    import element.* ; // import the package that contains
    // the ConsoleWindow class
    public class TheTest
         String name1;
         String turn;
         int cell, move;
         final static char NOUGHT='O', CROSS='X';
         public TheTest()
              c.out.println("Enter player's Name:");
              c.out.println("Name:");
              name1 = c.input.readString();
              turn = name1;
              move();
    public void move()
                   if(turn.compareTo(name1)==0)
                        c.out.println(name1 + " to play");
              c.out.println("Enter move by selecting number from grid, or 0 to draw");
                   c.out.println("Move entered: ");
                   cell = c.input.readInt();
         public void gridSheet(String fruit, boolean play)
              for(int j = 1; j<9; j=j+3)
                        char index;
                   for(int i = j; i<(j+3); i++)
         if(play==true)
         index = fruit.charAt (i);
         c.out.print (index + " ");
                                  //index = fruit.charAt(i);
                                  if(cell==1 && turn.compareTo(name1)==0)
                                  cell=fruit.indexOf('1');
                                  fruit=fruit.substring(0,cell) + CROSS + fruit.substring(cell+1);
                                  c.out.println(fruit);
                                  //move();
         //c.out.println(" ");
    Any help will be appreciated.
    Many thanks
    Dave

    this is a tic tac toe console and you're having trouble displaying it as a grid?
    if so, this is one way to simulate the board (some of the code is just for display in this example)
    import java.io.*;
    class TicTacToeConsole
      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
      String[] board = new String[9];
      public TicTacToeConsole()
        for(int x = 0; x < board.length; x++) board[x] = " _ ";
        try{playGame();}catch(Exception e){e.printStackTrace();}
      public void playGame() throws IOException
        System.out.println("Board at game start");
        printBoard();
        System.out.println("\nPlease select an available number to put your X");
        printAvailableSquares();
        int playerMove = Integer.parseInt(input.readLine()) -1;
        board[playerMove] = " X ";
        System.out.println("\nBoard after first move");
        printBoard();
        System.out.println("\nAvailable moves after first move");
        printAvailableSquares();
      public void printBoard()
        System.out.println();
        for(int x = 0; x < board.length; x++)
          System.out.print(board[x]);
          if(x%3 == 2) System.out.println("\n");
      public void printAvailableSquares()
        System.out.println();
        for(int x = 0; x < board.length; x++)
          if(board[x].equals(" _ ")) System.out.print(" " + (x+1) + " ");
          else System.out.print("   ");
          if(x%3 == 2) System.out.println("\n");
      public static void main(String[] args){new TicTacToeConsole();}
    }

  • Tic-Tac-Toe checkWinner method problem

    there seems to be a problem with the check winner method that I have, and the game isnt exactly playing out the way its supposed to. Any idea? By the way the game is a grid so the top left spot is 0,0, and the bottom spot is 2,2. It will as you to input a row and a column so you can put 1,0. Thanks for the help.
    import javax.swing.*;
    import java.text.*;
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.lang.*;
    import java.util.*;
    import java.math.*;
    import java.sql.*;
    import java.security.*;
    import java.beans.*;
    import javax.crypto.*;
    import javax.net.*;
    import org.omg.CORBA.*;
    import java.awt.color.*;
    import java.util.jar.*;
    public class TwoDArray
         String [] [] board=new String [3] [3];
         int x;
         public TwoDArray()
              for(int x=0;x<3;x++)
                   for(int y=0;y<3;y++)
                        board[x][y]="";
         public void getMove(int row, int col, String letter)
              if(board[row][col].equalsIgnoreCase(""));
                   board[row][col]=letter;
              x++;
         public void printBoard()
              for(int x=0;x<3;x++)
                   System.out.print("|");
                   for(int y=0;y<3;y++)
                        System.out.print(board[x][y]);
                   System.out.println("|");
         public boolean checkWinner()
              boolean win=false;
                   if(board[0][0].equalsIgnoreCase(board[0][1])&&board[0][0].equalsIgnoreCase(board[0][2]))
                        win=true;
                        return win;
                   if(board[0][0].equalsIgnoreCase(board[1][0])&&board[0][0].equalsIgnoreCase(board[2][0]))
                        win=true;
                        return win;
                   if(board[0][1].equalsIgnoreCase(board[1][1])&&board[0][1].equalsIgnoreCase(board[2][1]))
                        win=true;
                        return win;
                   if(board[0][2].equalsIgnoreCase(board[1][2])&&board[0][2].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[1][0].equalsIgnoreCase(board[1][1])&&board[1][0].equalsIgnoreCase(board[1][2]))
                        win=true;
                        return win;
                   if(board[2][0].equalsIgnoreCase(board[2][1])&&board[2][0].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[0][0].equals(board[1][1])&&board[0][0].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[2][0].equals(board[1][1])&&board[2][0].equalsIgnoreCase(board[0][2]))
                        win=true;
                        return win;
              return win;     
         public static void main(String[] args)
              boolean winner=false;     
              String player1="X";
              String player2="O";
              String instructions="Welcome to Tic-Tac-Toe.";
              for (int i = 0;i<instructions.length() ;i++ )
                    System.out.print(instructions.charAt(i));
              try
              Thread.sleep(99);
              }catch(InterruptedException e) {e.printStackTrace();}
              System.out.println();
              TwoDArray board=new TwoDArray();
              String input1=JOptionPane.showInputDialog("Enter the row you wish to move in.");
              int rowmove=Integer.parseInt(input1);
              String input2=JOptionPane.showInputDialog("Enter the column you wish to move in.");
              int colmove=Integer.parseInt(input2);
              board.getMove(rowmove,colmove,player1);
              board.printBoard();
              while(winner==board.checkWinner())
                   String input3=JOptionPane.showInputDialog("Enter the row you wish to move in.");
                   int rowmove2=Integer.parseInt(input3);
                   String input4=JOptionPane.showInputDialog("Enter the column you wish to move in.");
                   int colmove2=Integer.parseInt(input4);
                   board.getMove(rowmove2,colmove2,player2);
                   board.printBoard();
                   String input5=JOptionPane.showInputDialog("Enter the row you wish to move in.");
                   int rowmove3=Integer.parseInt(input5);
                   String input6=JOptionPane.showInputDialog("Enter the column you wish to move in.");
                   int colmove3=Integer.parseInt(input6);
                   board.getMove(rowmove3,colmove3,player1);
                   board.printBoard();
              System.out.println("YOU WON!!");
    }

    Take a look at this code:
    import javax.swing.JOptionPane;
    public class TicTacToe
        static final String PLAYER1 = "X";
        static final String PLAYER2 = "O";
        static final String EMPTY = "-";
        static String[][] board = new String[3][3];
        static public void init() {   
            for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 3; y++) {
                    board[x][y] = new String(EMPTY);
        static public void getMove(int row, int col, String letter) {
            if (board[row][col].equals(EMPTY)) {
                board[row][col] = letter;
        static public void printBoard() {
            for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 3; y++) {
                    System.out.print(board[x][y]);
                System.out.println();
            System.out.println();
        static public String winner() {
            for (int i = 0; i < board.length; i++) {
                /** check horizontally */
                if (board[0].equals(board[i][1]) &&
    board[i][0].equals(board[i][2])) {
    if (!board[i][0].equals(EMPTY)) {
    return board[i][0];
    /** check vertically */
    if (board[0][i].equals(board[1][i]) &&
    board[0][i].equals(board[2][i])) {
    if (!board[0][i].equals(EMPTY)) {
    return board[0][i];
    /** check diagonally */
    if (board[0][0].equals(board[1][1]) &&
    board[0][0].equals(board[2][2])) {
    if (!board[0][0].equals(EMPTY)) {
    return board[0][0];
    if (board[0][2].equals(board[1][1]) &&
    board[0][2].equals(board[2][0])) {
    if (!board[0][0].equals(EMPTY)) {
    return board[0][2];
    return EMPTY;
    static public void drawOutString(String str) {
    for (int i = 0; i < str.length(); i++) {
    System.out.print(str.charAt(i));
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    static public void main(String[] args) {
    init();
    drawOutString("Welcome to Tic-Tac-Toe.");
    System.out.println();
    do {
    int row = Integer.parseInt(JOptionPane.showInputDialog(
    "Enter the row you wish to move in."));
    int column = Integer.parseInt(JOptionPane.showInputDialog(
    "Enter the column you wish to move in."));
    getMove(row, column, PLAYER1);
    printBoard();
    } while(winner().equals(EMPTY));
    System.out.println("YOU WON!!");

  • Help with tic tac toe

    hey all,
    i am having problems creating a tic tac toe program. the program should create a board with NxN spaces, where N is obtained through user input.
    I created a fully working program that does a 3x3 board, checks for diagonal, vertical, horizontal wins and also allows 1 vs computer or 2 players play, but i am struggling with the NxN board.
    here is the code of what i have, can anyone point me in the right direction? all help is appreciated! please keep it simple as possible as i am just learning java!!
    import java.util.Scanner;
    import java.util.Random;
    public class NoughtsCrosses
    static final String PLAYER1 = "X";
    static final String PLAYER2 = "O";
    static final String EMPTY = "�";
    static String[][] board = new String[][];
    static int turn = 0;
    static public void makeBoard(int boardSize)
    for (int x = 0; x < boardSize; x++)
    for (int y = 0; y < boardSize; y++)
    board[x][y] = new String(EMPTY);
    static public void playComputer()
    Scanner scan = new Scanner(System.in);
    Random generator = new Random();
    int move;
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    System.out.print("Make a Move: ");
    move = scan.nextInt();
    else
    System.out.print("Computer, place your O: ");
    move = generator.nextInt(10);
    System.out.println(move);
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void playHuman()
    Scanner scan = new Scanner(System.in);
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    else
    System.out.println("Player 2, place your O");
    System.out.print("Make a Move: ");
    int move = scan.nextInt();
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void getMove(int move)
    int row = move/3;
    int col = move%3;
    if (board[row][col].equals(EMPTY))
    board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
    turn++;
    else
    System.out.println("OCCUPIED FIELD! TRY AGAIN!");
    static public void printBoard()
    for (int x = 0; x < 3; x++)
    for (int y = 0; y < 3; y++)
    if(y == 0)
    System.out.print(" ");
    System.out.print(board[x][y]);
    if(y < 2)
    System.out.print(" | ");
    System.out.println();
    if(x < 2)
    System.out.println(" ---|---|---");
    static public String winner()
    for (int i = 0; i < board.length; i++)
    /** check horizontally */
    if (board[0].equals(board[i][1]) && board[i][0].equals(board[i][2]))
    if (!board[i][0].equals(EMPTY))
    return board[i][0];
    /** check vertically */
    if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]))
    if (!board[0][i].equals(EMPTY))
    return board[0][i];
    /** check diagonally */
    if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]))
    if (!board[0][0].equals(EMPTY))
    return board[0][0];
    if (board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]))
    if (!board[0][2].equals(EMPTY))
    return board[0][2];
    return EMPTY;
    static public void main(String[] args)
    Scanner scan = new Scanner(System.in);
    int boardSize;
    System.out.println();
    System.out.println("Welcome to Tic Tac Toe!");
    System.out.println("�����������������������");
    System.out.println("How big should the board be?");
    boardSize = scan.nextInt();
    makeBoard(boardSize);
    int players = 0;
    do{
    System.out.println("How many players?");
    System.out.println("1 (vs. Computer) or 2 (vs. another player)?");
    players = scan.nextInt();
    System.out.println();
    }while(players < 1 || players > 2);
    if (players == 1)
    playComputer();
    else
    playHuman();

    well, i figured out how to do it all, thanks to the TREMENDOUS amount of help here...lol...
    i just have one more (minor problem)...
    i can't get an algorithm working to see if the two diagonals are occupied by x's or o's (see if someone won diagonally)
    to check horizontally & vertically on an NxN board, i use following code:
    int count = 0;
            /** check horizontally  */
            for (int i = 0; i < myBoard.length; i++)
               for (int j = 0; j < myBoard.length-1; j++)
                   if (myBoard[0].equals(myBoard[i][j+1]) && !myBoard[i][0].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[i][0];
    count = 0;
    count = 0;
    /** check vertically */
    for (int i = 0; i < myBoard.length; i++)
    for (int j = 0; j < myBoard.length-1; j++)
    if (myBoard[j][0].equals(myBoard[j+1][i]) && !myBoard[0][i].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[0][i];
    count = 0;
    now i was messing around ALOT and couldn't figure out how to get the diagonals showing! this is what i came up with:
    count =0;
    for (int j = 1; j < myBoard.length; j++)
           if (myBoard[0][0].equals(myBoard[j][j]) && !myBoard[0][0].equals(EMPTY))
                 count++;
                 System.out.println(count);
            if (count >= myBoard.length)
                 return myBoard[0][0];
    count = 0;
    for (int j = myBoard.length-1; j >= 0; j--)
         if (myBoard[0][myBoard.length-1].equals(myBoard[j][j]) && !myBoard[0][myBoard.length-1].equals(EMPTY))
             count++;
             System.out.println(count);
          if (count >= myBoard.length)
              return myBoard[0][myBoard.length-1];
          count = 0;

  • Need some help with Tic Tac Toe game

    hey. hope u guys can help me out...
    having a problem with my tic tac toe program...
    i have 2 problems.
    1) got the "X" and "O" to appear using a flag(teacher didn't explain)
    using code like this
    if (jb == button[0]){
    if (flag==0)
    button[0].setText("X");
    else
    button[0].setText("O");
    //toggle
    flag = (flag==0)?1:0;
    my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
    2) found this code in javascript online and i want to do what it does in java code
    if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
    alert("You Win!");
    reset();
    how would i do that?
    thanks for the help.

    ok here's my code:
    //TTT.java
    import javax.swing.*;
    import java.awt.*;
    import java .awt.event.*;
    public class TTT extends JFrame
                        implements WindowListener, ActionListener
    private JFrame frFirst;
    private Container cnFirst,cnSecond;
    private     JButton button[]=new JButton[9];
    private JButton btnNewGame,btnExit;
    private FlowLayout southLayout;
    private JPanel southPanel;
    private int flag;
    public TTT()
                   frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
                   cnFirst=frFirst.getContentPane();
                   cnFirst.setLayout (new GridLayout (4,4));
                   cnFirst.setBackground(Color.green);
              for(int i=0;i<button.length;i++)
                        button[i] = new JButton();
                        cnFirst.add(button);
                        flag=0;
              southPanel = new JPanel ();
              btnNewGame = new JButton ("New Game");
              southPanel.add (btnNewGame);
              btnExit = new JButton ("EXIT");
              southPanel.add (btnExit);
              frFirst.add (southPanel,BorderLayout.SOUTH);
              frFirst.setLocation(200, 200);
              frFirst.setSize(400,400);
              frFirst.setResizable(false);
              frFirst.setVisible(true);
              this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // listeners
                   frFirst.addWindowListener(this);
                   button[0].addActionListener(this);
                   button[1].addActionListener(this);
                   button[2].addActionListener(this);
                   button[3].addActionListener(this);
                   button[4].addActionListener(this);
                   button[5].addActionListener(this);
                   button[6].addActionListener(this);
                   button[7].addActionListener(this);
                   button[8].addActionListener(this);
                   btnNewGame.addActionListener (this);
                   btnExit.addActionListener (this);
         //define methods of WindowListener
    public void windowOpened(WindowEvent we)
         public void windowClosing(WindowEvent we)
         System.exit(0);
         public void windowClosed(WindowEvent we)
         public void windowIconified(WindowEvent we)
         public void windowDeiconified(WindowEvent we)
         public void windowActivated(WindowEvent we)
         public void windowDeactivated(WindowEvent we)
    public void actionPerformed(ActionEvent ae)
    //making the X and O to appear on JButtons
         Object obj = ae.getSource();
              if (obj instanceof JButton){
                   JButton jb = (JButton)obj;
                   if (jb == button[0])
                        if (flag==0)
                        button[0].setText("X");
                   else
                        button[0].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[1])
                        if (flag==0)
                        button[1].setText("X");
                   else
                        button[1].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[2])
                        if (flag==0)
                        button[2].setText("X");
                   else
                        button[2].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[3])
                        if (flag==0)
                        button[3].setText("X");
                   else
                        button[3].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[4])
                        if (flag==0)
                        button[4].setText("X");
                   else
                        button[4].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[5])
                        if (flag==0)
                        button[5].setText("X");
                   else
                        button[5].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[6])
                        if (flag==0)
                        button[6].setText("X");
                   else
                        button[6].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[7])
                        if (flag==0)
                        button[7].setText("X");
                   else
                        button[7].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[8])
                        if (flag==0)
                        button[8].setText("X");
                   else
                        button[8].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
    //New Game To Reset
              if (ae.getSource () == btnNewGame)
    /*     String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
    String YES;
    if (text == YES)
         JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
         else{
    add code to reset game
         //Exit Button to Exit
         if (ae.getSource () == btnExit)
              JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
              this.setVisible(false);
         System.exit(0);
              }     //end of if instanceof
    public static void main(String[]args)
         //instantiate GUI
         new TTT();

  • Gui tris (tic tac toe)

    Hi,
    i am trying to create the tris game in java (maybe you know this game as tic tac toe). I created windows and the alghoritm to play. But now i have the problem to create the board. My idea is to create a board with nine clickable cells, the player clicks on the cell he wants (if it's free), then the computer plays and so on...but i don't have the knowledges of making complex graphic things in java. How can I do?

    ok, and how can i manage the player's click?MouseListener on the JLabel.
    remember
    also that when the player clicks, the program must
    draw a symbol (x or o depending from the choice of
    player). how can i do all this things? For a noob
    like me this is very difficultRead the tutorials. I'm not going to explain to you how to create your app if you can read it up yourself.

  • Powershell tic tac toe programming

    Hey guys, I've got a little question, I'm working on a little game since some time now, and I have a little problem. I need to get the color of a button. Let me explain:
    Instead of crosses and circles, I'm using colors for my tic tac toe (or Noughts and crosses dunno how you call it) and I need to get the color of the buttons so I can program the computer to have his plays based on mine, have you got any idea?

    Try this. It works just fine:
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $button1 = New-Object 'System.Windows.Forms.Button'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    #endregion Generated Form Objects
    $button1_Click={
    if($button1.BackColor -eq 'red'){$button1.BackColor='blue'}else{$button1.BackColor='red'}
    $Form_StateCorrection_Load=
    #Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
    $Form_Cleanup_FormClosed=
    #Remove all event handlers from the controls
    try
    $button1.remove_Click($button1_Click)
    $form1.remove_Load($FormEvent_Load)
    $form1.remove_Load($Form_StateCorrection_Load)
    $form1.remove_FormClosed($Form_Cleanup_FormClosed)
    catch [Exception]
    $form1.SuspendLayout()
    $form1.Controls.Add($button1)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.ClientSize = '438, 262'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = "form1"
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = "Form"
    # button1
    $button1.BackColor = 'Red'
    $button1.Location = '197, 55'
    $button1.Name = "button1"
    $button1.Size = '75, 23'
    $button1.TabIndex = 1
    $button1.Text = "button1"
    $button1.UseVisualStyleBackColor = $False
    $button1.add_Click($button1_Click)
    # buttonOK
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '351, 227'
    $buttonOK.Name = "buttonOK"
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = "&OK"
    $buttonOK.UseVisualStyleBackColor = $True
    $form1.ResumeLayout()
    #endregion Generated Form Code
    $InitialFormWindowState = $form1.WindowState
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    $form1.ShowDialog()
    ¯\_(ツ)_/¯

  • Computer AI for Tic-Tac-Toe

    Hi, I'm pretty new to java. I've taken some classes but I don't know much. I am trying to create a Tic-Tac-Toe application and I want to create a computer that will play all the correct moves and never lose. I'm not finished with the moves that the computer makes. I've tagged where I'm having the problems. Here it is:package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    * Models a TicTacToe game.
    * @author Charles Lockner
    public class SupermanTicTacToe
       // Instance Variables
       private JFrame theFrame = new JFrame("Superman Tic-Tac-Toe");
       private JMenuBar theMenuBar = new JMenuBar();
       private JMenu fileMenu = new JMenu("File");
       private JMenuItem quit = new JMenuItem("Quit");
       private JMenu optionsMenu = new JMenu("Options");
       private JMenuItem reset = new JMenuItem("Reset Game");
       private JMenuItem vsComp = new JMenuItem("Human vs Superman");
       private JMenuItem vsHuman = new JMenuItem("Human vs Human");
       private JButton buttons[] = new JButton[9];
       private int[][] winCombinations = new int[][]
             { 0, 1, 2 },
             { 3, 4, 5 },
             { 6, 7, 8 }, // Horizontal wins
             { 0, 3, 6 },
             { 1, 4, 7 },
             { 2, 5, 8 }, // Vertical wins
             { 0, 4, 8 },
             { 2, 4, 6 } // Diagonal wins
       private String letter = "";
       private int count = 0;
       private boolean win = false;
       private boolean compPlayer = false;
       private boolean playerIsFirst = true;
       private Random generator = new Random();
       public SupermanTicTacToe()
          // Create window
          theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          theFrame.setSize(300,340);
          theFrame.setLayout(new GridLayout(3,3));
          theFrame.setLocationRelativeTo(null);
          theFrame.setResizable(false);
          // Add menu to window
          theMenuBar.add(fileMenu);
          fileMenu.add(quit);
          theMenuBar.add(optionsMenu);
          optionsMenu.add(reset);
          optionsMenu.addSeparator();
          optionsMenu.add(vsComp);
          optionsMenu.add(vsHuman);
          theFrame.setJMenuBar(theMenuBar);
          // Add buttons to panel
          for(int i = 0; i <= 8; i++)
             buttons[i] = new JButton();
             theFrame.add(buttons);
    // Make Window Visible
    theFrame.setVisible(true);
    // Actions
    quit.addActionListener(new QuitMenuListener());
    reset.addActionListener(new ResetMenuListener());
    vsComp.addActionListener(new VsCompMenuListener());
    vsHuman.addActionListener(new VsHumanMenuListener());
    for(int i = 0; i <= 8; i++)
    buttons[i].addActionListener(new ButtonListener());
    private class ButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    count++;
    System.out.println("Button click done.");
    // Calculate whose turn it is
    if (count % 2 == 0)
    letter = "O";
    else
    letter = "X";
    JButton pressedButton = (JButton) e.getSource();
    pressedButton.setText(letter);
    pressedButton.setEnabled(false);
    // Determine 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;
    // Show a dialog when game is over
    if (win == true)
    for (int i = 0; i <= 8; i++)
    buttons[i].setEnabled(false);
    JOptionPane.showMessageDialog(null, letter + " is a beast.");
    } else if (count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "No one is beastly enough to win this game.");
    // Computer's actions PROBLEMS!!!=====================================
    if (compPlayer)
    if (playerIsFirst)
    if (letter == "O")
    if (buttons[4].getText().equals(""))
    buttons[4].doClick();
    else if (buttons[0].getText().equals(""))
    buttons[0].doClick();
    else if (buttons[2].getText().equals(""))
    buttons[2].doClick();
    else if (buttons[6].getText().equals(""))
    buttons[6].doClick();
    else if (buttons[8].getText().equals(""))
    buttons[8].doClick();
    } else
    if (letter == "X")
    if (buttons[0].getText().equals(""))
    buttons[0].doClick();
    else if (buttons[2].getText().equals(""))
    buttons[2].doClick();
    else if (buttons[6].getText().equals(""))
    buttons[6].doClick();
    else if (buttons[8].getText().equals(""))
    buttons[8].doClick();
    } //==================================================================
    private class QuitMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    private class ResetMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    playerIsFirst = generator.nextBoolean();
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    if(playerIsFirst = false)
    buttons[4].doClick();
    private class VsCompMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    compPlayer = true;
    playerIsFirst = generator.nextBoolean();
    System.out.println(playerIsFirst);
    if(playerIsFirst = false)
    buttons[4].doClick();
    private class VsHumanMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    playerIsFirst = generator.nextBoolean();
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    compPlayer = false;
    public static void main(String[] args)
    new SupermanTicTacToe();

    Here is updated code, that I believe will not be beatable by human input. Let me know if you find any bugs.
    -Squeaker2
             // Computer's actions
             if (compPlayer)
                 if (letter.contentEquals("O")){}
                 else if(letter.contentEquals("X"))
                   {//Code Computer AI Logic
                      boolean flagger = false;
                      flagger = computerLogic();
                      if (flagger == false){
                          if (buttons[4].getText().contentEquals(""))
                             buttons[4].doClick();
                          //Check for inside
                          else if (buttons[1].getText().contentEquals("X")
                                  && buttons[5].getText().contentEquals("X")
                                  && buttons[2].getText().contentEquals(""))
                                buttons[2].doClick();
                          else if (buttons[7].getText().contentEquals("X")
                                  && buttons[5].getText().contentEquals("X")
                                  && buttons[8].getText().contentEquals(""))
                                buttons[8].doClick();
                          else if (buttons[3].getText().contentEquals("X")
                                  && buttons[7].getText().contentEquals("X")
                                  && buttons[6].getText().contentEquals(""))
                                buttons[6].doClick();
                          else if (buttons[1].getText().contentEquals("X")
                                  && buttons[3].getText().contentEquals("X")
                                  && buttons[0].getText().contentEquals(""))
                                buttons[0].doClick();
                          else if (buttons[4].getText().contentEquals("X")
                                  && buttons[0].getText().contentEquals(""))
                                buttons[0].doClick();
                          else if (buttons[1].getText().contentEquals(""))
                             buttons[1].doClick();
                          else if (buttons[3].getText().contentEquals(""))
                             buttons[3].doClick();
                          else if (buttons[5].getText().contentEquals(""))
                             buttons[5].doClick();
                          else if (buttons[7].getText().contentEquals(""))
                             buttons[7].doClick();
                          else if (buttons[0].getText().contentEquals(""))
                             buttons[0].doClick();
                          else if (buttons[2].getText().contentEquals(""))
                             buttons[2].doClick();
                          else if (buttons[6].getText().contentEquals(""))
                             buttons[6].doClick();
                          else if (buttons[8].getText().contentEquals(""))
                             buttons[8].doClick();
       public boolean computerLogic(){
           boolean flagger = false;
           boolean turnUsed = false;
            for (int i = 0; i <= 7; i++)
             { //Check for WIN loop
                if (turnUsed == false){
                    if (buttons[winCombinations[0]].getText().equals(buttons[winCombinations[i][1]].getText()) && buttons[winCombinations[i][0]].getText().contentEquals("O") && buttons[winCombinations[i][2]].getText().contentEquals(""))
    buttons[winCombinations[i][2]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][1]].getText().contentEquals("O") && buttons[winCombinations[i][0]].getText().contentEquals(""))
    buttons[winCombinations[i][0]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][2]].getText().contentEquals("O") && buttons[winCombinations[i][1]].getText().contentEquals(""))
    buttons[winCombinations[i][1]].doClick();
    flagger = true;
    turnUsed = true;
    for (int i = 0; i <= 7; i++)
    { //Check for Block Loop
    if (turnUsed == false){
    if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && buttons[winCombinations[i][0]].getText().contentEquals("X") && buttons[winCombinations[i][2]].getText().contentEquals(""))
    buttons[winCombinations[i][2]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][1]].getText().contentEquals("X") && buttons[winCombinations[i][0]].getText().contentEquals(""))
    buttons[winCombinations[i][0]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][2]].getText().contentEquals("X") && buttons[winCombinations[i][1]].getText().contentEquals(""))
    buttons[winCombinations[i][1]].doClick();
    flagger = true;
    turnUsed = true;
    return flagger;

  • Tic Tac Toe Assignment

    Hi, I'm brand new to your website this is my first post. I am currently in a Computer Science class and extremely new to Java. Our teacher gave us an assignment in Java (Eclipse) for Tic Tac Toe. I have the interface built already with Player One being X's and Player Two being O's and everything seems to work out but I have a major problem. When I get a player with 3 in a row I need a line to pop and for a message signify the winner. I have absolutely no idea on how to do this. So if there is anyone out there that would like to give me some guidance I would be greatly appreciated. I will just post my code below. Thank you very much.
    package mmr.ics3m1.tictac;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.WindowConstants;
    import javax.swing.SwingUtilities;
    public class tictactoe extends javax.swing.JFrame {
         private JLabel lblPlayer1;
         private JLabel lblPlayer2;
         private AbstractAction actionButtonPressed4;
         private AbstractAction actionExit;
         private JButton butExit;
         private AbstractAction actionButtonPressed9;
         private AbstractAction actionButtonPressed8;
         private AbstractAction actionButtonPressed7;
         private AbstractAction actionButtonPressed6;
         private AbstractAction actionButtonPressed5;
         private AbstractAction actionButtonPressed3;
         private AbstractAction actionButtonPressed2;
         private AbstractAction actionButtonPressed;
         private JButton butCell;
         private JButton butCell2;
         private JButton butCell3;
         private JButton butCell4;
         private JButton butCell5;
         private JButton butCell6;
         private JButton butCell7;
         private JButton butCell8;
         private JButton butCell9;
         private Boolean blnPlayer1=true;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        tictactoe inst = new tictactoe();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
         public tictactoe() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   getContentPane().setLayout(null);
                        lblPlayer1 = new JLabel();
                        getContentPane().add(lblPlayer1);
                        lblPlayer1.setText("Player One=X");
                        lblPlayer1.setBounds(28, 17, 110, 36);
                        lblPlayer1.setFont(new java.awt.Font("Segoe UI",3,12));
                        lblPlayer2 = new JLabel();
                        getContentPane().add(lblPlayer2);
                        lblPlayer2.setText("Player Two=O");
                        lblPlayer2.setBounds(245, 24, 83, 19);
                        lblPlayer2.setFont(new java.awt.Font("Segoe UI",3,12));
                        butCell = new JButton();
                        getContentPane().add(butCell);
                        getContentPane().add(getButCell2());
                        getContentPane().add(getButCell3());
                        getContentPane().add(getButCell4());
                        getContentPane().add(getButCell5());
                        getContentPane().add(getButCell6());
                        getContentPane().add(getButCell7());
                        getContentPane().add(getButCell8());
                        getContentPane().add(getButCell9());
                        getContentPane().add(getButExit());
                        butCell.setText("?");
                        butCell.setBounds(28, 65, 59, 40);
                        butCell.setAction(getActionButtonPressed(butCell));
                   pack();
                   setSize(400, 300);
              } catch (Exception e) {
                   e.printStackTrace();
         private AbstractAction getActionButtonPressed(final JButton pcell) {
              if(actionButtonPressed == null) {
                   actionButtonPressed = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed;
         private JButton getButCell2() {
              if(butCell2 == null) {
                   butCell2 = new JButton();
                   butCell2.setText("?");
                   butCell2.setBounds(150, 65, 59, 40);
                   butCell2.setAction(getActionButtonPressed2(butCell2));
              return butCell2;
         private AbstractAction getActionButtonPressed2(final JButton pcell2) {
              if(actionButtonPressed2 == null) {
                   actionButtonPressed2 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell2.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell2.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell2.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed2;
              return actionButtonPressed;
         private JButton getButCell3() {
              if(butCell3 == null) {
                   butCell3 = new JButton();
                   butCell3.setText("?");
                   butCell3.setBounds(269, 65, 59, 40);
                   butCell3.setAction(getActionButtonPressed3(butCell3));
              return butCell3;
         private JButton getButCell4() {
              if(butCell4 == null) {
                   butCell4 = new JButton();
                   butCell4.setText("?");
                   butCell4.setBounds(28, 116, 59, 40);
                   butCell4.setAction(getActionButtonPressed4(butCell4));
              return butCell4;
         private JButton getButCell5() {
              if(butCell5 == null) {
                   butCell5 = new JButton();
                   butCell5.setText("?");
                   butCell5.setBounds(149, 116, 59, 40);
                   butCell5.setAction(getActionButtonPressed5(butCell5));
              return butCell5;
         private JButton getButCell6() {
              if(butCell6 == null) {
                   butCell6 = new JButton();
                   butCell6.setText("?");
                   butCell6.setBounds(269, 116, 59, 40);
                   butCell6.setAction(getActionButtonPressed6(butCell6));
              return butCell6;
         private JButton getButCell7() {
              if(butCell7 == null) {
                   butCell7 = new JButton();
                   butCell7.setText("?");
                   butCell7.setBounds(28, 161, 59, 40);
                   butCell7.setAction(getActionButtonPressed7(butCell7));
              return butCell7;
         private JButton getButCell8() {
              if(butCell8 == null) {
                   butCell8 = new JButton();
                   butCell8.setText("?");
                   butCell8.setBounds(149, 161, 59, 40);
                   butCell8.setAction(getActionButtonPressed8(butCell8));
              return butCell8;
         private JButton getButCell9() {
              if(butCell9 == null) {
                   butCell9 = new JButton();
                   butCell9.setText("?");
                   butCell9.setBounds(269, 161, 59, 40);
                   butCell9.setAction(getActionButtonPressed9(butCell9));
              return butCell9;
         private AbstractAction getActionButtonPressed3(final JButton pcell3) {
              if(actionButtonPressed3 == null) {
                   actionButtonPressed3 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell3.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell3.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell3.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed3;
         private AbstractAction getActionButtonPressed4(final JButton pcell4) {
              if(actionButtonPressed4 == null) {
                   actionButtonPressed4 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell4.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell4.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell4.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed4;
         private AbstractAction getActionButtonPressed5(final JButton pcell5) {
              if(actionButtonPressed5 == null) {
                   actionButtonPressed5 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell5.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell5.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell5.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed5;
         private AbstractAction getActionButtonPressed6(final JButton pcell6) {
              if(actionButtonPressed6 == null) {
                   actionButtonPressed6 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell6.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell6.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell6.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed6;
         private AbstractAction getActionButtonPressed7(final JButton pcell7) {
              if(actionButtonPressed7 == null) {
                   actionButtonPressed7 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell7.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell7.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell7.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed7;
         private AbstractAction getActionButtonPressed8(final JButton pcell8) {
              if(actionButtonPressed8 == null) {
                   actionButtonPressed8 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell8.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell8.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell8.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed8;
         private AbstractAction getActionButtonPressed9(final JButton pcell9) {
              if(actionButtonPressed9 == null) {
                   actionButtonPressed9 = new AbstractAction("?", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if (pcell9.getText()=="?")
                                  //set square to X or O
                                  if (blnPlayer1){
                             pcell9.setText("X");
                             blnPlayer1=false;
                        else{
                             pcell9.setText("O");
                             blnPlayer1=true;
                        else
                             System.out.println("already taken");
              return actionButtonPressed9;
         private JButton getButExit() {
              if(butExit == null) {
                   butExit = new JButton();
                   butExit.setText("Exit");
                   butExit.setBounds(328, 231, 56, 33);
                   butExit.setAction(getActionExit());
              return butExit;
         private AbstractAction getActionExit() {
              if(actionExit == null) {
                   actionExit = new AbstractAction("Exit", null) {
                        public void actionPerformed(ActionEvent evt) {
                             System.exit(0);
              return actionExit;
    }

    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    When I get a player with 3 in a row I need a line to pop and for a message signify the winner. Use a JOptionPane. Read the JOptionPane API and you will find a link to the Swing tutorial on "How to Use Dialogs".

  • Tic Tac Toe code Help

    I am a beginner Java programmer, and I need help with my tic tac toe code.
    import javax.swing.JOptionPane;
    * Created on Nov 14, 2006
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author jye
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class TicTacToe {
        public static void main(String[] args) {
            int[][]matrix = {{0,1,2},{3,4,5},{6,7,8}};
            while (true)
            System.out.println(); //keeps the tables seperate
            for(int row = 0; row<matrix.length;row++)
                for(int col = 0; col < matrix[row].length;col++)
                if (matrix[row][col]!=-1 && matrix[row][col]!=-2) //Compares each element to -1 and and -2, if not, then it just prints out the regular number
                System.out.print(matrix[row][col] + " ");
                if (matrix[row][col]==-1)
                    System.out.print("X" + " ");
                if (matrix[row][col]==-2)
                System.out.print("O" + " ");
                System.out.println();
                int p1 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 1"));
                int p2 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 2"));
            for(int row = 0; row<matrix.length;row++) //this piece of code refers to above print code
                for(int col = 0; col < matrix[row].length;col++)
                if (p1==matrix[row][col]) //compares each element in array to the position inputted. If it is equal to the number inputted, then it changes that to -1. For example, the postition of 4 is [1][1], it will replace [1][1] with -1. The matrix[row][col] is a position.
                    matrix[row][col]=-1;
                if(p2==matrix[row][col])
                    matrix[row][col]=-2;
            for(int row = 0; row<matrix.length;row++)
                for(int col = 0; col < matrix[row].length;col++)
                    if(matrix[0][0]==-1 && matrix[0][1]==-1 && matrix[0][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[1][0]==-1 && matrix[1][1]==-1 && matrix[1][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[2][0]==-1 && matrix[2][1]==-1 && matrix[2][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][0]==-1 && matrix[1][0]==-1 && matrix[2][0]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][1]==-1 && matrix[1][1]==-1 && matrix[2][1]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][2]==-1 && matrix[1][2]==-1 && matrix[2][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][0]==-1 && matrix[1][1]==-1 && matrix[2][2]==-1);
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][2]==-1 && matrix[1][1]==-1 && matrix[2][0]== -1)
                        System.out.println("Player 1 wins.");break; //I GET A "UNREACHEABLE CODE" ERROR HERE
                    if(matrix[0][0]==-2 && matrix[0][1]==-2 && matrix[0][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[1][0]==-2 && matrix[1][1]==-2 && matrix[1][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[2][0]==-2 && matrix[2][1]==-2 && matrix[2][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][0]==-2 && matrix[1][0]==-2 && matrix[2][0]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][1]==-2 && matrix[1][1]==-2 && matrix[2][1]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][2]==-2 && matrix[2][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
                        System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
    }Why do I get a unreachable error code???
    Thanks.

    Just in case you are tired I mean this (from the ending bit of your code)
    if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);// <== PROBLEM RIGHT HERE
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
                        System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
                    }And same earlier on.

  • Tic Tac Toe Java help!

    Hi, I have been trying to create a simple Tic Tac Toe game using Java. I'm currently having problems as to how to create the board using arrays (sorry I don't understand them very well). All I have so far is this,
    public class ticTacToe {
    private int [] [] theBoard = new int [3] [3];
         // *'N' is no winner
         // 'X' is X won
         // 'O' is O won
         // 'C' is a cat's game
         public static char didSomeoneWin(int [] [] currentBoard)
              int winForX = 8000, winForO = 1, checkIfItsAcatsGame = 1, product;
              char winner = 'N';
              for(int column = 0; column < 3; column++) // Check the columns
                   product = currentBoard [0] [column] * currentBoard [1] [column] * currentBoard [2] [column];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              for(int row = 0; row < 3; row++) // Check the rows
                   product = currentBoard [row] [0] * currentBoard [row] [1] * currentBoard [row] [2];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              product = currentBoard [0] [0] * currentBoard [1] [1] * currentBoard [2] [2]; // Check one diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              product = currentBoard [0] [2] * currentBoard [1] [1] * currentBoard [2] [0]; // Check the other diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              if(winner == 'N') // If nobody's won, Check for a cat's game
                   for(int row = 0; row < 3; row++)
                        for(int column = 0; column < 3; column++)
                             checkIfItsAcatsGame *=currentBoard [row] [column];
                   if(checkIfItsAcatsGame != 0) winner = 'C'; // any empty space is a zero. So product is zero if there is space left.
              return winner;
         public void markX(int row, int column)
              myBoard [row] [column] = 20;
         public void markO(int row, int column)
              myBoard [row] [column] = 1;
    That is all so far, could someone help me print out the board? And help me out on the arrays? I don't think they are quite right. Thanks in Advance!
    Message was edited by:
    matthews1.7.2.0

    Hi,
    Do you need a GUI ?
    If yes see http://java.sun.com/docs/books/tutorial/uiswing/index.html
    You can also see this : http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html about printing.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Tic Tac Toe with AI

    Well I'm getting ready for my second semester of Java programing and I figured I would try and get back in the swing (no pun intended) of things by creating a simple tic tac toe game. I was able to make a two player game with in a matter of hours so I figured I would try and make a one player game with AI and thats where im having some issues. Here is my code for two person tic tac toe
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToeV2 implements ActionListener {
         /*Instance Variables*/
         private int[][] winCombinations = new int[][] {
                   {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, //horizontal wins
                   {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, //virticle wins
                   {1, 5, 9}, {3, 5, 7}                //diagonal wins
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         private String letter = "";
         private boolean win = false;
         public TicTacToeV2(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i=1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Calculate whose turn it is*/
              if(count % 2 == 0){
                   letter = "O";
              } else {
                   letter = "X";
              /*Write the letter to the button and deactivate it*/
              for(int i=1; i<=9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText(letter);
                        buttons[i].setEnabled(false);
              /*Determine who won*/
              for(int i=0; i<=7; i++){
                   if( buttons[winCombinations[i][0]].getText() == buttons[winCombinations[i][1]].getText() &&
                        buttons[winCombinations[i][1]].getText() == buttons[winCombinations[i][2]].getText() &&
                        buttons[winCombinations[i][0]].getText() != ""){
                        win = true;
              /*Show a dialog when game is over*/
              if(win == true){
                   JOptionPane.showMessageDialog(null, letter + " wins the game!");
                   System.exit(0);
              } else if(count == 9 && win == false){
                   JOptionPane.showMessageDialog(null, "The game was tie!");
                   System.exit(0);
         public static void main(String[] args){
              TicTacToeV2 starter = new TicTacToeV2();
    Now for my program with AI I'm essentially using the same code and just for clarity I removed all the code that determines who won (as it isnt needed to get the AI to work) This is what I have so far
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV3 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         public TicTacToeV3(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
         public static void main(String[] args){
              new TicTacToeV3();
    It kind of works because each time i choose a box the "computer" also chooses one, but since it is so random the chances the computer wins is very limited. I then tried to do something like this in the AI() method and it seems to be on the right track but once one of the if's are satisfied the all the AI logic stops
         public void AI(){
              //horizontal AI defencive code
              if(buttons[1].getText().equals(buttons[2].getText()) && buttons[1].getText() != ""){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if(buttons[2].getText().equals(buttons[3].getText()) && buttons[2].getText() != ""){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);
              } else if(buttons[4].getText().equals(buttons[5].getText()) && buttons[4].getText() != ""){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              } else if(buttons[5].getText().equals(buttons[6].getText()) && buttons[5].getText() != ""){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);
              } else if(buttons[7].getText().equals(buttons[8].getText()) && buttons[7].getText() != ""){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);
              } else if(buttons[8].getText().equals(buttons[9].getText()) && buttons[8].getText() != ""){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);
              } else {
                   Random x = new Random();
                   int y = 1 + x.nextInt(9);
                   if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                        AI();
                   } else {
                        buttons[y].setText("O");
                        buttons[y].setEnabled(false);
         }And basically what that does is it checks if I have two X's in a row horizontally, If I do it will place an O in the box preventing me from getting three in a row (only in horizontal rows). Of course I would iterate this over and over for all possible combinations of offensive moves and defensive moves and probably do it using a for loop but this is just some scratch code I threw together to show you my thoughts. And again my problem is once one of the conditions are satisfied it never checks the conditions again and I'm not sure why that is...
    So I'm looking for some ideas and/or some pseudo code to help me out a little.
    Thanks

    Well I did this and its a step closer to working but there is another bug and all this logic is hurting my head. Again lets say my grid is numbered like this
    1 | 2 | 3
    4 | 5 | 6
    7 | 8 | 9
    If I go 1, the computer will randomly pick a square thats not set. Lets say the computer picks 4. Now I pick 5 and the computer picks 9 because I would earn 3 in a row diagonally. Then I pick 2 and I can now win three in a row 2-5-8 or 1-2-3. The computer picks 3 because that logic is earlier in the code. BUT when I press 8 to to take the win, but the computer cheats and labels my button thats supposed to be an X as an O, so it should look like this:
    X | X | O
    O | X | 6
    7 | X | O
    but it does this
    X | X | O
    O | X | 6
    7 | O | O
    Here is the AI logic part (its mostly repetitive)
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
                else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         }Here is the entire code if you want to try it and compile it to see what im talking about in real time:
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV4 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         private boolean went = false;
         public TicTacToeV4(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
              else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         public static void main(String[] args){
              new TicTacToeV4();
    What am I doing wrong?

  • Tic-tac-toe multithreaded server game

    i have written the code for tic-tac-toe game partially.i am stuck at writing the code for "who is the winner"? and adding a button to start the new game ?please help me out to write the remaining?
    iam unable to attach the code now;
    Message was edited by:
    vamshijupally

    i have written the code for tic-tac-toe game
    partially.i am stuck at writing the code for "who is
    the winner"? and adding a button to start the new
    game ?please help me out to write the remaining?That question is almost impossible to answer because you didn't provide two vital pieces of information.
    1) What specific problems you're having.
    2) Relevant code.
    iam unable to attach the code now;So, you call the doctor on the phone, say, "I'm not feeling well. Please make me better. I can't come to your office or tell you anything about what's wrong with me now."

  • Array of Characters(Tic Tac Toe)

    My problem is this:
    I am continuing the Tic Tac Toe code downloaded from the java.sun site.
    I want to know if any one could point me in the direction of a simpler solution as to how to deal with the character array. Right now, I'm just writting the method that checks the board for a tie game, and I don't want to write 23 'else if' statements.
    If any one could help I would be your best friend forever.
    thanks.

    use an int array
    then u can do math to check

  • Help with printing a tic tac toe board (using a loop to print)

    hey im making the smiple game tic tac toe and im tryin to print out the board after each turn. I have a 2d array called char which is a 3 by 3 array and i dont know how i would make a for loop to print out the x's and o's in their right spot and still have the board look like a normal tic tac toe board. When the board is printing the x's and o's are already in the 2d char array board.So basically what i want to happen is after player 1's turn is up wherever he put the x replace the number on the board with an x and keep the rest the same and whenever player 2's turn is up wherever he put the o replace the number on the board with an o and keep the rest the same. Any help would be awesome thanks alot.
    Here is the code to the program (i know i use if statements to much its a bad habit of mine)
    import java.util.*;
    public class Tictactoe
        private char board [] [] = new board [3] [3];
        private int X;
        private int O;
        private Scanner p1choice;
        private Scanner p2choice;
        Scanner input = new Scanner(System.in);
        public Tictactoe()
            p1choice = new Scanner(System.in);
            p2choice = new Scanner(System.in);
            play();
        public void play()
            printoriginalboard();
        public void printoriginalboard()
            System.out.println("    |    |    ");  
            System.out.println("  3 |  2 |  1 ");
            System.out.println("____|____|____");
            System.out.println("    |    |    ");
            System.out.println("  6 |  5 |  4 ");
            System.out.println("    |    |    ");
            System.out.println("____|____|____");
            System.out.println("    |    |    ");
            System.out.println("  9 |  8 |  7 ");
            System.out.println("    |    |    ");
            System.out.println("This is the classic game of tictactoe simply pick a number 1 through 9 to place an x or an o in that area.");
            player1turn();
        public void player1turn()
            System.out.println("Player 1 pick an area to place an X");
            int p1choice= p1choice.nextInt();
            if(p1choice == 1 && p2choice == 1 || p1choice == 1){
                System.out.println("This spot has already been taken");
                else
                board[0][2] = 'x';
            pintboard();
            if(p1choice == 2 && p2choice == 2 || p1choice == 2){
            System.out.println("This spot has already been taken");
            else
                board[1][2] = 'x';
            pintboard();
            if(p1choice == 3 && p2choice == 3 || p1choice == 3){
            System.out.println("This spot has already been taken");
            else
                board[2][2] = 'x';
            pintboard();
            if(p1choice == 4 && p2choice == 4 || p1choice == 4){
            System.out.println("This spot has already been taken");
                board[0][1] = 'x';
            pintboard();
            if(p1choice == 5 && p2choice == 5 || p1choice == 5){
            System.out.println("This spot has already been taken");
            else
                board[1][1] = 'x';
            pintboard();
            if(p1choice == 6 && p2choice == 6 || p1choice == 6){
            System.out.println("This spot has already been taken");
            else
                board[2][1] = 'x';
            pintboard();
            if(p1choice == 7 && p2choice == 7 || p1choice == 7){
            System.out.println("This spot has already been taken");
            else
                board[0][0] = 'x';
            pintboard();
            if(p1choice ==8 && p2choice == 8 || p1choice == 8){
            System.out.println("This spot has already been taken");
            else
                board[1][0] = 'x';
            pintboard();
            if(p1choice == 9 && p2choice == 9 || p1choice == 9){
            System.out.println("This spot has already been taken");
            else
                board[2][0] = 'x';
            pintboard();
        public void p2turn()
            System.out.println("Pick an area to place an O");
            int p2choice = p2choice.nextInt();
            if(p2choice == 1 && p1choice == 1 || p2choice == 1){
            System.out.println("This spot has already been taken");
            else
                board[0][2] = 'o';
            pintboard();
            if(p2choice == 2 && p1choice == 2 || p2choice == 2){
            System.out.println("This spot has already been taken");
            else
                board[1][2] = 'o';
            pintboard();
            if(p2choice == 3 && p1choice == 3 || p2choice == 3){
            System.out.println("This spot has already been taken");
            else
                board[2][2] = 'o';
            pintboard();
            if(p2choice == 4 && p1choice == 4 || p2choice == 4){
            System.out.println("This spot has already been taken");
            else
                board[0][1] = 'o';
            pintboard();
            if(p2choice == 5 && p1choice == 5 || p2choice == 5){
            System.out.println("This spot has already been taken");
            else
                board[1][1] = 'o';
            pintboard();
            if(p2choice == 6 && p1choice == 6 || p2choice == 6){
            System.out.println("This spot has already been taken");
            else
                board[2][1] = 'o';
            pintboard();
            if(p2choice == 7 && p1choice == 7 || p2choice == 7){
            System.out.println("This spot has already been taken");
            else
                board[0][0] = 'o';
            pintboard();
            if(p2choice == 8 && p1choice == 8 || p2choice == 8){
            System.out.println("This spot has already been taken");
            else
                board[1][0] = 'o';
            pintboard();
            if(p2choice == 9 && p1choice == 9 || p2choice == 9){
            System.out.println("This spot has already been taken");
            else
                board[2][0] = 'o';
            pintboard();
        public void pintboard()
        {

    Anyway the answer is that you are trying to create an array of char as there is no such thing as a board[3][3].
    One of the best tools a programmer can do is learn how to break a big problem into little problems and work on each little problem in isolation, and then when finished combining the solutions together into the final program. You big mistake that I see here is trying to bite off more than you can chew: trying to create a whole functioning interactive program from just one class. Why give yourself a task that would be difficult even for an experienced java programmer? I suggest that you break this down into logical parts and try to solve the smaller problems before worrying about the whole. For instance, if I were doing something like this, I'd create a class called TTTBoard that encapsulated the tic tac toe board and nothing but the board. I'd think of it as an entity. When I wanted the current state of the board, I'd query the board via a method such as getCurrentState. I'd have methods for checking if position is free, for placing an x/o in a spot, for checking for win, etc... Then I'd create a user interface class where I'd give the users a choice and get their responses. I'd probably create a Game class to control it all. While this all seems daunting, you are trying to do essentially the same thing, but all in one huge class. My recommendation: study OOPs and learn to do it the smart way. Good luck.

Maybe you are looking for

  • Days missing from list view if no event entered in iCal

    if i have no event entered on a particular day, the list view of iCal doesn't display the day. how can i still see the day in list view?

  • Airplay dropouts - only on some tracks in iTunes and not from iPhone

    Hi I experience heavy Airplay dropouts on certain tracks in my collection. And when I play the exact same track from my iPhone4 there is no problem. So I expect it to be an issue with iTunes and not a network bandwidth issue. What I noticed is that i

  • Error starting the MDM server in client system

    Hi MDM Experts, I am new to MDM and we have just installed MDM 5.5 on our system. We are able to 'Mount the Repository' via the MDM Console on the client side but when we try to 'Start MDM Server', we encounter the error below: "Error starting MDM se

  • Photoshop menu bar...

    Hello, So I finally made a menubar in photoshop, styled exactly how I want it... but when I brought it over to DW I could not select the text or figure out how to create the links ...  help please. how do you select the text in a photoshop created me

  • Call a view without Model ?

    Hello All, My application is a Page with flow logic BSP. I need to view a jsp file from this BSP . So i created a MIME Object and imported the JSP as a MIME. I converted that Mime Object into a VIew. Now I want to viewthe output of  that View. But as