Making a tic tac toe grid

hi, I've created my code and for the tic tac toe grid but I dont know how to make it look like a grid (i.e
1 2 3
4 5 6
7 8 9)
it has came out as "123X56789" "X" meaning a number has taken up a cross.
can anyone help??
heres the code of the grid........
// GAMEINTERFACE
public class GameInterface extends MyPrint
     private String theGrid;
     final static char NOUGHT='O', CROSS='X';
     public GameInterface()
     theGrid = "?123456789";
     public void pictureBoard(String theGrid)
for(int i = 1; i<theGrid.length(); i++)
          int hit = i%3;
          if(hit!=0)
               myPrint(Character.toString((theGrid.charAt(i))));
          else
               myPrint(Character.toString((theGrid.charAt(i))));
     public void play(char cell, boolean playTurn)
          char noughtCross = ' ';
          if(playTurn = true)
               noughtCross = CROSS;
          else if(playTurn = false)
               noughtCross = NOUGHT;
          if('1'<=cell || cell<='9')
               theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(CROSS) + theGrid.substring(theGrid.indexOf(cell)+1);
          else if('1'<=cell || cell<='9')
               theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(NOUGHT) + theGrid.substring(theGrid.indexOf(cell)+1);
     public String display()
          return theGrid;
Plus how do i create a 'O' in the output as 'X' appears for the 2 players playing.
this will be very appreciated.
many thanks
Dave

just tried that warnerja, it doesnt work either.
it has to be linked to this other class(program below)
//GAME
public class Game extends MyPrint
     GameInterface gameInterface;
     String s = "?123456789";
     Player player1;
     Player player2;
     public Game() // Constructor
     public void makeMove()
          gameInterface = new GameInterface ();
          player1 = new Player ();
          player2 = new Player ();
          myPrintln("Enter name of player");
          String FP = c.input.readString();
          myPrintln(FP, SYSTEM);
          myPrintln("Enter name of other player");
          String SP = c.input.readString();
          myPrintln(SP, SYSTEM);
          gameInterface.pictureBoard(s);
          myPrintln("");
          //boolean whoWon=false;
          int loop = 0;
          while(loop<=6)
               player1.setName(FP);
               myPrintln(player1.getName() + " (X) to play");
               myPrintln("Enter move by selecting number from grid");
               myPrintln("or 0 to draw");
               char name1 = c.input.readChar();
               name1 = c.input.readChar();
               boolean playTurn = true;
               gameInterface.play(name1, true);
               gameInterface.pictureBoard(gameInterface.display());
               myPrintln("");
               //if(checkWin(gameInt.display()))
               //     whoWon=true;
               //     break;
               player2.setName(SP);
               myPrintln(player2.getName() + " (O) to play");
myPrintln("Enter move by selecting number from grid");
               myPrintln("or 0 to draw");
               char name2 = c.input.readChar();
               name2 = c.input.readChar();
               playTurn = false;
               gameInterface.play(name2, false);
               gameInterface.pictureBoard(gameInterface.display());
               myPrintln("");
               //if(checkWin(gameInt.display()))
               //     whoWon=true;
               //     break;
               loop++;
}

