我有一个Tic Tac Toe 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);
}
发布于 2020-11-24 17:03:17
由于计算机应该在用户完成其操作后立即移动,我相信您可以将其绑定到相同的事件。这样,每当用户选择自己的位置时,他就会触发计算机移动。
您可以选择在这两个操作之间添加一个较短的延迟。
public void actionPerformed(ActionEvent e) {
if(((JButton)e.getSource()).getText().equals("") && isWinner == false) {
button.setText(currentPlayer);
crossesCount += 1;
hasWinner();
// optional short delay
computersMove();
circlesCount += 1;
hasWinner();
}
}
https://stackoverflow.com/questions/64990840
复制相似问题