I wrote this code to randomly generate a square terrain that somewhat resembles an island. First, I randomly populated a square with grass tiles (1s) on a plane of water tiles (0s):
Then, I looped through each tile and changed its tile type according to its neighboring tiles(if a tile is surrounded by 4 or more water tiles, it becomes a water tile, otherwise it becomes a grass tile):
The results don't seem all that pleasing; not only is the terrain filled with holes and lack overall "togetherness", it is also weirdly symmetrical diagonally.
Here's the code:
private void SmoothMap (Chunk chunk)
{
for(int row = 1; row < chunk.rows-1; row++)
{
for(int col = 1; col < chunk.cols-1; col++)
{
//if current tile is not null
if(chunk.GetTile(row, col) != null)
{
//Check its neighboring tiles
int neighboringTiles = GetSurroundingTiles(row, col, chunk);
//System.out.println("Position: " + row + ", " + col);
//System.out.println("Current tile type: " + chunk.GetTile(row, col).type);
//System.out.println("Neighboring water tiles: " + neighboringTiles);
if (neighboringTiles > 4)
{
if (chunk.GetTile(row, col) != null)
{
chunk.GetTile(row, col).texture = GetRandomWaterTexture();
chunk.GetTile(row, col).type = Enums.tileType.Water;
}
}
else if (neighboringTiles < 4)
{
if (chunk.GetTile(row, col) != null)
{
chunk.GetTile(row, col).texture = GetRandomGrassTexture();
chunk.GetTile(row, col).type = Enums.tileType.Grass;
}
}
}
}
}
}
private int GetSurroundingTiles(int r, int c, Chunk chunk)
{
int surroundingTiles = 0;
for(int x = c-1; x <= c+1; x++)
{
for(int y = r-1; y <= r+1; y++)
{
if (x != c || y != r)
{
if(chunk.GetTile(x, y) != null)
{
if (chunk.GetTileCode(x, y).equals("0"))
{
surroundingTiles++;
}
}
}
}
}
return surroundingTiles;
}
Does anyone know why it is the way it is? Or a better way to approach generating an terrain like this?
Here's the GetTile() code:
public String GetTileCode(int r, int c)
{
Tile tile;
ArrayList<Tile> chunk_row;
if(tiles.size() > r && r >= 0){
chunk_row = tiles.get(r);
if(chunk_row != null && chunk_row.size() > c && c >= 0){
tile = chunk_row.get(c);
return tile.isGrass() ? "1" : "0";
}
}
return "0";
}
1 is grass, and 0 is water.
chunk.GetTileCode()
? \$\endgroup\$