我有这个代码在我的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
布尔值适用于以后。
答案 0 :(得分:1)
这个答案来自我在评论中可以确定的内容。
代码如下:
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
}