Get blank screen each time? tic tac toe GUI...

I get a blank screen each time i run this...I'm trying to display a tic tac toe board...the x's and o's are randomly generated...any idea why it's blank each time??
public class TicTacToe extends JFrame
     private ImageIcon x = new ImageIcon("cross.gif");
     private ImageIcon o = new ImageIcon("not.gif");
     Random random = new Random(2);
     public TicTacToe()
          setLayout(new GridLayout(3,3));
          for(int y = 0; y<= 9; y++)
            Random r = new Random(2);
               int randint = r.nextInt();
               if (randint == 0)
                    add(new JLabel(x));
               if (randint == 2)
                    add(new JLabel(o));
     public static void main(String args[])
          TicTacToe frame = new TicTacToe();
          frame.setTitle("Tic Tac Toe");
          frame.setSize(450,450);
          frame.setLocationRelativeTo(null);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
}

Timm017 wrote:
Interested, what was wrong?He used Random and random.nextInt() incorrectly. Given that nextInt() without arguments can return any int between Integer.MIN_VALUE and Integer.MAX_VALUE with equal probability, the chance of hitting 0 or 2 is fairly low. So, most times (for most Random seeds), his code would never add any buttons to the panel. And, actually, since he used a '2' to seed the Random generator, he always got the same sequence of "random" numbers every time. So, his code would always give the same 9 numbers, and, apparently, those numbers don't include either 0 or 2.
By the way, rollarace, besides picking the proper nextInt(...) method [you want the one that requires a parameter, as I assume you figured out], you should create the Random object once BEFORE the loop starts, and then just reuse it.
Also:
for(int y = 0; y<= 9; y++)should be:
for(int y = 0; y< 9; y++)Otherwise, once the nextInt(...) part was fixed, he'd add 10 buttons.

