user3165683
user3165683

Reputation: 367

2d randomly generated tiled game Libgdx Java

So i am trying to create a game that is top down 2d and using a pixel tiled map style format. They way i would like to do it is have say 4 different tiles, different shades of green and brown for grass. I would like to generate these 4 tiles randomly around the 1920*1080 pixel area to give a semi realistic effect. So something like this: enter image description here

But with randomly generated different tiles in there. What would be the best way of doing this?

Upvotes: 1

Views: 2543

Answers (1)

theDazzler
theDazzler

Reputation: 1059

Just use a for loop and place a random tile at each location

for(int i = 0; i < numTilesY; i++)
{
    for(int j = 0; j < numTilesX; j++)
    {
        placeRandomTile(i, j);
    }
}

placeRandomTile would just use java's Random class to choose a random number, and depending on the number will place the corresponding tile. For example, if randomNumber == 2, place grass tile.

If you want the tiles to form a realistic looking world similiar to Minecraft, you should use some sort of a noise function like Perlin Noise. It will be random in that every time you generate a new world, the world will be different.

EDIT:

int[][] map= new int[32][32]; //create 32x32 tile map

public void placeRandomTile(int xIndex, int yIndex)
{
    Random rand = new Random();
    int value = rand.nextInt(5);//get value between 0 and 5
    int tile = 0;

    if(value == 0)
    {
        tile = 1; //1 corresponds to GRASS tile
    }

    if(value == 1)
    {
        tile = 2; //WATER tile
    }

    this.map[xIndex][yIndex] = tile;
}

Now that you have your map data stored in a 2D array, you just need to loop through the data and draw each tile accordingly at the proper locations.

In your drawing method, you would just draw each tile from the map like so:

public void draw(float x, float y, Graphics g)
{
    for(int i = 0; i < map.length; i++)
    {
        for(int j = 0; j < map[i].length; j++)
        {
            int tileType = map[i][j]; //get tile type
            if(tileType == Tile.grass.id)
            {
                Tile.grass.draw(x + (j * Tile.WIDTH), y + (i * Tile.HEIGHT));//draw grass
            }

        }
    }
}

Since you are using libgdx, you will need to look into these classes: TiledMap, TiledMapTileLayer, Screen, Texture, and OrthogonalTiledMapRenderer. You basically create a TiledMap and draw Textures using a TiledMapRenderer.

You can view a sample game I have on Github from a while ago that does what you want. It's here. Look at Dungeon class and screens/GameScreen class

Upvotes: 1

Related Questions