2013-11-27 56 views
0

我有這段代碼在我的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

你是如何確定這些樹木AREN」產卵? –

+1

不完全確定是什麼導致我正在閱讀的問題,但是,如果(treeX <256){treeX = 256; }否則......'不會按照我認爲你所期望的方式行事。如果'treeX'小於256,那麼你的樹永遠不會被繪製,因爲你使用了'else'。根據你在'if'語句中將'treeX'設置爲256的方式,我猜'else'是無意的,你仍然想繪製樹。 –

+0

另外,看看你的代碼,給定X和Y的'tiles'索引的通用公式是'tiles [x + y * width]';但是您將瓷磚編入索引的方式看起來不正確(或者您沒有完全解釋預期的行爲)。爲什麼'treeX'的範圍是0到5 * '寬度'的所有加減是什麼? –

回答

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 
} 
+0

謝謝,這是問題的一部分,也意識到我在一個地方繪製隨機數的樹木:/ – user2687097