import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class TicTac implements ActionListener { public TicTac(){ window.setSize(150,150); window.setLayout(new GridLayout(3,3)); // display the buttons, smaller code with loop for(int i=0; i<=8; i++){ buttons[i] = new JButton(); window.add(buttons[i]); buttons[i].addActionListener(this); } //show the window window.setVisible(true); } private JFrame window = new JFrame("Noughts & Crossess"); private int count = -1; private int[][] winner = new int[][] { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6} }; private JButton buttons[] = new JButton[9]; private String player = ""; private boolean clicked[] = new boolean[10] ; private boolean won = false; public void actionPerformed(ActionEvent game) { for( int i = 0; i < clicked.length; i++ ) clicked[i] = false ; count++; // PC or Human's go if(count % 2 == 0){ player = "O"; JButton pressedButton = (JButton)game.getSource(); pressedButton.setText(player); pressedButton.setEnabled(false); } else { Random generator = new Random(); player = "X"; int cpuclick; do { cpuclick = generator.nextInt(9); } while(!buttons[cpuclick].isEnabled()); //isEnabled http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html#isEnabled() //this line checks if the button has already been clicked by the computer or human player { buttons[cpuclick].setText(player); buttons[cpuclick].setEnabled(false); } } // Is there a winner? for(int i=0; i<=7; i++){ if( buttons[winner[i][0]].getText().equals(buttons[winner[i][1]].getText()) && buttons[winner[i][1]].getText().equals(buttons[winner[i][2]].getText()) && buttons[winner[i][0]].getText() != ""){ won = true; } } // if there is a winner display who one and close if(won == true){ JOptionPane.showMessageDialog(null, player + " wins the game!"); System.exit(0); } else if(count == 9 && won == false){ JOptionPane.showMessageDialog(null, "The game was tie!"); System.exit(0); } } //open TicTac public static void main(String[] args){ new TicTac(); } }
Copy of code hosted at http://pastie.org/688030
Code saved as TicTac.java
Place your comment