import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CSE141HW5 implements ActionListener
{
public static void main (String[] args)
{
new CSE141HW5();
}
/* Instance Variables */
private JFrame gameWindow = new JFrame ("Tic-Tac-Toe");
private int [][] winningCombinations = 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 int count = 0;
private String mark = "";
private boolean win = false;
public CSE141HW5()
{
/* Creating gameWindow */
Container con = gameWindow.getContentPane();
con.setBackground(Color.WHITE);
gameWindow.setVisible (true);
gameWindow.setSize (220,220);
gameWindow.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
gameWindow.setLayout (new GridLayout (3, 3));
gameWindow.setLocation (830, 400);
gameWindow.setBackground(Color.WHITE);
/* Adding Buttons */
for (int i = 0; i <= 8; i++)
{
buttons[i] = new JButton ();
gameWindow.add (buttons [i]);
buttons[i].addActionListener (this);
buttons[i].setBackground(Color.WHITE);
}
}
/* When an object clicked... */
public void actionPerformed (ActionEvent click)
{
JButton pressedButton = (JButton)click.getSource();
/* Whose turn? */
if ((count % 2) == 0)
{
mark = "O";
pressedButton.setBackground(Color.CYAN);
}
else
{
mark = "X";
pressedButton.setBackground(Color.yellow);
}
/* Write the letter to the button and deactivate it */
pressedButton.setText (mark);
pressedButton.setEnabled (false);
/* Determining that who won */
for (int i = 0; i <= 7; i++)
{
if (buttons[winningCombinations[i][0]].getText().equals(buttons[winningCombinations[i][1]].getText())
&& buttons[winningCombinations[i][1]].getText().equals(buttons[winningCombinations[i][2]].getText())
&& buttons[winningCombinations[i][0]].getText() != "") win = true;
}
/* Ending Dialog */
if (win == true)
{
byte response = (byte) (JOptionPane.showConfirmDialog(null, mark + " won!\nPlay again?", "Homework 5", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE));
if (response == 0) new CSE141HW5();
else System.exit(0);
}
else if (count == 8 && win == false)
{
byte response = (byte) (JOptionPane.showConfirmDialog(null, "Draw!\nPlay again?", "Homework 5", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE));
if (response == 0) new CSE141HW5();
else System.exit(0);
}
count++;
}
}
I am a newbie on programming and have coded a tic-tac-toe game on java. I want to improve this program but there are things that i couldn't handle.
I have changed buttons colors with default colors, like Color.yellow etc. How can i use more detailed color?
When game overs, program asks for re-play. If user selects Yes, then new game window appears, but old window still remains, which i didn't like. I want that old windows to be closed, but couldn't find how to implement it.
If you find any code on my program, which you think unnecessary or if you think that there is a better way than what i do, please tell me. So i can learn.