我正在制作一个模拟游戏,其中有涂鸦虫和 Ant ,随着模拟的进行,涂鸦虫试图吃掉 Ant 。我遇到的问题是初始化我创建的二维数组。我需要将 100 只 Ant 和 5 只涂鸦虫随机放置在网格上。我已经随机化了网格,但只是作为一个整体,所以我得到了随机数量的 Ant 和涂鸦虫。我还在使用一个较小的数组,直到我得到这个工作。任何帮助将非常感激。
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();
}
}
最佳答案
你创建了一个10x10的数组,这意味着它有100个位置,这意味着所有位置都应该被 Ant 占据? (因为您告诉过您需要 100 只 Ant - 除非同一位置可以有超过 1 只昆虫)。
<小时/>无论如何,我认为你正在做一个“逆”逻辑。思考什么应该是随机的,什么不应该是随机的。您循环整个数组并调用random()
来了解每个位置必须放置什么昆虫,因此您无法控制将创建每种昆虫的数量。
如果您需要 Ant 和 doodlebug 的确切数量,这些是固定的 - 您不需要调用 random()
来知道它是 Ant 还是 dooblebug,您已经知道需要多少个。必须随机的是它们的位置,因此您应该调用random()
来获取行和列位置,而不是昆虫类型。
首先,我会创建一些类来代表昆虫和细胞:
// enum type, better than "magic numbers"
public enum Insect {
ANT,
DOODLEBUG;
}
public class Cell {
// the insect placed in this cell
private Insect insect;
public Cell() {
// cell starts without any insect
this.insect = null;
}
public Insect getInsect() {
return insect;
}
public void setInsect(Insect insect) {
this.insect = insect;
}
// check if cell already has an insect
public boolean isOccupied() {
return this.insect != null;
}
}
然后我初始化板:
int size = 10; // assuming a square
Cell[][] cells = new Cell[size][size];
// fill with empty cells
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
cells[i][j] = new Cell();
}
}
然后我用昆虫填充它:
// how many ants? Just an example, change the value according to your needs
int nAnts = 8;
// how many doodlebugs? Just an example, change the value according to your needs
int nBugs = 2;
Random rand = new Random();
// place the ants
for (int i = 0; i < nAnts; i++) {
int row, column;
// get a random position that's not occupied
do {
row = rand.nextInt(size);
column = rand.nextInt(size);
} while (cells[row][column].isOccupied());
// fill with ant
cells[row][column].setInsect(Insect.ANT);
}
// place the doodlebugs
for (int i = 0; i < nBugs; i++) {
int row, column;
// get a random position that's not occupied
do {
row = rand.nextInt(size);
column = rand.nextInt(size);
} while (cells[row][column].isOccupied());
// fill with doodlebug
cells[row][column].setInsect(Insect.DOODLEBUG);
}
放置昆虫的 for
循环有点重复,因此您也可以将它们重构为方法。
我还假设 cells
是一个正方形,但如果不是,只需为行数和列数创建 2 个变量,并相应地更改代码 - 但逻辑是相同的。
关于java - 在Java中,如何使用特定数量的随机值初始化二维数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241538/