1

I'm a beginner of learning Java programming and I'm doing the game of tic tac toe.

When I finish my game, I can't continue to play the game, because the program will exit. What should I add to this code. Since I don't use the paint method, repaint () can't be used.

import java.awt.*;  
import java.awt.event.*;
import javax.swing.*;

public class TicTacToeV1 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 = "";
    public static int count = 0;
    public TicTacToeV1(){           
        /*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);

        String input = JOptionPane.showInputDialog("Please select ur pawn: \n1) X\n2) O");
        int pawn = Integer.parseInt(input);
        if ( input.equals("2")){
              setCount(1);
        }
    }

    public static void setCount (int co){
        count = co;            
    }

    public void actionPerformed(ActionEvent a) {    
        count++;

        /*Calculate Who's Turn It Is*/
        if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9|| count == 11){
            letter = "X";

        } else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
            letter = "O";
        }

        /*Display X's or O's on the buttons*/
        if(a.getSource() == button1){
            button1.setText(letter);
            button1.setEnabled(false);
        } else if(a.getSource() == button2){
            button2.setText(letter);
            button2.setEnabled(false);
        } else if(a.getSource() == button3){
            button3.setText(letter);
            button3.setEnabled(false);
        } else if(a.getSource() == button4){
             button4.setText(letter);
             button4.setEnabled(false);
        } else if(a.getSource() == button5){
             button5.setText(letter);
             button5.setEnabled(false);
        } else if(a.getSource() == button6){
             button6.setText(letter);
             button6.setEnabled(false);
        } else if(a.getSource() == button7){
             button7.setText(letter);
             button7.setEnabled(false);
        } else if(a.getSource() == button8){
             button8.setText(letter);
             button8.setEnabled(false);
        } else if(a.getSource() == button9){
             button9.setText(letter);
             button9.setEnabled(false);
        }       
    }

    public static void main(String[] args){           
            new TicTacToeV1();
    }
}
user unknown
  • 35,537
  • 11
  • 75
  • 121
user1403675
  • 49
  • 4
  • 9
  • 2
    Give it a `reset()` method where you reset the state of your program, and call this from a resetButton's ActionListener. – Hovercraft Full Of Eels Jun 09 '12 at 14:24
  • 2
    You really should look into two dimensional arrays here - would simplify the code by far and also make the `reset` method Hovercraft proposes simpler. Also while some space is generally considered a good idea one can overdo it. – Voo Jun 09 '12 at 14:25
  • 2
    Notes 1+2: If you put an empty line after every line, it doesn't serve in structuring the output. 2: If you name variables jb1, jb2 and so on, you're using crippled arrays without all their benefits. – user unknown Jun 09 '12 at 15:03

2 Answers2

1

Create a method called reset (or something of the like) and make it do the following:

  1. Reset each text value.
  2. Reset count to 0.

You may want to make an array [] (or 2D array if you know how to >> [][]) for the buttons as well as its easier to manage. This allows for better management of many buttons and removes alot of useless repetition your current code has.

Example code:

public static void reset() {
    button1.setText("");
    button1.setEnabled(true);
    //etc...
    count = 0;
}

Then just call reset() when the game ends (you may want to also make it check who has won).

Hope this helps and DFTBA. :)

Jason S
  • 61
  • 6
1

a) Your whole code fits into 50 lines. b) You don't have a method to detect the winner or a finished game, so I just added the code after count == 9.

import java.awt.*;  
import java.awt.event.*;
import javax.swing.*;

public class TicTacToeV1 extends JFrame implements ActionListener {
    private JButton [] button  = new JButton [9];
    private int count = 0;

    public TicTacToeV1 () {           
        super ("Tic-Tac-Toe");
        setSize (300, 300);
        setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setLayout (new GridLayout (3, 3));
        init ();
    }

    private void init () {           
        count = 0;
        for (int i = 0; i < 9; ++i) {
            button [i] = new JButton ("");
            button [i].addActionListener (this);
            add (button [i]);
        }
        setVisible (true);
    }

    public void actionPerformed (ActionEvent a) {    
        String letter = (++count % 2 == 1) ? "X" : "O";
        /*Display X's or O's on the buttons*/
        for (JButton jb : button) 
        if (a.getSource () == jb) {
            jb.setText (letter);
            jb.setEnabled (false);
        }
        if (count == 9) {
            for (JButton jb : button) 
                remove (jb) ;
            init ();
        }
    }

    public static void main (String [] args) {           
        new TicTacToeV1 ();
    }
}

I put the variable part into it's own method (init), and call it from the Ctor or from the end-of-game method.

Of course you could call a new Ctor from there too. Or just reset the button state and counter. There are many ways to Rome. While it shouldn't play a role, avoiding 100 ended games in memory with all their buttons might save 10kb of memory or so.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • This is a very common CS course problem (its prob. homework). Fixing his entire method so that he can just copy and paste, won't make him a better programmer. – mawburn Jun 09 '12 at 17:09
  • 1
    @MadBurn: Yes, but newcomers usually get problems in initialization of arrays of nonprimitives, confuse the an array for 9 buttons with the 9 button themselfes, get NPEs therefore, so I made a working solution without a meaningful new-game-detection. user1403675 may look at it, and try to write the same thing without looking again, or cut-and-paste; that's his choice. He has some unused code to select which symbol the first player uses, and needs to do something to make it work although. – user unknown Jun 09 '12 at 23:13