Search code examples
python2d-games

Problem with map width and height values when making a tilemap in pygame


So, I'm trying to create a game map maker in python using pygame. I've written a bit of code that's meant to initialize the map with border tiles. I have two main variables for this: tiles_wide and tiles_tall. That is, how many tiles wide and tall the map is. When they're the same value (say, both 25), my code works. But when they aren't, it breaks. I have no idea why and it's frustrating me.

My Code:

tiles_wide = 30
tiles_tall = 25

# Create world list
world_data = []
for row in range(tiles_tall):
    # Create the set number of columns
    num_columns = [0] * tiles_wide
    world_data.append(num_columns)

# Create boundary
for tile in range(0, tiles_wide):
    world_data[tiles_wide - 1][tile] = 2
    world_data[0][tile] = 1
for tile in range(0, tiles_tall):
    world_data[tile][0] = 1
    world_data[tile][tiles_tall - 1] = 1

The exact error I get is:

IndexError: list index out of range

Solution

  • This piece of code looks suspicious, since the first index is the height and the second index is the width:

    # Create boundary
    for tile in range(0, tiles_wide):
        world_data[tiles_wide - 1][tile] = 2
        world_data[0][tile] = 1
    for tile in range(0, tiles_tall):
        world_data[tile][0] = 1
        world_data[tile][tiles_tall - 1] = 1
    

    Perhaps it should be:

    # Create boundary
    for tile in range(0, tiles_wide):
        world_data[tiles_tall - 1][tile] = 2
        world_data[0][tile] = 1
    for tile in range(0, tiles_tall):
        world_data[tile][0] = 1
        world_data[tile][tiles_wide - 1] = 1
    

    ?