Jason94
Jason94

Reputation: 13608

How can I create a square hextilemap?

I have this code:

            int tX = 1;

            for (int y = 0; y < ROWS; y++)
            {
                for (int x = 0; x < tX; x++)
                {
                    Tile t = new Tile()
                    {
                        Texture = tile,
                        Position = new Microsoft.Xna.Framework.Point(x, y),
                        Troops = rnd.Next(1, 4),
                        OwnedByPlayerIndex = 0
                    };
                    t.Tap += tile_Tap;

                    if (t.Position.Y < ROWS)
                        tiles.Add(t);
                }
                tX += 2;

                tX = (int)MathHelper.Clamp(tX, 0, COLS);
            }

And what im trying to do is create a map within a rect, limiting the map by number of rows and cols.

But it does not work as it does not follow up and finishes the last corner, leaving it uncomplete

enter image description here

Upvotes: 0

Views: 129

Answers (1)

RogerN
RogerN

Reputation: 3821

You appear to have some redudant logic in there, and your inner loop is not iterating over all columns. If you want to fill the entire rectangle then you don't need tX at all. Example:

for (int y = 0; y < ROWS; y++)
{
    for (int x = 0; x < COLS; x++)
    {
        Tile t = new Tile()
        {
            Texture = tile,
            Position = new Microsoft.Xna.Framework.Point(x, y),
            Troops = rnd.Next(1, 4),
            OwnedByPlayerIndex = 0
        };
        t.Tap += tile_Tap;
        tiles.Add(t);
    }
}

Additionally, from your screenshot it looks like if the entire bottom row were filled then the lower staggered hexes would overlap the bottom of the red rectangle. If you don't want to add those lower hexes then you'll need to add them conditionally:

...
if (y > 0 || 0 == (x & 1))
    tiles.Add(t);

Upvotes: 1

Related Questions