如何随机选择一个 java 按钮,我正在尝试创建一个用户玩 cpu 或其他玩家的井字游戏。我让它适用于 2 名玩家,但卡在 1 名玩家游戏中,我不知道是否可以完成,但我的想法是我只是随机选择一个按钮进行 cpu 检查以查看它之前是否被选中,然后分配将 x 或 o 分配到选定的正方形。
public void buttonSelected(ActionEvent click) {
Object source = click.getSource();
// loop through to see which button has been selected
if(onePlayer){
// User Vs CPU
/*if((turn % 2 == 0)){// CPU Turn
int selected;
do {
selected = new Random().nextInt(btnEmpty.length );
if (chosen[selected -1] == false){
chosen[selected -1] = true;
}
}while (chosen[selected -1] == true);
source = Integer.valueOf(selected);
for(int i=1; i<= btnNotSelected.length; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert appropriate x or y
btnNotSelected[i].setText("X");
btnNotSelected[i].setEnabled(false); // disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
}
}
}
else{ //User Turn
for(int i=1; i<=9; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert O
btnNotSelected[i].setText("O");
btnNotSelected[i].setEnabled(false);
chosen[i] = true;// disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
}
}
} */
turn++;
}
else if(twoPlayer){
for(int i=1; i<=9; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert appropriate x or y
if(turn % 2 == 0){
btnNotSelected[i].setText("X");
}
else{
btnNotSelected[i].setText("O");
}
btnNotSelected[i].setEnabled(false); // disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
turn++;
}`