2013-10-15 30 views
0

我正在开发一个针对android的tic tac toe游戏。用户将与电脑对战。我完成了大部分的比赛,但只是停留在最后一个问题上。我尝试了很多,但找不到合适的随机方法来选择一个空的随机方块。 这是我宣布我的9个按钮的方式。随机方法tic tac toe android

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); 

请帮帮我。提前致谢!

+1

难道你不想要的电脑玩家通过游戏逻辑来打,而不是随机选择一个空方? –

+0

@ Dr.Avalanche我只是一个14岁的孩子。我已经编程了逻辑,但是第一步我想让电脑选择一个随机方位。请帮助我! –

回答

1

将您的按钮放入列表中,生成一个随机数字,并从列表中获取所选数字的按钮。

+0

但是,如果该按钮已被选中,该怎么办?请帮忙! –

+0

您只需从列表中删除该按钮 - 注意随机生成器也是为了避免IndexOutOfBounds异常! – Ezzored

1

为了避免选择一个已经被选中的按钮,你可以组成一个大小为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; 
} 
} 

编辑:我忘了提及:把所有的按钮放在一个数组中。所产生的数的方法是在阵列细胞

`

+0

谢谢!我一定会尝试。 –

1

我建议从状态视图分离。

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; 
}