我有这段代码可以在Java游戏中生成“树”。它可以工作并生成一棵“树”。我决定制作一个最多30个随机数生成器,该生成器会生成许多“树”。但是,当我运行代码时,没有任何错误,但是“树”没有生成。生成算法可以在下面找到。
private void generateLevel() {
int dungeonCoord = dungeonSpawn.nextInt(height * width);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tiles[x + y * width] = Tile.GRASS.getId();
tiles[dungeonCoord] = Tile.TUNNEL.getId();
while(tCount < tRan) {
System.out.println(tRan);
tCount ++;
int treeX = treeSpawn.nextInt(width * 5);
if(treeX < 256) {
treeX = 256;
}else {
tiles[treeX] = Tile.LOG.getId();
tiles[treeX + width] = Tile.LOG.getId();
tiles[treeX + width + width] = Tile.LOG.getId();
tiles[treeX - width] = Tile.LEAVES.getId();
tiles[treeX - width] = Tile.LEAVES.getId();
tiles[treeX - width - width] = Tile.LEAVES.getId();
tiles[treeX - width - width + 1] = Tile.LEAVES.getId();
tiles[treeX - width - width - 1] = Tile.LEAVES.getId();
tiles[treeX - width + 1] = Tile.LEAVES.getId();
tiles[treeX - width + 2] = Tile.LEAVES.getId();
tiles[treeX - width - 1] = Tile.LEAVES.getId();
tiles[treeX - width - 2] = Tile.LEAVES.getId();
tiles[treeX + 1] = Tile.LEAVES.getId();
tiles[treeX - 1] = Tile.LEAVES.getId();
tiles[treeX - width - width - width] = Tile.LEAVES.getId();
}
}
}
}
}
如何声明所有内容:
private byte[] tiles;
public int width;
public int height;
public boolean generateTree = true;
Random treeSpawn = new Random();
Random dungeonSpawn = new Random();
Random numTrees = new Random();
int tCount = 0;
int tRan = numTrees.nextInt(30);
treeSpawn
布尔值供以后使用。 最佳答案
这个答案来自我在评论中可以确定的。
代码如下:
if(treeX < 256) {
treeX = 256;
} else {
表示如果
treeX
小于256,则您的代码甚至不会尝试绘制树。为了绘制树,您需要删除else
(当您将if
语句评估为true
时,将忽略它),因此while
循环如下所示:while(tCount < tRan) {
System.out.println(tRan);
tCount ++;
int treeX = treeSpawn.nextInt(width * 5);
if(treeX < 256) {
treeX = 256;
}
tiles[treeX] = Tile.LOG.getId();
tiles[treeX + width] = Tile.LOG.getId();
tiles[treeX + width + width] = Tile.LOG.getId();
tiles[treeX - width] = Tile.LEAVES.getId();
... // Rest of the tree drawing code
}
关于java - 随机生成算法无法正确生成,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20250245/