import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Tix extends JFrame {
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
private boolean xTurn = true;
private Font style;
private static JButton[][] btns = new JButton[3][3];
public Tix() {
setTitle("Tix");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
createContents();
setVisible(true);
}
public void createContents() {
style = new Font("Comic Sans", 1, 100);
Listener listener = new Listener();
setLayout(new GridLayout(3,3));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
btns[i][j] = new JButton();
btns[i][j].setFont(style);
btns[i][j].addActionListener(listener);
add(btns[i][j]);
}
}
}
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if (xTurn)
btn.setForeground(Color.RED);
else
btn.setForeground(Color.BLUE);
if (btn.getText().isEmpty()) {
btn.setText(xTurn ? "X" : "O");
if (win()) {
JOptionPane.showMessageDialog(null, "Congratulations! Player " + (xTurn ? "X" : "O") + " wins!");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
btns[i][j].setText(null);
}
}
xTurn = true;
}
else {
xTurn = !xTurn;
}
}
else {
JOptionPane.showMessageDialog(null,"Cell already clicked!");
}
}
}
public static boolean win() {
for (int i = 0; i < 3; i++)
if (btns[i][0].equals("X") && btns[i][1].equals("X") && btns[i][2].equals("X"))
return true;
for (int j = 0; j < 3; j++)
if (btns[0][j].equals("X") && btns[1][j].equals("X") && btns[2][j].equals("X"))
return true;
if (btns[0][0].equals("X") && btns[1][1].equals("X") && btns[2][2].equals("X"))
return true;
if (btns[0][2].equals("X") && btns[1][1].equals("X") && btns[2][0].equals("X"))
return true;
return false;
}
public static void main(String[] args) {
new Tix();
}
}
用于检查行的for循环。 用于检查列的for循环。 用于检查对角线的两个if语句。
win方法根本不会返回true。 &amp;&amp; amp;有什么问题吗?运营商?
答案 0 :(得分:5)
- (NSDate *)weekOfDate:(NSDate *)originalDate
{
NSCalendar *currentCal = [NSCalendar currentCalendar];
[currentCal setFirstWeekday:2]; // Sun = 1, Mon = 2, etc.
NSDateComponents *weekdayComponents = [currentCal components:NSCalendarUnitWeekday fromDate:originalDate];
// Calculate the number of days to subtract and create NSDateComponents with them.
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
NSInteger daysToSubtract = (([weekdayComponents weekday] - [currentCal firstWeekday]) + 7) % 7;
[componentsToSubtract setDay:-1 * daysToSubtract];
return [currentCal dateByAddingComponents:componentsToSubtract toDate:originalDate options:0];
}
是btns[i][j]
所以它永远不会等于一个字符串。
您应该使用JButton
等内容替换btns[i][0].equals("X")
形式的每个方法调用。
除此之外,您的btns[i][0].getText().equals("X")
方法仅检查“X”玩家是否获胜。那个“O”球员怎么样?