【发布时间】:2021-03-07 11:48:12
【问题描述】:
我有一个井字游戏 GUI,可让用户与计算机对战。我使用 actionListener 来接收用户鼠标点击他们想要在板上放置“X”的位置。 我遇到的问题是,我的代码设置方式,只要计算机在放置它们之前转动,我的 GUI 就会等待鼠标点击。换句话说,用户首先将他们的“X”块放在他们想要的任何地方。用户走后,用户必须点击棋盘上的空棋子来模拟电脑转动,即模拟电脑放下“O”棋子。 我的目标是尝试让计算机的棋子自动出现在棋盘上,而无需用户单击空白棋子来模拟计算机的运动。这是我使用 ActionListener 初始化板的代码:
private void initializeBoard() {
Font f1 = new Font(Font.DIALOG, Font.BOLD, 100);
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
JButton button = new JButton();
gameBoard[i][j] = button;
button.setFont(f1);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(((JButton)e.getSource()).getText().equals("") && isWinner == false) {
if(isPlayersMove) //players turn to make a move
{
button.setText(currentPlayer);
isPlayersMove = false;
crossesCount += 1;
}
else //computers turn to make a move
{
computersMove();
circlesCount += 1;
isPlayersMove = true;
}
hasWinner();
}
}
});
pane.add(button);
}
}
}
这是计算机如何确定放置一块的代码(目前是随机的):
// Choose a random number between 0-2
private int getMove() {
Random rand = new Random();
int x = rand.nextInt(3);
return x;
}
/*
* Decision making for the computer. Currently, the computer
* chooses a piece on the board that is empty based on a random
* value (0-2) for the row and column
*/
public void computersMove() {
int row = getMove(), col = getMove();
while(gameBoard[row][col].getText().equals("x") || //if space is occupied, choose new spot
gameBoard[row][col].getText().equals("o"))
{
row = getMove();
col = getMove();
}
gameBoard[row][col].setText(computerPlayer);
}
【问题讨论】:
-
也许让计算机在您希望计算机选择的按钮上调用
doClick()方法?
标签: java swing awt jbutton actionlistener