我想嘗試評估遊戲以下井字遊戲中的獲勝狀態。評估井字遊戲的獲勝狀態
所以我最終會做通常試圖使用上的按鈕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);
}
}
}
}
你試過步驟雖然使用調試器程序? –