Similar Messages

  • Networked Tic Tac Toe

    I need help with making my Tic Tac Toe game networked. Is there an easy
    way to pass two ints over through a network. Heres my Code so far. I
    already have a working Tic Tac Toe. Just wanted to add Network
    Capability.
    Heres my code:
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Vector;
    import javax.swing.*;
    * This class functions as the controller for my Tic Tac Toe game.
    * @author Zosden
    * Date Due: 2/22/2008
    * @version 1.0 (22 February 2008)
    * Input: playersFile.txt is a text file to hold players information.
    * String playerXName is a temp String for input of player x's name.
    * String playerOName is a temp String for input of player O's name.
    * Output: playersFile.txt
    public class GameController
        //  Properties   //
        private GameView myView;
        private GameModel myModel;
        private Player myPlayerX;
        private Player myPlayerO;
        private File playersFile;
        private FileReader fileReader;
        private BufferedReader bufReader;
        private FileOutputStream outFileStream;
        private PrintStream p;
        private boolean myPlayerXNewPlayer = true;
        private boolean myPlayerONewPlayer = true;
        private int myPlayerXPosition;
        private int myPlayerOPosition;
        private Vector myPlayerVector = new Vector(10);
        private ServerSocket serverSocket;
        private Socket clientSocket;
        private PrintWriter out;
        private String inputLine;
        private String outputLine;
        private boolean isClient;
        private BufferedReader in;
        private String fromServer;
         * Default controller constructor.
        public GameController(Player aPlayerX, Player aPlayerO, boolean isClient)
            myPlayerX = aPlayerX;
            myPlayerO = aPlayerO;
            this.isClient = isClient;
            this.readPlayers();
            myModel = new GameModel(this);
            myView = new GameView(this);
            if(isClient)
                this.setUpClient();
                this.waitForTurn(-1 , -1);
            else
                this.setUpServer();
        private void waitForTurn(int aRow, int aCol)
            if(isClient)
                if(!(aRow == -1 || aCol == -1))
                    out.println(aRow + " " + aCol + " ");
                    System.out.println("Made Move");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    if(fromServer != null)
                        int row = fromServer.indexOf(" ");
                        int col = fromServer.indexOf(" ");
                        System.out.println(row + " " + col);
                        myModel.move(row, col);
                        break;
            else
                out.println(aRow + " " + aCol + " ");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    int row = fromServer.indexOf(" ");
                    int col = fromServer.indexOf(" ");
                    System.out.println(row + " " + col);
                    myModel.move(row, col);
                    break;
        private void setUpServer()
            serverSocket = null;
            try
                serverSocket = new ServerSocket(4444);
            catch (IOException e)
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            clientSocket = null;
            try
                clientSocket = serverSocket.accept();
            catch (IOException e)
                System.err.println("Accept failed.");
                System.exit(1);
            try
                out = new PrintWriter(clientSocket.getOutputStream(), true);
            catch (IOException e)
                e.printStackTrace();
        private void setUpClient()
            try
                clientSocket = new Socket(myPlayerO.getName(), 4444);
                out = new PrintWriter(clientSocket.getOutputStream(), true);   
            catch (UnknownHostException e)
                System.err.println("Don't know about host.");
                System.exit(1);
            catch (IOException e)
                System.err.println("Couldn't get I/O for the connection to.");
                System.exit(1);
         * Tells the model that something has been selected then
         * passes the row and col of the event.
         * pre:  a valid view, model and controller have been designated
         * post: sends aRow and aCol to move in the model class.
         * @param aRow
         * @param aCol
        public void choiceMade(Integer aRow, Integer aCol)
            myModel.move(aRow, aCol);
            this.waitForTurn(aRow, aCol);
        public void changePlayersName()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        public void changeMusic()
            myView.displayDialog();
        public void pauseMusic()
            myModel.pauseMusic();  
        public void startMusic()
            myModel.startMusic();  
        public void quitGame()
            this.writePlayers();
            System.exit(0);
         * Increments the number of wins a certain player has,
         * which is determined by the argument.
         * @param aPlayerType
        public void changeImage(int aRow, int aCol, int aPlayerType)
            myView.setMyImagePieces(aRow, aCol, aPlayerType);
        public void updateScore()
            myView.setWins();
        public void changeMessage(String aString)
            myView.changeMyMessage(aString);
         * This method writes the players name and wins into a text file in
         * order to save that information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will rewrite the entire text file
         * with all the players names.
         * </pre>
        public void writePlayers()
            if(!myPlayerXNewPlayer)
                myPlayerVector.remove(myPlayerXPosition + 1);
                myPlayerVector.insertElementAt(getPlayerXWins(),
                        myPlayerXPosition + 1);
            else
                myPlayerVector.add(getPlayerXName());
                myPlayerVector.add(getPlayerXWins());
            if(!myPlayerONewPlayer)
                myPlayerVector.remove(myPlayerOPosition + 1);
                myPlayerVector.insertElementAt(getPlayerOWins(),
                        myPlayerOPosition + 1);
            else
                myPlayerVector.add(getPlayerOName());
                myPlayerVector.add(getPlayerOWins());
                try
                    outFileStream = new FileOutputStream(playersFile);
                    p = new PrintStream(outFileStream);
                catch (IOException e)
                    e.printStackTrace();
            for(int i = 0; i < myPlayerVector.size(); i++)
                p.println(myPlayerVector.elementAt(i));
            p.close();
         * This method reads the players name and wins in a text file in
         * order to find out their information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will read the entire text file
         * with all the players names.
         * </pre>
        public void readPlayers()
            String tempName = null;
            int tempPosition = 0;
            int tempWins = 0;
            playersFile = new File("playersText.txt");
            try
                fileReader = new FileReader(playersFile);
                bufReader = new BufferedReader(fileReader);
                catch (FileNotFoundException e)
                    e.printStackTrace();
            while(true)
                tempName = null;
                try
                    tempName = bufReader.readLine();
                    if(tempName == null)
                        break;
                    myPlayerVector.insertElementAt(tempName, tempPosition);
                    if(getPlayerXName().equalsIgnoreCase(tempName))
                        myPlayerXPosition = tempPosition;
                    if(getPlayerOName().equalsIgnoreCase(tempName))
                        myPlayerOPosition = tempPosition;
                    tempPosition++;
                    try
                        tempWins = Integer.parseInt(bufReader.readLine());
                    catch(NumberFormatException e)
                        e.printStackTrace();
                    myPlayerVector.insertElementAt(tempWins, tempPosition);
                    tempPosition++;
                catch (IOException e)
                    e.printStackTrace();
                if(getPlayerXName().equalsIgnoreCase(tempName))
                    setPlayerXWins(tempWins);
                    myPlayerXNewPlayer = false;
                if(getPlayerOName().equalsIgnoreCase(tempName))
                    setPlayerOWins(tempWins);
                    myPlayerONewPlayer = false;
        public void incrementWin(int aPlayerType)
            if(aPlayerType == getPlayerOType())
                myPlayerO.incrementWins();
            if(aPlayerType == getPlayerXType())
                myPlayerX.incrementWins();
            updateScore();
        public void changePlayersNames()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        //   Accessor Methods     //
        public int getNumDraws()
            return myModel.getNumberDraws();
        public String getMessages()
            return myModel.getMessages();
        public void setMusic(Integer aSong)
            myModel.setMusic(aSong);
        public String getPlayerXName()
            return myPlayerX.getName();
        public String getPlayerOName()
            return myPlayerO.getName();
        public int getPlayerXWins()
            return myPlayerX.getNumWins();
        public int getPlayerOWins()
            return myPlayerO.getNumWins();
        public int getPlayerXType()
            return myPlayerX.getType();
        public int getPlayerOType()
            return myPlayerO.getType();
        public int getNoPlayerType()
            return myPlayerO.NO_PLAYER;
        private void setPlayerXWins(int aNumWins)
            myPlayerX.setNumWins(aNumWins);
        private void setPlayerOWins(int aNumWins)
            myPlayerO.setNumWins(aNumWins);
        private void setPlayerXName(String aName)
            myPlayerX.setName(aName);
        private void setPlayerOName(String aName)
            myPlayerO.setName(aName);
    }</div>{noformat}
    </div>

    I think I figured it out. I still have some work to do, but that part is easy. Heres the file in case anyone is interested.[TTT.Zip|http://www.mediafire.com/?wii1fn5wqom]
    If anyone knows of a better way to do this same thing please let me know

  • 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--need help!

    Im making a tic tac toe game and everything works fine until you try to click the third set of blocks in order to put your X or Y in it. The program does nothing, it even seems as if the mouseDown function isnt working.......can someone help (Code below)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.lang.*;
    public class TicTacToe extends Applet {
    int test = 0;
    int test1 = 0;
    int score;
    int temp;
    char square[][];
    protected int turn;
    final int width = 117;
    boolean TurnP1;
    boolean TurnP2;
    public void init() {
    square = new char[3][3];
         for(int i = 0; i < 3; i++) {
         for(int j = 0; j < 3; j++) {
         square[i][j] = 0;
         score = 0;
         turn = 0;
         temp = 0;
         TurnP1 = false;
         TurnP2 = false;
    public void paint(Graphics g) {
         Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.black);
         for (int i = 0; i < 3; i++)
         for (int j = 0; j < 3; j++) g2.fillRect(i * width / 3, j * width / 3, 35, 35);
         drawXandO(g2);
         g2.drawString(Integer.toString(test) + " " + Integer.toString(test1), 130, 50);
    public void drawXandO(Graphics g) {
         g.setColor(Color.red);
         Font myFont = new Font("Impact", Font.PLAIN, 20);
         g.setFont(myFont);
         for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
         if (square[i][j] != 0) {
         g.drawString(" " + square[i][j] + " ", i * width / 3 + 10, j * width / 3 - 5);
    public boolean mouseDown(java.awt.Event e, int x, int y) {
    int column = (int)(x / (width / 3));
         int row = (int)(y / (width / 3)+1);
         test = column;
         test1 = row;
         turn++;
         if (square[column][row] != 0) {
         play(getCodeBase(), "beep.wav");
         if (TurnP2) {
         turn = 4;
         } else {
         turn = 3;
         return true;
         if (turn % 2 == 0) {
         //Its Player 2 turn
         TurnP1 = false;
         TurnP2 = true;
         square[column][row] = 'O';
         } else {
         //Its Player 1 turn
         TurnP1 = true;
         TurnP2 = false;
         square[column][row] = 'X';
         repaint();
    return true;

    the method you use should not be overridden without a call to the ancestor like:
    public boolean mouseDown(Event e,int x,int y){
              super.mouseDown(e,x,y);
              //your code here
    }it is more safe.but anyway the best thing to do what you want is to use:
    public MyApplet extends Applet implements MouseListener {
           public init(){
              addMouseListener(this);
          //methods mouseReleased,...
          public void mouseDown(MouseEvent e){

  • Tic-tac-toe and 2 dimensional arrays?

    Hi. I'm relatively new to Java Programming and have been experimenting with lots of code and using Eclipse to input my code. I was wondering if there is a way to program a 2 player tic-tac-toe game (without using a java applet) using 2-dimensional arrays to be played in the console.
    So for example, instead of a normal tic-tac-toe grid, i now have:
    1 2 3
    4 5 6
    7 8 9
    as my grid and now the players have to input a number which will replace the selected with a X or O.
    Eg:
    "Player X, please choose a number on the grid: "
    1
    X 2 3
    4 5 6
    7 8 9
    "Player O, please choose a number on the grid: "
    4
    X 2 3
    O 5 6
    7 8 9
    and so forth...
    I haven't gone as far as to writing validation methods because I can't get the 1st input to remain on the board after the 2nd input.
    So when Player X enters 1 and then Player O enters 4, i get:
    1 2 3
    O 5 6
    7 8 9
    How do I store the state of the tic-tac-toe after someone has inputted a value???
    thanx...

    well i don't think i'm intentionally clearing it and i know for sure that i'm not storing it...
    here's the code i've written...(yes it's horrible...such a n00b -.- )
    import java.util.Scanner;
    public class TheBoard{
         public static void main(String[] args){
              String input1;
              String input2;
              String input3;
              String input4;
              String input5;
              String input6;
              String input7;
              String input8;
              String input9;
              char letter;
              char[][] board = new char[3][3];
              board [0][0] = '1';
              board [0][1] = '2';
              board [0][2] = '3';
              board [1][0] = '4';
              board [1][1] = '5';
              board [1][2] = '6';
              board [2][0] = '7';
              board [2][1] = '8';
              board [2][2] = '9';
              System.out.println("The starting grid is: ");
              System.out.print(board[0][0]);
              System.out.print(board[0][1]);
              System.out.print(board[0][2]);
              System.out.println("");
              System.out.print(board[1][0]);
              System.out.print(board[1][1]);
              System.out.print(board[1][2]);
              System.out.println("");
              System.out.print(board[2][0]);
              System.out.print(board[2][1]);
              System.out.print(board[2][2]);
              char[][] boardX = new char[3][3];
              boardX [0][0] = 'X';
              boardX [0][1] = 'X';
              boardX [0][2] = 'X';
              boardX [1][0] = 'X';
              boardX [1][1] = 'X';
              boardX [1][2] = 'X';
              boardX [2][0] = 'X';
              boardX [2][1] = 'X';
              boardX [2][2] = 'X';
              char[][] boardO = new char[3][3];
              boardO [0][0] = 'O';
              boardO [0][1] = 'O';
              boardO [0][2] = 'O';
              boardO [1][0] = 'O';
              boardO [1][1] = 'O';
              boardO [1][2] = 'O';
              boardO [2][0] = 'O';
              boardO [2][1] = 'O';
              boardO [2][2] = 'O';
              Scanner keyboard = new Scanner(System.in);
              System.out.println("\n" + "Player X, please input a valid number: ");
              input1 = keyboard.next();
              int letterLength = input1.length();
         for(int i1=0; i1<letterLength; i1++){
         letter=input1.charAt(i1);
         if(letter=='1')
              System.out.print(boardX[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                   if(letter=='2')
              System.out.print(board[0][0] + "" + boardX[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
         if(letter=='3')
              System.out.print(board[0][0] + "" + board[0][1] + boardX[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
         if(letter=='4')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + boardX[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
         if(letter=='5')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + boardX[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
         if(letter=='6')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + boardX[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
         if(letter=='7')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + boardX[2][0] + board[2][1] + board[2][2]);
         if(letter=='8')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + boardX[2][1] + board[2][2]);
         if(letter=='9')
                   System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + boardX[2][2]);
         else if(Character.isLetter(letter))
                   System.out.println("");
                   System.out.println("\n" + "Player O, please input a valid number: ");
                   input2 = keyboard.next();
                   int letterLength2 = input2.length();
              for(int i2=0; i2<letterLength2; i2++){
              letter=input2.charAt(i2);
              if(letter=='1')
                   System.out.print(boardO[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='2')
                   System.out.print(board[0][0] + "" + boardO[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
              if(letter=='3')
                   System.out.print(board[0][0] + "" + board[0][1] + boardO[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
              if(letter=='4')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + boardO[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
              if(letter=='5')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + boardO[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
              if(letter=='6')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + boardO[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
              if(letter=='7')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + boardO[2][0] + board[2][1] + board[2][2]);
              if(letter=='8')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + boardO[2][1] + board[2][2]);
              if(letter=='9')
                        System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + boardO[2][2]);
              else if(Character.isLetter(letter))
                        System.out.println("");
              System.out.println("\n" + "Player X, please input a valid number: ");
              input3 = keyboard.next();
                   int letterLength3 = input3.length();
                        for(int i3=0; i3<letterLength3; i3++){
                        letter=input3.charAt(i3);
                        if(letter=='1')
                             System.out.print(boardX[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                                  if(letter=='2')
                             System.out.print(board[0][0] + "" + boardX[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='3')
                             System.out.print(board[0][0] + "" + board[0][1] + boardX[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='4')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + boardX[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='5')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + boardX[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='6')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + boardX[1][2] + "\n" + board[2][0] + board[2][1] + board[2][2]);
                        if(letter=='7')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + boardX[2][0] + board[2][1] + board[2][2]);
                        if(letter=='8')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + boardX[2][1] + board[2][2]);
                        if(letter=='9')
                                  System.out.print(board[0][0] + "" + board[0][1] + board[0][2] + "\n" + board[1][0] + board[1][1] + board[1][2] + "\n" + board[2][0] + board[2][1] + boardX[2][2]);
                        else if(Character.isLetter(letter))
                                  System.out.println("");
         }

  • 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

  • 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.

  • Tic - Tac - Toe Game - Please Help!

    Hi everyone, I am attempting to create a tic - tac - toe game (O's & X's).
    I would like there to be two playing modes to the game, the first mode will be one player where the user plays against the computer. The second mode is a two - player game, where two users play, one being X's and the other being O's.
    Can anyone help me get started with this game, I know there is source code on the internet but I would rather not use this as I would like to learn as I create the game.
    Thanks Everyone

    its amazing how much code a simple game like tic-tac-toe can require.. well, only if you program the AI of the computer.. i wrote one in c++ last year, for my computer science class, and the whole class had trouble with it, mainly the AI.. a suggestion to you: write it in an object-oriented manner. i ended up writing it procedurally and in the end, it looked very bad, but it worked!
    i would prob. setup some objects like: Board (the 3x3 grid), Mark (a user mark, such as an "x" or an "o")..
    i dunno.. hope that helps some, if you need help with the AI at all.. i do have the tic-tac-toe program i wrote on my website (http://www.angelfire.com/blues/smb/ ) in the C++ section.. i used a graphics package, but the logic is all there and the code is well commented.
    anyway, ill talk to ya later, good luck,
    Steven Berardi

  • Tic-Tac-Toe Project

    Hey, im making tic tac toe as my final project for Programming 1, and im gonna need some help. this is what i have so far:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TicTacToe extends JFrame implements ActionListener
         private JButton[][]buttons;
         public JButton[][] fillArray()
              String names="012345678";
              JButton [][]buttonArray=new JButton[3][3];
              int x=0;
              for(int r=0;r<3;r++)
                   for(int c=0;c<3;c++)
                        buttonArray[r][c]=new JButton();
                        buttonArray[r][c].addActionListener(this);
                        buttonArray[r][c].setActionCommand( names.substring(x,x+1));    
                        buttonArray[r][c].setBackground(Color.black);
                        buttonArray[r][c].setForeground(Color.white);
                        Font fontType = new Font("Serif", Font.BOLD, 100);
                        buttonArray[r][c].setFont(fontType);
                        contentPane.add(buttonArray[r][c]);
                        x++;
              return buttonArray;
         private static Container contentPane;
         public TicTacToe()
              setSize(800, 600);
              setTitle("Tic Tac Toe");
              contentPane = getContentPane();
              contentPane.setLayout(new GridLayout(3,3));
              fillArray();
         public void actionPerformed(ActionEvent event)
              Container contentPane = getContentPane();
              if(event.getActionCommand().equals("0"))
                   System.out.println("0");
              else if(event.getActionCommand().equals("1"))
                   System.out.println("1");
              else if(event.getActionCommand().equals("2"))
                   System.out.println("2");
              else if(event.getActionCommand().equals("3"))
                   System.out.println("3");
              else if( event.getActionCommand().equals("4"))
                   System.out.println("4");
              else if(event.getActionCommand().equals("5"))
                   System.out.println("5");
              else if(event.getActionCommand ().equals("6"))
                   System.out.println("6");
              else if(event.getActionCommand().equals("7"))
                   System.out.println("7");
              else if(event.getActionCommand().equals("8"))
                   System.out.println("8");
              else if(event.getActionCommand().equals("Exit"))
                   System.exit(0);
              else System.out.println("Error in button interface.");
         public static void main(String[] args)
              TicTacToe buttonGui= new TicTacToe();
              buttonGui.setVisible(true);
    }right now as you can see i just have the actionPerformed to print the number in the console window cuz i wanted to make sure it works. What do i need to put in the actionPerformed to get an X or an O to print on the button?

    its not working, what am i missing?
              String text="X";
              if(event.getActionCommand().equals("0"))
                   buttons[][].setText(text);its underlined.

  • Tic tac toe 3x3 multiplaye​r game

    How can i build a tic tac toe game in labview
    What im interested in is the following
    1) A 3x3 multiplayer game
    2) A boolean to move left in the tictactoe grid and another to move down
    3) A boolean array to display the grid an another string array to show the X and O's
    4) A boolean to confirm player's choice
    5) A way to choose whether player 1 or player 2 begins
    6) A way to show which player wins or loses, or if it is a draw.
    Thank You in Advance
    I appreciate your help 

    Some of your classmates with the same assignment already asked this quesiton. Why don't you do a quick search before starting a new thread?
    LabVIEW Champion . Do more with less code and in less time .

  • Tic-Tac-Toe or Noughts & Crosses

    Hi
    I need help creating an effect which can best be described as using a single slide to create the game ‘Tic-Tac-Toe’ or ‘Noughts and Crosses’.
    The slide would have to contain 18 objects (9 circles and 9 crosses) in a 3 by 3 grid. Each to appear (dissolve, wipe etc) only if it is ‘clicked on’ using the mouse/pointer. Those that are NOT clicked on to remain hidden even when clicking to move to the next slide.
    Can this be done using Keynote?
    Thanks
    Jai

    You can create this, but, since Keynote doesn't handle hyperlinks like PowerPoint does, you would need one slide for each possible combination of game results. Given that each of the nine spaces has 3 possible options (X, O, or empty), I think the permutations would be 33*3*3*3*3*3*33 or (google tells me) 19,683 individual slides all connected with links.
    I'm not even sure how Keynote would react to having to cache that many slides at once.

  • 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!!");

  • 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 help using array

    Ok i am trying to get a tic tac toe game, which uses array. I need to get 3 buttons and store them then i can check those numbers to see if its a win. Here is my code
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int map[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i< c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String args[] )
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    I couldn't try this out due to a few syntax errors, so fixed some. Now the buttons seem to work.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int c[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
    private int flag;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3=0;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i < c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String[] args)
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

Maybe you are looking for

  • Can we assign value to a variable in PL/SQL Loop

    Hi Can we assign value to a variable in PL/SQL Loops? DECLARE V_Num NUMBER; BEGIN LOOP V_Num := 10; DBMS_OUTPUT.put_line(V_num); V_Num := V_Num - 1; EXIT WHEN V_Num = 0; END LOOP; END; In the above program, Can we assign V_num with a value 10????????

  • 4th Gen won't connect to internet even though it says it's connected

    Hello Apple Community! I have been using my (4th Gen) Time Capsule to back up my devices and for my household WiFi for about 2 years now. The other day, after a storm, my connectivity was down. I thought it was my ISP, but after bypassing the TC and

  • White Screen of Death (or coma, at least)

    Hi everyone, I've been searching all over the place for a couple of days and no solution to the following situation has worked as of yet, so any help would be greatly appreciated. Brand new installation of Snow Leopard on a late 2006 24" white iMac w

  • Zip'ing files from multiple folders to the same zip file

    Could somebody recommend a method to create a zip file with file contents from multiple folders? Or is there an application I can drag and drop a bunch of files to zip em?

  • Cost Center not appearing in FAGLL03

    Dear Forum, We have come accross a peculiar situation. The GL Document is posted using the Non-Statistical Order as well as Cost Center. However, when we veiw the Expense GL Account using the T Code FAGLL03, we cannot see the Cost Center, but can vie