Similar Messages

  • Creating Tic Tac Toe GUI game.

    Okay so can someone please help fix my code for Tic Tac Toe i have no idea how to! =/
    I'm new to programming so help would be appreciated..
    thanx.
    <code>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToe implements ActionListener {
    /*Instance Variables*/
    private JFrame window = new JFrame("Tic-Tac-Toe");
    private JButton button1 = new JButton("");
    private JButton button2 = new JButton("");
    private JButton button3 = new JButton("");
    private JButton button4 = new JButton("");
    private JButton button5 = new JButton("");
    private JButton button6 = new JButton("");
    private JButton button7 = new JButton("");
    private JButton button8 = new JButton("");
    private JButton button9 = new JButton("");
    private String letter = "";
    private ImageIcon O = new ImageIcon("LET-O.jpg");
    private ImageIcon X = new ImageIcon("LET-X.jpg");
    private int count = 0;
    private boolean win = false;
    public TicTacToe(){
    /*Create Window*/
    window.setSize(300,300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new GridLayout(3,3));
    /*Add Buttons To The Window*/
    window.add(button1);
    window.add(button2);
    window.add(button3);
    window.add(button4);
    window.add(button5);
    window.add(button6);
    window.add(button7);
    window.add(button8);
    window.add(button9);
    /*Add The Action Listener To The Buttons*/
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    button6.addActionListener(this);
    button7.addActionListener(this);
    button8.addActionListener(this);
    button9.addActionListener(this);
    /*Make The Window Visible*/
    window.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9)
         X = new ImageIcon("LET-X.jpg");
    else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
         O = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(e.getSource() == button1){
    button1.setIcon();
    button1.setEnabled(false);
    } else if(e.getSource() == button2){
    button2.setIcon();
    button2.setEnabled(false);
    } else if(e.getSource() == button3){
    button3.setIcon();
    button3.setEnabled(false);
    } else if(e.getSource() == button4){
    button4.setIcon();
    button4.setEnabled(false);
    } else if(e.getSource() == button5){
    button5.setIcon();
    button5.setEnabled(false);
    } else if(e.getSource() == button6){
    button6.setIcon();
    button6.setEnabled(false);
    } else if(e.getSource() == button7){
    button7.setIcon();
    button7.setEnabled(false);
    } else if(e.getSource() == button8){
    button8.setIcon();
    button8.setEnabled(false);
    } else if(e.getSource() == button9){
    button9.setIcon();
    button9.setEnabled(false);
    //Determine who won
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //vertical wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    /*Show a dialog if someone wins or the game is tie*/
    if(win == true)
    JOptionPane.showMessageDialog(null, letter + " WINS!");
    else if(count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "Tie Game!");
    public static void main(String[] args)
    new TicTacToe();
    </code>

    Yeah Thanks.
    So I'm just stuck here. Like I need to program a Tic Tac Toe GUI with the X's and O's as images but I have no clue on what to do next. I have the images for both but I don't know how to make them work once the buttons are clicked.
    Sorry here it is again..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToe implements ActionListener {
    /*Instance Variables*/
    private JFrame window = new JFrame("Tic-Tac-Toe");
    private JButton button1 = new JButton("");
    private JButton button2 = new JButton("");
    private JButton button3 = new JButton("");
    private JButton button4 = new JButton("");
    private JButton button5 = new JButton("");
    private JButton button6 = new JButton("");
    private JButton button7 = new JButton("");
    private JButton button8 = new JButton("");
    private JButton button9 = new JButton("");
    private String letter = "";
    private ImageIcon O = new ImageIcon("LET-O.jpg");
    private ImageIcon X = new ImageIcon("LET-X.jpg");
    private int count = 0;
    private boolean win = false;
    public TicTacToe(){
    /*Create Window*/
    window.setSize(300,300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new GridLayout(3,3));
    /*Add Buttons To The Window*/
    window.add(button1);
    window.add(button2);
    window.add(button3);
    window.add(button4);
    window.add(button5);
    window.add(button6);
    window.add(button7);
    window.add(button8);
    window.add(button9);
    /*Add The Action Listener To The Buttons*/
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    button6.addActionListener(this);
    button7.addActionListener(this);
    button8.addActionListener(this);
    button9.addActionListener(this);
    /*Make The Window Visible*/
    window.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9)
    X = new ImageIcon("LET-X.jpg");
    else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
    O = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(e.getSource() == button1){
    button1.setIcon();
    button1.setEnabled(false);
    } else if(e.getSource() == button2){
    button2.setIcon();
    button2.setEnabled(false);
    } else if(e.getSource() == button3){
    button3.setIcon();
    button3.setEnabled(false);
    } else if(e.getSource() == button4){
    button4.setIcon();
    button4.setEnabled(false);
    } else if(e.getSource() == button5){
    button5.setIcon();
    button5.setEnabled(false);
    } else if(e.getSource() == button6){
    button6.setIcon();
    button6.setEnabled(false);
    } else if(e.getSource() == button7){
    button7.setIcon();
    button7.setEnabled(false);
    } else if(e.getSource() == button8){
    button8.setIcon();
    button8.setEnabled(false);
    } else if(e.getSource() == button9){
    button9.setIcon();
    button9.setEnabled(false);
    //Determine who won
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //vertical wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    /*Show a dialog if someone wins or the game is tie*/
    if(win == true)
    JOptionPane.showMessageDialog(null, letter + " WINS!");
    else if(count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "Tie Game!");
    public static void main(String[] args)
    new TicTacToe();
    }

  • Tic Tac Toe GUI!!

    Hey can someone please tell me how to hide the text in my code so that when I run it, the images only appear no text.
    thanks.
    Here's what I have so far..
    public void actionPerformed(ActionEvent a) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
    letter = "X";
    Icon = new ImageIcon("LET-X.jpg");
    } else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
    letter = "O";
    Icon = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(a.getSource() == button1){
         button1.setText(letter);
    button1.setIcon(Icon);
    button1.setEnabled(false);
    } else if(a.getSource() == button2){
         button2.setText(letter);
         button2.setIcon(Icon);
    button2.setEnabled(false);
    } else if(a.getSource() == button3){
         button3.setText(letter);
         button3.setIcon(Icon);
    button3.setEnabled(false);
    } else if(a.getSource() == button4){
         button4.setText(letter);
         button4.setIcon(Icon);
    button4.setEnabled(false);
    } else if(a.getSource() == button5){
         button5.setText(letter);
         button5.setIcon(Icon);
    button5.setEnabled(false);
    } else if(a.getSource() == button6){
         button6.setText(letter);
         button6.setIcon(Icon);
    button6.setEnabled(false);
    } else if(a.getSource() == button7){
         button7.setText(letter);
         button7.setIcon(Icon);
    button7.setEnabled(false);
    } else if(a.getSource() == button8){
         button8.setText(letter);
         button8.setIcon(Icon);
    button8.setEnabled(false);
    } else if(a.getSource() == button9){
         button9.setText(letter);
         button9.setIcon(Icon);
    button9.setEnabled(false);
    /*Determine who won*/
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //virticle wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    }

    Yeah but then it messes up the whole code. It won't determine who wins if I stop calling the setText method.
    Is there a better way to code this??
    public void actionPerformed(ActionEvent a) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
    letter = "X";
    Icon = new ImageIcon("LET-X.jpg");
    } else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
    letter = "O";
    Icon = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(a.getSource() == button1){
         button1.setText(letter);
    button1.setIcon(Icon);
    button1.setEnabled(false);
    } else if(a.getSource() == button2){
         button2.setText(letter);
         button2.setIcon(Icon);
    button2.setEnabled(false);
    } else if(a.getSource() == button3){
         button3.setText(letter);
         button3.setIcon(Icon);
    button3.setEnabled(false);
    } else if(a.getSource() == button4){
         button4.setText(letter);
         button4.setIcon(Icon);
    button4.setEnabled(false);
    } else if(a.getSource() == button5){
         button5.setText(letter);
         button5.setIcon(Icon);
    button5.setEnabled(false);
    } else if(a.getSource() == button6){
         button6.setText(letter);
         button6.setIcon(Icon);
    button6.setEnabled(false);
    } else if(a.getSource() == button7){
         button7.setText(letter);
         button7.setIcon(Icon);
    button7.setEnabled(false);
    } else if(a.getSource() == button8){
         button8.setText(letter);
         button8.setIcon(Icon);
    button8.setEnabled(false);
    } else if(a.getSource() == button9){
         button9.setText(letter);
         button9.setIcon(Icon);
    button9.setEnabled(false);
    /*Determine who won*/
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //virticle wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    }

  • Email app won't open. I get blank screen and it immediately force closes. I've rebooted the iPad several times.  It still works on my iPhone 5s

    Email app won't open. I get blank screen and it immediately force closes. I've rebooted the iPad several times.  It still works on my iPhone 5s

    Hi Darr4425,
    That's not good! We definitely want your device to work properly at all times. What email application are you attempting to open? When did the issue start? Do you receive an error message when the application force closes?
    Thanks,
    PamelaF_VZW
    Follow us on Twitter @VZWSupport
    If my response answered your question please click the "Correct Answer" button under my response. This ensures others can benefit from our conversation. Thanks in advance for your help with this!!

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

  • Test out this Tic Tac Toe game please

    I know this is suppose to be a real java forum, but this is stripped down version of java, but it's still java. Before using real java I used this Judo. So can you guys download the stuff and play it a few times. Give me any suggestions or bug reports. This is v. 1.0 and there isn't a winner decider yet. Thanks and hope you have fun!
    You will need to download JUDO
    http://judo.sourceforge.net/#download
    Open JUDO and paste this code into it and run.
    void main () {
    String Intro = "Tic Tac Toe v 1.0 only funcutions under lower case letters.";
    String Start = "Execute y/n...";
    drawString(Intro, 150,50);
    drawString(Start, 150,70);
    String Go = "y";
    String go;
    go = readString();
    if(equal(go,Go)){
    setColor(blue);
    for(int loading = 0 ; loading < 460; loading++)
    int lpercent = loading;
    //printLine("Loading percent... "+lpercent/460+"%");
    fillRectangle(loading*1,250, 25,25);
    delay(0.01);
    String complete = "Loading Complete...";
    drawString(complete,0,235);
    //Ask what user would like [X or O]
    //get player name
    String PlayerName;
    String PlayerName2;
    printLine("Enter Player 1 name...");
    PlayerName = readString();
    printLine("Enter Player 2 name...");
    PlayerName2 = readString();
    //Recycle program loop here
    String execute = "y";
    String yes = "y";
    //While user would still like to run program
    while(equal(execute, yes)) {
    //decide player symbol
    String PlayerOne;
    String PlayerTwo;
    printLine("Select player 1 character...[x or o]");
    PlayerOne = readString();
    String O = "o";
    String X = "x";
    if(equal(PlayerOne, X) ) {
    PlayerTwo = O;
    else{
    PlayerTwo = X;
    //Printout inputed data
    printLine("Player 1 : ("+ PlayerOne +") " + PlayerName + " Player 2 : (" + PlayerTwo +") "+ PlayerName2);
    //Draw playing board
    String info = "Player 1 : ("+ PlayerOne +") " + PlayerName + " | Player 2 : (" + PlayerTwo +") "+ PlayerName2;
    //clearDrawing();
    for(int roundTime = 0 ; roundTime < 6; roundTime++) {
    setBackgroundColor(azure);
    drawString(info, 150,50);
    //horizontal lines
    setColor(black);
    drawLine(100,100, 400,100);
    drawLine(100,101, 400,101);
    drawLine(100,141, 400,141);
    drawLine(100,142, 400,142);
    drawLine(100,182, 400,182);
    drawLine(100,183, 400,183);
    //verticle lines
    drawLine(200,60, 200,223);
    drawLine(201,60, 201,223);
    drawLine(300,60, 300,223);
    drawLine(301,60, 301,223);
    //code boxed
    String a = "A";
    String b = "B";
    String c = "C";
    String d = "D";
    String one = "1";
    String two = "2";
    String three = "3";
    drawString(a, 100,80);
    drawString(b, 100,120);
    drawString(c, 100,160);
    drawString(d, 100,200);
    drawString(one, 150,230);
    drawString(two, 250,230);
    drawString(three, 350,230);
    //Let X go first then O (continue alternating)
    String pOne = PlayerName + "'s turn to move...";
    String pTwo = PlayerName2 + "'s turn to move...";
    if(equal(PlayerOne,X)) {
    drawString(pOne, 50,243);
    else{
    drawString(pTwo, 50,243);
    //ask user to make move here, then alternate character moves.
    String move;
    String move2;
    String A1 = "a1";
    String A2 = "a2";
    String A3 = "a3";
    String B1 = "b1";
    String B2 = "b2";
    String B3 = "b3";
    String C1 = "c1";
    String C2 = "c2";
    String C3 = "c3";
    String D1 = "d1";
    String D2 = "d2";
    String D3 = "d3";
    printLine("Please enter your character position player(X)...");
    move = readString();
    String CX = "X";
    String CO = "O";
    if(equal(move,A1)) {
    setColor(blue);
    drawString(CX, 42, 140,99);
    else{
    //continue program execution
    if(equal(move,A2)) {
    setColor(blue);
    drawString(CX, 42, 240,99);
    else{
    //continue program execution
    if(equal(move,A3)) {
    setColor(blue);
    drawString(CX, 42, 340,99);
    else{
    //continue program execution
    if(equal(move,B1)) {
    setColor(blue);
    drawString(CX, 42, 140,140);
    else{
    //continue program execution
    if(equal(move,B2)) {
    setColor(blue);
    drawString(CX, 42, 240,140);
    else{
    //continue program execution
    if(equal(move,B3)) {
    setColor(blue);
    drawString(CX, 42, 340,140);
    else{
    //continue program execution
    if(equal(move,C1)) {
    setColor(blue);
    drawString(CX, 42, 140,181);
    else{
    //continue program execution
    if(equal(move,C2)) {
    setColor(blue);
    drawString(CX, 42, 240,181);
    else{
    //continue program execution
    if(equal(move,C3)) {
    setColor(blue);
    drawString(CX, 42, 340,181);
    else{
    //continue program execution
    if(equal(move,D1)) {
    setColor(blue);
    drawString(CX, 42, 140,222);
    else{
    //continue program execution
    if(equal(move,D2)) {
    setColor(blue);
    drawString(CX, 42, 240,222);
    else{
    //continue program execution
    if(equal(move,D3)) {
    setColor(blue);
    drawString(CX, 42, 340,222);
    else{
    //continue program execution
    //clearDrawing();
    if(equal(PlayerOne,X)) {
    drawString(pTwo, 50,243);
    else{
    drawString(pOne, 50,243);
    //O 's movement here
    printLine("Please enter your character position player(O)...");
    move2 = readString();
    if(equal(move2,A1)) {
    setColor(red);
    drawString(CO, 42, 140,99);
    else{
    //continue program execution
    if(equal(move2,A2)) {
    setColor(red);
    drawString(CO, 42, 240,99);
    else{
    //continue program execution
    if(equal(move2,A3)) {
    setColor(red);
    drawString(CO, 42, 340,99);
    else{
    //continue program execution
    if(equal(move2,B1)) {
    setColor(red);
    drawString(CO, 42, 140,140);
    else{
    //continue program execution
    if(equal(move2,B2)) {
    setColor(red);
    drawString(CO, 42, 240,140);
    else{
    //continue program execution
    if(equal(move2,B3)) {
    setColor(red);
    drawString(CO, 42, 340,140);
    else{
    //continue program execution
    if(equal(move2,C1)) {
    setColor(red);
    drawString(CO, 42, 140,181);
    else{
    //continue program execution
    if(equal(move2,C2)) {
    setColor(red);
    drawString(CO, 42, 240,181);
    else{
    //continue program execution
    if(equal(move2,C3)) {
    setColor(red);
    drawString(CO, 42, 340,181);
    else{
    //continue program execution
    if(equal(move2,D1)) {
    setColor(red);
    drawString(CO, 42, 140,222);
    else{
    //continue program execution
    if(equal(move2,D2)) {
    setColor(red);
    drawString(CO, 42, 240,222);
    else{
    //continue program execution
    if(equal(move2,D3)) {
    setColor(red);
    drawString(CO, 42, 340,222);
    else{
    //continue program execution
    /*setBackgroundColor(azure);
    drawString(info, 150,50);
    //horizontal lines
    setColor(black);
    drawLine(100,100, 400,100);
    drawLine(100,101, 400,101);
    drawLine(100,141, 400,141);
    drawLine(100,142, 400,142);
    drawLine(100,182, 400,182);
    drawLine(100,183, 400,183);
    //verticle lines
    drawLine(200,60, 200,223);
    drawLine(201,60, 201,223);
    drawLine(300,60, 300,223);
    drawLine(301,60, 301,223);
    //code boxed
    drawString(a, 100,80);
    drawString(b, 100,120);
    drawString(c, 100,160);
    drawString(d, 100,200);
    drawString(one, 150,230);
    drawString(two, 250,230);
    */ drawString(three, 350,230);
    printLine("would you like to execute program further? Y/N");
    execute = readString();
    else{
    clearDrawing();
    String Fail = "User declined program execution...";
    drawString(Fail, 150,60);

    please format the code..
    RK

  • Powershell tic tac toe programming

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

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

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

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

  • Help in swing app. tic tac toe

    Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
    import java.awt.*; //import
    import javax.swing.*; //import
    import java.awt.event.*; //import
    import java.awt.Rectangle; //import
    import java.awt.Font; //import
    import javax.swing.BorderFactory; //import
    import javax.swing.border.TitledBorder; //import
    import java.awt.Color; //import
    public class TicTacToeFrame extends JFrame implements ActionListener {
        public TicTacToeFrame() {
            try { //try the following
                jbInit();
            } catch (Exception ex) { // exit on [X]
                ex.printStackTrace(); //exit and print errors
        int xWon = 0; //counting how many times O has won
        int oWon = 0; //counting how many times X has one
        double i = 0; // loop variable to determine turn
        public void actionPerformed(ActionEvent e) {
            String turn = "null"; //current turn
            String notTurn = "null"; //not current turn
            newGameBUT.setEnabled(false); //disable new game button
            if (i % 2 == 0) { // for determining who's turn it is
                turn = "X"; // X's turn when counter is even
                notTurn = "O"; //notTurn used to show who's turn it is in turnTF
            if (i % 2 != 0) { // for determining who's turn it is
                turn = "O"; // O's turn when counter is odd
                notTurn = "X"; //notTurn used to show who's turn it is in turnTF
            turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
    //horizontal, top, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqFour == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqTwo == "O") {
                    if (sqThree == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, o wins
            if (sqOne == "O") {
                if (sqFive == "O") { //checking too see if player O has won
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, o wins
            if (sqTwo == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqEight == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqSix == "O") {
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top right to bottom left, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
             $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    //horizontal, top, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFour == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqTwo == "X") {
                    if (sqThree == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, x wins
            if (sqTwo == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqEight == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqSix == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            // diagonal, top right to bottom left, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            String wins = turnTF.getText(); //Reading who won to print win winTF
            if (wins.equals("X wins!")) { //if X wins
                xWon++; //adding 1 to X's amount of wins
                String xWonString = Integer.toString(xWon); //converting to String
                xWinsTF.setText(xWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (wins.equals("O wins!")) { //if O wins
                oWon++; //adding 1 to O's amount of wins
                String oWonString = Integer.toString(oWon); //converting to String
                oWinsTF.setText(oWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (e.getSource() == newGameBUT) {
            i++; // turn switch
        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(null);
            this.getContentPane().setBackground(Color.darkGray);
            sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
            sqTwoBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
            sqFourBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
            sqFiveBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
            sqSixBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
            sqOneBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
            sqEightBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
            sqNineBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
            sqSevenBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.addActionListener(this);
            sqTwoBUT.addActionListener(this);
            sqThreeBUT.addActionListener(this);
            sqFourBUT.addActionListener(this);
            sqFiveBUT.addActionListener(this);
            sqSixBUT.addActionListener(this);
            sqSevenBUT.addActionListener(this);
            sqEightBUT.addActionListener(this);
            sqNineBUT.addActionListener(this);
            newGameBUT.addActionListener(this);
            sqThreeBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setEditable(false);
            turnTF.setText("X goes first");
            turnTF.setHorizontalAlignment(SwingConstants.CENTER);
            turnTF.setBounds(new Rectangle(2, 346, 346, 35));
            oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            oWinsTF.setEditable(false);
            oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
            xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            xWinsTF.setEditable(false);
            xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
            oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            oWinsLBL.setForeground(Color.white);
            oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsLBL.setText("O wins:");
            oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
            xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            xWinsLBL.setForeground(Color.white);
            xWinsLBL.setDisplayedMnemonic('0');
            xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsLBL.setText("X wins:");
            xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
            newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
            newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                                 Font.BOLD, 14));
            newGameBUT.setText("New Game");
            this.getContentPane().add(sqFourBUT);
            this.getContentPane().add(sqThreeBUT);
            this.getContentPane().add(sqTwoBUT);
            this.getContentPane().add(sqOneBUT);
            this.getContentPane().add(sqFiveBUT);
            this.getContentPane().add(sqSixBUT);
            this.getContentPane().add(sqNineBUT);
            this.getContentPane().add(sqEightBUT);
            this.getContentPane().add(sqSevenBUT);
            this.getContentPane().add(turnTF);
            this.getContentPane().add(xWinsLBL);
            this.getContentPane().add(xWinsTF);
            this.getContentPane().add(oWinsLBL);
            this.getContentPane().add(oWinsTF);
            this.getContentPane().add(newGameBUT);
            sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
        JButton sqTwoBUT = new JButton();
        JButton sqThreeBUT = new JButton();
        JButton sqFourBUT = new JButton();
        JButton sqFiveBUT = new JButton();
        JButton sqSixBUT = new JButton();
        JButton sqOneBUT = new JButton();
        JButton sqEightBUT = new JButton();
        JButton sqNineBUT = new JButton();
        JButton sqSevenBUT = new JButton();
        JTextField turnTF = new JTextField();
        JTextField oWinsTF = new JTextField();
        JTextField xWinsTF = new JTextField();
        JLabel oWinsLBL = new JLabel();
        JLabel xWinsLBL = new JLabel();
        JButton newGameBUT = new JButton();
    }

    This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner

  • Help with tic tac toe

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

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

Maybe you are looking for

  • When I send a text message to someone I am also getting the text to my phone. How can I stop this?

    When I send a text message to someone I am also getting the text to my phone. How can I stop this?

  • Solaris 10 on Newisys 4300 - Cannot see disks.

    Dear All, I am trying to install Solaris 10 on this machine but after going through the initial install screens (indentify host/network setup) it quits the install process complaining that no disks are found. The machine has an LSI Logic MegaRaid SCS

  • Page numbering difficulty!

    I have to write a lab report by tomorrow and my professor is very strict about how it should look. He wants the pages to be numbered such as: -1-, -2-, etc. on the bottom of each page (and not the cover sheet). But for some reason (maybe because I ju

  • Init ora file for 2000 server oracle

    i'm running 9.02 on windows 2000. How do i find out which init ora file the start services is picking up. I looked it up in the registry and it wasn't obvious. thanks

  • How to install BDE cluster without software

    In BDE 2.1, it is documented that you can create the guests for a cluster and let the distro management software (such as Ambari) install the cluster. We are looking to upgrade to 2.1, but currently on 2.0.  Is it possible to simply create the VM's a