gpt4 book ai didi

java - 随机生成算法无法正确生成

转载 作者:行者123 更新时间:2023-12-01 13:47:32 25 4
gpt4 key购买 nike

我有这段代码可以在我的 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 boolean 值供稍后使用。

最佳答案

这个答案来 self 在评论中可以确定的内容。

代码如下:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com