【发布时间】:2014-05-21 18:06:47
【问题描述】:
如何为我的井字游戏设定获胜条件?我还需要做到这一点,当玩家完成时,它会询问他们是否想再玩一次。如果你想出办法,你能告诉我为什么会这样。这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class game extends JFrame{
JFrame gameWindow = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private String mark = "";
private int count = 0;
public static void main(String[] args){
new game();
}
public game(){
HandlerClass handler = new HandlerClass();
// Sets buttons on the screen
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(mark);
buttons[i].addActionListener(handler);
gameWindow.add(buttons[i]);
}
// Sets the looks of the window
gameWindow.setLayout(new GridLayout(3,3));
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.setSize(300,300);
gameWindow.setVisible(true);
}
private class HandlerClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
JButton click = (JButton) event.getSource();
if(count % 2 == 0){
mark = "X";
click.setBackground(Color.YELLOW);
}else{
mark = "O";
click.setBackground(Color.CYAN);
}
click.setText(mark);
click.setEnabled(false);
System.out.println(count + "\n" + (count % 2));
count++;
}
}
}
【问题讨论】:
-
您如何跟踪所有 X 和 Os 的放置位置?
-
你必须遍历你的按钮。如果按钮位于二维 [3][3] 数组中,则可能更容易实现和理解逻辑。
-
@jschabs 这是用
click.setText(mark)完成的,混合模型和视图....
标签: java arrays swing tic-tac-toe