Array of Characters(Tic Tac Toe)

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

use an int array
then u can do math to check

Similar Messages

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

  • 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

  • Help with Tic Tac Toe program....

    I am writing a tic tac toe program, and I have already put the 9 boxes onto the screen so that it looks like the Tic Tac Toe board.
    My first box looks something like this:
    Rectangle2D.Double box1 = new Rectangle2D.Double(0, 0, 100, 100);
    g2.draw(box1);
    I want assign a number to the 9 boxes so it looks like this:
    123
    456
    789
    And I want to know how am I suppose to assign a number to a box, so that when the number is pressed it will put an "X" or "O"(depending on whose turn it is).
    P.S. If you already made a Tic Tac Toe progaram can you post it so I will have an idea of what you did. thx.

    I'd hate to post the whole thing, but if you don't have access to it, here it goes:
    * @(#)TicTacToe.java     1.6 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.net.*;
    import java.applet.*;
    * A TicTacToe applet. A very simple, and mostly brain-dead
    * implementation of your favorite game! <p>
    * In this game a position is represented by a white and black
    * bitmask. A bit is set if a position is ocupied. There are
    * 9 squares so there are 1<<9 possible positions for each
    * side. An array of 1<<9 booleans is created, it marks
    * all the winning positions.
    * @version      1.2, 13 Oct 1995
    * @author Arthur van Hoff
    * @modified 04/23/96 Jim Hagen : winning sounds
    * @modified 02/10/98 Mike McCloskey : added destroy()
    public
    class TicTacToe extends Applet implements MouseListener {
         * White's current position. The computer is white.
        int white;
         * Black's current position. The user is black.
        int black;
         * The squares in order of importance...
        final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
         * The winning positions.
        static boolean won[] = new boolean[1 << 9];
        static final int DONE = (1 << 9) - 1;
        static final int OK = 0;
        static final int WIN = 1;
        static final int LOSE = 2;
        static final int STALEMATE = 3;
         * Mark all positions with these bits set as winning.
        static void isWon(int pos) {
         for (int i = 0 ; i < DONE ; i++) {
             if ((i & pos) == pos) {
              won[i] = true;
         * Initialize all winning positions.
        static {
         isWon((1 << 0) | (1 << 1) | (1 << 2));
         isWon((1 << 3) | (1 << 4) | (1 << 5));
         isWon((1 << 6) | (1 << 7) | (1 << 8));
         isWon((1 << 0) | (1 << 3) | (1 << 6));
         isWon((1 << 1) | (1 << 4) | (1 << 7));
         isWon((1 << 2) | (1 << 5) | (1 << 8));
         isWon((1 << 0) | (1 << 4) | (1 << 8));
         isWon((1 << 2) | (1 << 4) | (1 << 6));
         * Compute the best move for white.
         * @return the square to take
        int bestMove(int white, int black) {
         int bestmove = -1;
          loop:
         for (int i = 0 ; i < 9 ; i++) {
             int mw = moves;
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              int pw = white | (1 << mw);
              if (won[pw]) {
              // white wins, take it!
              return mw;
              for (int mb = 0 ; mb < 9 ; mb++) {
              if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
                   int pb = black | (1 << mb);
                   if (won[pb]) {
                   // black wins, take another
                   continue loop;
              // Neither white nor black can win in one move, this will do.
              if (bestmove == -1) {
              bestmove = mw;
         if (bestmove != -1) {
         return bestmove;
         // No move is totally satisfactory, try the first one that is open
         for (int i = 0 ; i < 9 ; i++) {
         int mw = moves[i];
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              return mw;
         // No more moves
         return -1;
    * User move.
    * @return true if legal
    boolean yourMove(int m) {
         if ((m < 0) || (m > 8)) {
         return false;
         if (((black | white) & (1 << m)) != 0) {
         return false;
         black |= 1 << m;
         return true;
    * Computer move.
    * @return true if legal
    boolean myMove() {
         if ((black | white) == DONE) {
         return false;
         int best = bestMove(white, black);
         white |= 1 << best;
         return true;
    * Figure what the status of the game is.
    int status() {
         if (won[white]) {
         return WIN;
         if (won[black]) {
         return LOSE;
         if ((black | white) == DONE) {
         return STALEMATE;
         return OK;
    * Who goes first in the next game?
    boolean first = true;
    * The image for white.
    Image notImage;
    * The image for black.
    Image crossImage;
    * Initialize the applet. Resize and load images.
    public void init() {
         notImage = getImage(getCodeBase(), "images/not.gif");
         crossImage = getImage(getCodeBase(), "images/cross.gif");
         addMouseListener(this);
    public void destroy() {
    removeMouseListener(this);
    * Paint it.
    public void paint(Graphics g) {
         Dimension d = getSize();
         g.setColor(Color.black);
         int xoff = d.width / 3;
         int yoff = d.height / 3;
         g.drawLine(xoff, 0, xoff, d.height);
         g.drawLine(2*xoff, 0, 2*xoff, d.height);
         g.drawLine(0, yoff, d.width, yoff);
         g.drawLine(0, 2*yoff, d.width, 2*yoff);
         int i = 0;
         for (int r = 0 ; r < 3 ; r++) {
         for (int c = 0 ; c < 3 ; c++, i++) {
              if ((white & (1 << i)) != 0) {
              g.drawImage(notImage, c*xoff + 1, r*yoff + 1, this);
              } else if ((black & (1 << i)) != 0) {
              g.drawImage(crossImage, c*xoff + 1, r*yoff + 1, this);
    * The user has clicked in the applet. Figure out where
    * and see if a legal move is possible. If it is a legal
    * move, respond with a legal move (if possible).
    public void mouseReleased(MouseEvent e) {
         int x = e.getX();
         int y = e.getY();
         switch (status()) {
         case WIN:
         case LOSE:
         case STALEMATE:
         play(getCodeBase(), "audio/return.au");
         white = black = 0;
         if (first) {
              white |= 1 << (int)(Math.random() * 9);
         first = !first;
         repaint();
         return;
         // Figure out the row/column
         Dimension d = getSize();
         int c = (x * 3) / d.width;
         int r = (y * 3) / d.height;
         if (yourMove(c + r * 3)) {
         repaint();
         switch (status()) {
         case WIN:
              play(getCodeBase(), "audio/yahoo1.au");
              break;
         case LOSE:
              play(getCodeBase(), "audio/yahoo2.au");
              break;
         case STALEMATE:
              break;
         default:
              if (myMove()) {
              repaint();
              switch (status()) {
              case WIN:
                   play(getCodeBase(), "audio/yahoo1.au");
                   break;
              case LOSE:
                   play(getCodeBase(), "audio/yahoo2.au");
                   break;
              case STALEMATE:
                   break;
              default:
                   play(getCodeBase(), "audio/ding.au");
              } else {
              play(getCodeBase(), "audio/beep.au");
         } else {
         play(getCodeBase(), "audio/beep.au");
    public void mousePressed(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public String getAppletInfo() {
         return "TicTacToe by Arthur van Hoff";

  • Help Tic Tac Toe beginner

    A Tic Tac Toe board is represented as an array of 9 chars. Write a program that will allow two users to play tic tac toe. The player should ask for moves alternately from players X and O. The program is too dumb to check whether anyone has won or lost and just stops after 9 turns. The program should display the game position as follows after each move.
    The output should be somewhat as follows:
    Choose a spot (1 to 9) for X: 1
    X || ||
    || ||
    || ||
    Basically i have to do this. I was wondering if anyone could lead me in the right direction please?

    class TicTacToe {
        // instance variables
        // constructor(s)
        // method(s)
        public static void main(String[] args) {
            new TicTacToe();
    }There you go. I got you started. Now all you need to do is finish.

  • NEED TIC TAC TOE HELP

    Why do I keep getting the following errors in a very simple, basic TIC TAC TOE program? Any help would be greatly appreciated. Thanks.
    C:\Class\Teresa\TicTacToe017.java:114: 'else' without 'if'
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    ^
    C:\Class\Teresa\TicTacToe017.java:185: 'else' without 'if'
    else // Next player's turn
    ^
    C:\Class\Teresa\TicTacToe017.java:39: cannot resolve symbol
    symbol : method call ()
    location: class TicTacToe017
                        call();
    ^
    C:\Class\Teresa\TicTacToe017.java:145: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:165: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:181: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    6 errors
    Tool completed with exit code 1
    Here is my code so far.
    File name: TicTacToe.java
    A class to play TicTacToe.
    Entries cannot be changed once they are entered.
    Written by: Lew Rakocy
    email address: [email protected]
    Date: 9/2/00
    Changes: 03/13/2003 Made comments like text examples.
    Added code to display board after win and draw.
    public class TicTacToe017
    // Use a 3 X 3 (two-dimensional) array for the game board.
    private static char[][] board = new char[3][3];
    private static char turn;
    private static int row; // Loop controls to
    private static int col; // display the board
    private static int turnRow; // User input to
    private static int turnCol; // select move
    private static boolean entryError;
    private static boolean anotherGame = true;
    private static char repeat; // User input: y or Y to repeat
    private static int entryCount = 0; // Game ends when board is full
    // (when entryCount = 9);
    public static void main(String[] args)
    while(anotherGame)
    newGame();
    while(!winner())
                        //WRITE THE METHOD CALL TO DISPLAY THE "BOARD" HERE
                        call();
                        System.out.println("This is the game board.");
    //WRITE THE METHOD CALL FOR THE "PLAY" OF THE GAME HERE
                        System.out.print("Welcome to Teresa's Tic Tac Toe!");
    System.out.println("Another game? Enter Y or y for yes.");
    repeat = SavitchIn.readLineNonwhiteChar();
    //WRITE THE IF/ELSE STATEMENT TO PLAY ANOTHER GAME HERE
    if ((repeat == 'Y') || (repeat == 'y'))
         System.out.println("Play another game.");
    else
         System.out.println("End of game. Thanks for playing.");
    //WRITE THE HEADER FOR THE writeBoard METHOD HERE
    System.out.println("-----------------");
    System.out.println("|R\\C| 1 | 2 | 3 |");
    System.out.println("-----------------");
    for(row = 0; row < 3; ++row)
    System.out.println("| " + (row + 1)
    + " | " + board[row][0]
    + " | " + board[row][1]
    + " | " + board[row][2]
    + " |");
    System.out.println("-----------------");
    private static void getMove()
    entryError = true; // Will change to false if valid row
    // and column numbers are entered.
    while(entryError)
    System.out.println();
    System.out.println(turn + "'s turn.");
    System.out.println("Where do what your " + turn + " placed?");
    System.out.println(
    "Please enter row number and column number"
    + " separated by a space.");
    System.out.println();
    turnRow = SavitchIn.readInt();
    turnCol = SavitchIn.readInt();
    System.out.println("You have entered row #" + turnRow);
    System.out.println(" and column #" + turnCol);
    // Check for proper range (1, 2, or 3)
                   //WRITE THE IF STATEMENT HERE FOR AN INVALID ENTRY
                   if (board[turnRow - 1][turnCol - 1] > 3)
              System.out.println("Invalid entry: try again.");
    System.out.println(
    "Row & column numbers must be either 1, 2, or 3.");
    // Check to see if it is already occupied
    // Adjust turnRow and turnCol for 0-numbering in array
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    || board[turnRow - 1][turnCol - 1] == 'O')
    System.out.println("That cell is already taken.");
    System.out.println("Please make another selection.");
    else // Valid entry
    entryError = false;
    System.out.println("Thank you for your selection.");
    board[turnRow - 1][turnCol - 1] = turn;
    ++entryCount;
    private static boolean winner()
    // Row checks
    for(row = 0; row < 3; ++row)
    if(board[row][0] == turn)
    if(board[row][1] == turn)
    if(board[row][2] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // WRITE A FOR LOOP FOR THE COLUMN CHECKS HERE
    // WRITE A FOR LOOP FOR THE DIAGONAL CHECKS HERE
    if(board[0][2] == turn)
    if(board[1][1] == turn)
    if(board[2][0] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // These lines execute only if there is no winner.
    // End game if board is full
    //WRITE THE IF STATEMENT TO CHECK IF THE BOARD IS FULL
              if (entryCount == 9)
    System.out.println();
    System.out.println("Draw: no winner and board is full.");
    writeBoard();
    return true;
    else // Next player's turn
    //WRTITE THE IF/ELSE STATEMENT FOR THE NEXT PLAYER'S TURN
    return false;
    private static void newGame()
    System.out.println();
    System.out.println("New Game: X goes first.");
    turn = 'O'; // Turn will change to X when winner() is called
    // Clear the board
    for(row = 0; row < 3; ++row)
    for(col = 0; col < 3; ++col)
    board[row][col] = ' ';
    entryCount = 0;
    System.out.println();

    the "else without if" means that you have an else statement that wasn't attached to an if statement. In your case, it seems to be because you had multiple statements following an if statement, and you didn't enclose them in a single block.
    The "cannot resolve symbol" means that you referred to something that wasn't defined. Either it's your code, and you forgot to define it, or you were referring to someone else's code, in which case you probably forgot an import statement, or you're using their code incorrectly.

  • 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 code Help

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

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

  • Tic Tac Toe Java help!

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

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

  • Tic Tac Toe with simple GUI

    Hello,
    I am working on a Tic Tac Toe game, I have already started woking on it put i am
    stuck on the array part. This is what is required in the project: Create a nine-member array to hold results of the game.. Initialize the array before the start of the game...Allow the user input to indicate which square ther user selects...
    Thank You
    help will be appreciated..
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.applet.*;
    public class TicTacToe extends Applet
    public void init()
    // declaration aand created array
    int Array[];
    Array = new int[8];
    String input1;
    String input2;
    int choice1;
    int choice2;
    input1 =
    JOptionPane.showInputDialog
    "Please select your symbol\n"+
    "1= O \n"+
    "2= X \n");
    // converts string to integer
    choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint (Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
    int X_coordinate = d.width / 3;
         int Y_coordinate = d.height / 3;
         g.drawLine(X_coordinate, 0, X_coordinate, d.height);      
         g.drawLine(2*X_coordinate, 0, 2*X_coordinate, d.height);
         g.drawLine(0, Y_coordinate, d.width, Y_coordinate);
         g.drawLine(0, 2*Y_coordinate, d.width, 2*Y_coordinate);
    } //end of paitn method
    }// end of class

    Try this:
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    public class TicTac extends JApplet
    public void init()
    // declaration aand created array
         int Array[] = new int[8];
         String input1;
         String input2;
         int    choice1 = 0;
         int    choice2;
         for(int i=0; i < Array.length; i++) Array[i] = 0;
         while (choice1 == 0)
              input1 = JOptionPane.showInputDialog
                   ("Please select your symbol\n"+
                    "1= O \n"+
                    "2= X \n");
              if (input1.equals("1")) choice1 = 1;
              if (input1.equals("2")) choice1 = 2;
    //     converts string to integer
    //     choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint(Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
         int sz = 0;
         if (d.height/4 - 10 < d.width/4) sz = d.height / 4;
              else             sz = d.width  / 4;
         for (int j=0; j < 4; j++)
              g.drawLine(10,sz*j+10,sz*3+10,sz*j+10);
              g.drawLine(j*sz+10,10,j*sz+10,sz*3+10);
         g.setColor(Color.black);
         g.drawRect(9,9,sz*3+2,sz*3+2);
    } //end of paitn method
    }// end of class
    Noah
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    public class TicTac extends JApplet
    public void init()
    // declaration aand created array
         int Array[] = new int[8];
         String input1;
         String input2;
         int choice1 = 0;
         int choice2;
         for(int j=0; j < Array.length; j++) Array[j] = 0;
         while (choice1 == 0)
              input1 = JOptionPane.showInputDialog
                   ("Please select your symbol\n"+
                   "1= O \n"+
                   "2= X \n");
              if (input1.equals("1")) choice1 = 1;
              if (input1.equals("2")) choice1 = 2;
    //     converts string to integer
    //     choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint(Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
         int sz = 0;
         if (d.height/4 - 10 < d.width/4) sz = d.height / 4;
              else                         sz = d.width / 4;
         for (int j=0; j < 4; j++)
              g.drawLine(10,sz*j+10,sz*3+10,sz*j+10);
              g.drawLine(j*sz+10,10,j*sz+10,sz*3+10);
         g.setColor(Color.black);
         g.drawRect(9,9,sz*3+2,sz*3+2);
    } //end of paitn method
    }// end of class

  • Tic Tac Toe game using Graphs

    Does anyone know of an open-source implementation of Tic-Tac-Toe using Graphs? I'm reading through Michael Mann's Data Structures and Other Objects Using Java book and in chapter 14, he briefly mentions the use of directed graphs in implementing a game of Tic Tac Toe. I'm interested in seeing how one would implement something of this sort (and no, it's not a homework assignment).
    If someone would be kind enough as to post a link to a site that offers mini-java applications, along with code that novice developers such as myself can traverse, please do so.
    Thanks in advance.

    As an added though, there's really no need to for each node to keep track of incoming connections, only outgoing ones. What I, personally would do is keep an array of 8 outgoing connections, one for each direction. If no connection was there, then that element in the array would be null. If a connection was there, then that element would be an edge connecting to another node, or the other node itself (depending on whether or not you explicitly implemented 'edges' in your graph).
    That way, you could do something like:
        Node    s         = getOneOfTheEdgeNodes();
        boolean hasWinner = false;    
        try {
            for (int i = 0; i < 8; i ++) {
                if (s.getOutgoing(i).getNode().getOutgoing(i).getNode() != null) {
                    hasWinner = true;
                    break;
        } catch (NullPointerException npx) {
            // No winner.
        if (hasWinner)
            System.out.println(s.getPlayer() + " has won");Yeah, that's a shitty example, but hopefully you get my drift.
    Jason

  • Tic tac toe pls help! there is clarification

    How can i build a tic tac toe game in labview
    What im interested in is the following, and ive added an image of what the front panel should look like with some clarification
    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 !!
    Attachments:
    3.JPG ‏58 KB

    You have already asked the question here.
    You still have to prove that this isn't homework. 

  • Tic Tac Toe Program

    I want to write a tic tac toe applet that draws a game board and then accepts mouseclicks into the squares. It automatically changes players after each turn and declares a winner at the end.
    I figured out how I might do this by using a JFrame with a grid layout of buttons in a panel (i.e. click buttons and their labels change?).
    But how would I go about doing it without using buttons. I need to create a grid of squares that accept mouse clicks. I also need to be able to proclaim a winner based upon a winning pattern.
    Any ideas? Could you just point me in the right direction?
    How would the grid be generated? (A series of rectangle objects? Lines?)
    How would I actually place a letter (x or o) in a square. ( some calculating of bounding coordinates for each box?)
    Thanks!!

    each square could be a jpanel. write a class called Square, that extends jpanel.
    implement MouseListener... and that's about it. It will just be a state machine.
    In your main class, make a 2d array of Squares...
    not really difficult.

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

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

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

Maybe you are looking for

  • I bought a £15 itunes card to download some music on to my iphone but it wont take any money off it and keeps asking for my card details,

    This is the first time i have brought an itunes voucher to use on my iphone, i have been able to redeem it and it shows up on my account but it wont take any money off it and it just keeps asking for my apple id all over agin and for my card details.

  • Creating a service material.

    Hi All, One  of the user has sent a request to create a service material (Security Software). This is mainly for to improve security of the current billing  cycle. I used T-Code MM01 to created the material but later on instructed to create this mate

  • Changes to 3rd party cookies options are not saved

    I want to change Cookies setting to allow 3rd party cookies because an important website that I access frequently says that my browser (Firefox) does not accept these cookies. I am following the Firefox Support instructions @ https://support.mozilla.

  • SORT NODE Fn. in Mapping

    Hello, I am trying to use this node fn sort in my gui mapping and whenever i use this fn and execute my mapping shows error: RuntimeException in Message-Mapping transformation: Exception:[java.lang.IllegalArgumentException: Unknown comparator type: L

  • 2010 Mac Pro and Leopard

    I recently purchased a retail version of Leopard.  I want to install this on my 2010 3.3ghz 6-core Mac Pro, but no luck.  The DVD just does not work.  I'm thinking you can't do it on the Mac Pro.. Thoughts?  Thank you.