我正在制作一个模拟游戏,游戏中有涂鸦虫和蚂蚁,随着模拟的进行,涂鸦虫试图吃掉蚂蚁。我遇到的问题是初始化我创建的2d数组。我需要100只蚂蚁和5只涂鸦虫随机地放在网格上。我已经把网格随机化了,但是作为一个整体,我得到了随机数量的蚂蚁和涂鸦虫。我也在处理一个更小的数组任何帮助都将不胜感激。
Random rand = new Random();
int[][] cells = new int[10][10];
public void display() {
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
cells[i][j] = (int) (Math.random()*3);
if(cells[i][j] == 2) { // 2 = ants;
cells[i][j] = 4;
}
if(cells[i][j] == 1) { // 1 = doodlebugs
cells[i][j] = 3;
}
if(cells[i][j] == 0) {
cells[i][j] = 0;
}
System.out.print(cells[i][j]);
}
System.out.println();
}
}发布于 2018-03-12 18:14:01
一个简单的方法是创建一个for循环,循环次数与您想要的最大次数相同(在本例中是蚂蚁和涂鸦虫)。在for循环的每一次迭代中,您都可以生成事物的随机坐标。这相当于两个循环,一个用于蚂蚁,另一个用于涂鸦。
for (int i = 0; i < desiredNumOfAnts; i++)
{
int randX = rand.nextInt(cells[i].length); // this generates a random X coordinate, up to the length of the current row
int randY = rand.nextInt(cells.length); // this generates a random Y coordinate, according to the height of the array
/* using these coordinates, insert a new ant into the cells */
}看看你能不能自己弄明白怎么做剩下的事!
https://stackoverflow.com/questions/49241538
复制相似问题