我想尝试评估游戏以下井字游戏中的获胜状态。评估井字游戏的获胜状态
所以我最终会做通常试图使用上的按钮getText()
方法在for循环和评估,例如,如果cells[0][i].getText()
等于cells[0][1]
和cells[0][2]
。
然后我看看cells[0][2]
是不是空白(所以不等于" "
),那么这将完成第一行。
问题是,这是行不通的,如果有人为我提供了一种更好的替代方法,如果有的话,我将不胜感激。
package tictactoe;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TicTacToe implements ActionListener
{
JFrame window;
static JButton[][]cells=new JButton[3][3];
boolean playing;
char turn='X';
public TicTacToe()
{
//SETS UP THE WINDOW
window=new JFrame("TicTacToe");
window.setSize(new Dimension(400,400));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
//**********************//
createCells();
window.setVisible(true);
}
public static void main(String[] args)
{
new TicTacToe();
}
private void createCells()
{
window.setLayout(new GridLayout(3,3));
for(int i=0;i<cells.length;i++)
{
for(int j=0;j<cells.length;j++)
{
cells[i][j]=new JButton();
cells[i][j].addActionListener(this);
window.add(cells[i][j]);
}
}
}
@Override
public void actionPerformed(ActionEvent e)
{
playing=true;
JButton _buttonPressed=(JButton)e.getSource();
while(playing)
{
if(turn=='X')
{
_buttonPressed.setText("X");
_buttonPressed.setEnabled(false);
turn='O';
}
else
{
_buttonPressed.setText("O");
_buttonPressed.setEnabled(false);
}
}
}
}
你试过步骤虽然使用调试器程序? –