CIS 162[M] Laboratory Activity #08:
Tic-Tac-Toe

2009:October:26(Mon)

Write a basic implementation of Tic-Tac-Toe as follows:
  1. Create a class named "TicTacToe".
  2. Copy into your TicTacToe.java document the material of BasicComponents.java — except change occurrences of the name "BasicComponents" to "TicTacToe".
  3. Get rid of the code for the text-field tf and the JLabel.
  4. Change the code so there are nine buttons instead of only three.  (Using an array or ArrayList for this may be good, but it's actually not necessary.) 
  5. Change the code to use appropriate numbers for the GridLayout.
  6. Write a method called won() which checks whether buttons' texts are equal and not empty ("") across any row, column, or diagonal.
  7. Then, do the following in actionPerformed():
    1. Disable the clicked button, and set its text to "X".
    2. Invoke won(), and if it indicates that some player (who should be "X" at this point) won, then use JOptionPane.showMessageDialog() to tell the user something like, "Congratulations, you won!", and stop.
    3. Otherwise, create an ArrayList to contain JButtons; and add each button that is still enabled to this ArrayList.
    4. Then, if that ArrayList is empty, use JOptionPane.showMessageDialog() to tell the user something like, "Sorry, it's a cat's game."
    5. Otherwise, if it isn't a cat's game, use Random.nextInt() to choose an element of that ArrayList randomly.
    6. Then, disable that randomly chosen button, and set its text to "O".
    7. Then, invoke won(), and if it indicates that some player (who should be "O" at this point) won, then use JOptionPane.showMessageDialog() to tell the user something like, "The computer won; better luck next time."
  8. Make other little changes as appropriate.

Submission

Submit the following:



(Copyright © 2009 by Hugh McGuire   -- for thoughts about this, see   http://www.csis.gvsu.edu/~mcguire/teaching/copyright_thoughts.html .)