Merlin
Merlin

Reputation: 185

How to find all empty buttons and select one by random?

I have written a piece of code below where if there are any empty buttons, then the first empty button it finds mark it with an 'O'. I want to advance this. I want to be able to iterate through all of the empty buttons and out of those select one by random to set its text as O.

   private boolean computerMove() {
        String[][] field = new String[3][3];

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                field[i][j] = buttons[i][j].getText().toString();
                if (field[i][j].equals("")) {
                    buttons[i][j].setText("O");
                    buttons[i][j].setTextColor(playerO);
                    turnsCount++;
                    return true;
                }
            }
        }
        return false;
    }

Upvotes: 0

Views: 75

Answers (1)

assylias
assylias

Reputation: 328618

  1. Create a List<Button> emptyButtons containing all the empty buttons.
  2. Select a button randomly.
  3. Set the button to "O".

In other words:

Random r = new Random(); //you may want to declare this as a class field

List<Button> emptyButtons = new ArrayList<> ();

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
    String s = buttons[i][j].getText().toString();
    if (s.isEmpty()) emptyButtons.add(buttons[i][j]);
  }
}

Button b = emptyButtons.get(r.nextInt(emptyButtons.size());
b.setText("O");
b.setTextColor(player));

Upvotes: 1

Related Questions