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++;
}
}
我是一名編程新手,並且在java上編寫了一個tic-tac-toe遊戲。我想改善這個計劃,但有些事我無法處理。來自新手的幾個問題
我改變了默認顏色的按鈕顏色,如Color.ellow等。我如何使用更詳細的顏色?
當遊戲結束時,程序要求重新玩。如果用戶選擇是,那麼會出現新的遊戲窗口,但舊窗口仍然存在,我不喜歡。我想要關閉舊窗口,但無法找到如何實現它。
如果您發現我的程序中有任何代碼,您認爲這些代碼不必要,或者您認爲有比我更好的方法,請告訴我。所以我可以學習。