gpt4 book ai didi

java - Tic Tac Toe 游戏 - 数组没有保存值(value)?

转载 作者:行者123 更新时间:2023-11-30 07:44:05 24 4
gpt4 key购买 nike

我正在创建一个 Tic Tac Toe 游戏(带有 GUI),并且使用 2D 数组来确定获胜者。我发现当用户单击板上的某个位置后,数组不会保存以前的值。

所以如果 board[0][0] 是“X”,则数组是

[[X, 2, 3], [4, 5, 6], [7, 8, 9]]

之后,如果用户点击 board[1][1],则数组应为:

[[X, 2, 3], [4, X, 6], [7, 8, 9]]

但它是:

[[1, 2, 3], [4, X, 6], [7, 8, 9]]

为什么会发生这种情况?

这是代码:

private class Play implements ActionListener{
public void actionPerformed(ActionEvent event){
JButton src = (JButton) event.getSource();

//create board
String[][] board = { {"1","2","3"},
{"4","5","6"},
{"7","8","9"}
};
// who's turn?
count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9 )
letter = playerChoice;
else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
letter = computerChoice;


//player choice - show button
if(src.equals(one)){
one.setText(letter);
one.setEnabled(false);
board[0][0]= letter;
}else if(src.equals(two)){
two.setText(letter);
two.setEnabled(false);
board[0][1] = letter;
}else if(src.equals(three)){
three.setText(letter);
three.setEnabled(false);
board[0][2] = letter;
}else if(src.equals(four)){
four.setText(letter);
four.setEnabled(false);
board[1][0] = letter;
}else if(src.equals(five)){
five.setText(letter);
five.setEnabled(false);
board[1][1] = letter;
}else if(src.equals(six)){
six.setText(letter);
six.setEnabled(false);
board[1][2] = letter;
}else if(src.equals(seven)){
seven.setText(letter);
seven.setEnabled(false);
board[2][0] = letter;
}else if(src.equals(eight)){
eight.setText(letter);
eight.setEnabled(false);
board[2][1] = letter;
}else if(src.equals(nine)){
nine.setText(letter);
nine.setEnabled(false);
board[2][2] = letter;
}


System.out.println(Arrays.deepToString(board));

最佳答案

每次调用 actionPerformed 时,您都会创建一个新的局部变量 board...

private class Play implements ActionListener {

public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();

//create board
String[][] board = {{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
//...

这意味着状态在调用之间永远不会保存,而是在每次调用时重新创建。

相反,board 应该是一个实例字段,例如...

private class Play implements ActionListener {

private String[][] board = {{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};

public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();

count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9 )
letter = playerChoice;
else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
letter = computerChoice;
//...

关于java - Tic Tac Toe 游戏 - 数组没有保存值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34169016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com