我正在尝试开发Tic Tac Toe游戏,其中玩家1将点击一个按钮来放"X“,然后玩家2(计算机)将把"O”随机放到第一个step.For上的其他按钮,我需要创建一个介于0-8之间的随机数字,除了玩家1点击的那个。
我正在使用以下代码来生成随机数
Random random=new Random();
int number=random.nextInt(9);
发布于 2014-03-02 22:12:03
如果你想要从0到8的随机数,不包括一个值,那么实际上有8个可能的值,而不是9。所以生成一个从0到7的随机数- random.nextInt(8)
-如果结果大于或等于你排除的值,就加1。
发布于 2014-03-02 22:15:03
我会预先生成随机数列表,然后从中分配。例如:
// Initialize the list:
List<Integer> numbers;
public void init() {
numbers = new LinkedList<Integer>(9);
for (int i = 0; i < 9; ++i) {
numbers.add(i);
}
}
public int nextSelectNumber() {
int index = random.nextInt (numbers.size());
return numbers.get(index);
}
发布于 2014-03-02 22:26:30
除了玩家选择的最后一个之外,你不需要在0到8之间随机选择一个数字,你需要从你的选项列表中选择一个随机数字。这可能会有所不同,因为人类和计算机会选择不同的(随机?)数字。这并不像其他人已经回答的那么容易。一个选项可以是使用作业的List<Integer>
来保存要选择的当前选项。基于@Mureinik's answer中提供的代码
class TicTacToeCells {
private static final int MAX_CELLS = 9;
private List<Integer> cells;
private Random random;
public void init() {
random = new Random();
cells = new ArrayList<Integer>(MAX_CELLS);
for (int i = 0; i < MAX_CELLS; ++i) {
numbers.add(i);
}
}
//for human moves
public boolean canPickCell(int cellToPick) {
return cells.contains(cellToPick);
}
public int pickCellByComputer() {
int index = random.nextInt(cells.size());
return cells.get(index);
}
public void pickCell(int cellToPick) {
cells.remove(cellToPick);
//further logic to display the move or something else...
}
}
https://stackoverflow.com/questions/22128634
复制相似问题