Случайный метод крестики-нолики андроид

Я разрабатываю игру крестики-нолики для Android. Пользователь будет играть против компьютера. Я почти закончил игру, но просто застрял на этой последней проблеме. Я много пробовал, но не смог найти подходящего случайного метода для выбора случайного пустого квадрата. Вот как я объявил свои 9 кнопок.

    btn00 = (Button) findViewById(R.id.button);
    btn01 = (Button) findViewById(R.id.button2);
    btn01 = (Button) findViewById(R.id.button3);
    btn10 = (Button) findViewById(R.id.button4);
    btn11 = (Button) findViewById(R.id.button5);
    btn12 = (Button) findViewById(R.id.button6);
    btn20 = (Button) findViewById(R.id.button7);
    btn21 = (Button) findViewById(R.id.button8);
    btn22 = (Button) findViewById(R.id.button9);

Пожалуйста, помогите мне. Заранее спасибо!


person Chinmay Dabke    schedule 15.10.2013    source источник
comment
Разве вы не хотели бы, чтобы компьютерный игрок играл по логике игры, а не выбирал наугад пустую клетку?   -  person Dr.Avalanche    schedule 15.10.2013
comment
@Dr.Avalanche Мне всего лишь 14 лет. Я уже запрограммировал логику, но для первого хода я хочу, чтобы компьютер выбрал случайный квадрат. Пожалуйста, помогите мне!   -  person Chinmay Dabke    schedule 15.10.2013


Ответы (3)


Поместите свои кнопки в список, сгенерируйте случайное число и получите кнопку с выбранным номером из списка.

person Ezzored    schedule 15.10.2013
comment
Вы просто удаляете эту кнопку из списка — следите за генератором случайных чисел, чтобы избежать исключений IndexOutOfBounds! - person Ezzored; 15.10.2013

чтобы избежать выбора кнопки, которая уже была выбрана, вы можете сформировать массив размером 9, выбрать случайное число и удалить его. вот пример:`

/**
 * RandomArray is a data structure similiar to a set, which removes a random number one at a time and decreases the size of the set by one.
 */
public class RandomArray {
    int size;
    int[] array;

/**
 * The only constructor for this class. assigns numbers from 1 to m in the 0 to m-1 cells respectively. 
 * @param size holds the value of m - meaning, the method will generate a number for each movie.
 */
public RandomArray(int size) {
    this.size = size;
    array = new int[size];
    for (int i = 0; i<size; i++) {
        array[i] = i+1;
    }
}

/**
 * remove removes a number randomly and returns it.
 * with each removal the number in the last cell replaces the removed number and size is decreased by one.
 * @return a random number represents a movie that hasn't been played yet.
 */
public int remove() {
    int ans = -1;
    if (size > 0) {
        // generating a random number from 0 to the last cell. 
        int randomNum = (int)(Math.random()*size);
        ans = array[randomNum];
        // last number replaces the number to be removed.
        array[randomNum] = array[size-1];
        size--;
    }
    return ans;
}
}

РЕДАКТИРОВАТЬ: я забыл упомянуть: поместите все ваши кнопки в массив. таким образом, сгенерированное число является ячейкой массива

`

person Tom    schedule 15.10.2013
comment
Спасибо! Я обязательно попробую это. - person Chinmay Dabke; 15.10.2013

Рекомендую отделить представление от состояния.

int[] state = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0 }; // int[9] 
Button[] buttons = new Button[] { 
   (Button) findViewById(R.id.button),
   (Button) findViewById(R.id.button2),
   (Button) findViewById(R.id.button3),
   ...
}

Затем попробуйте найти пустую ячейку, используя состояние:

Random rnd = new Random();
int index = rnd.nextInt(state.length);
while(state[index] != 0) {
    index = rnd.nextInt(state.length);
}

Установите состояние:

state[index] = 1;

Затем обновите кнопку:

Button b = buttons[index];
b.set....();
...

То же самое относится к вашим кнопкам, когда пользователь нажимает на них, используйте эту функцию в onClick() для определения индекса:

int getIndex(Button b) {
   for(int i = 0; i < buttons.length; i++) {
      if(buttons[i].equals(b)) {
         return i;
      }
   }
   return -1;
}
person gaborsch    schedule 15.10.2013