user2193386
user2193386

Reputation: 11

Python, list index out of range error

I'm trying to test a simple 2d map coordinate generator in python. It creates a Tile objects with x and y array so that I can access the coordinates and modify their properties.

This creates the map object and fills it with tiles in a 2D coordinate plane

map = [[ Tile(True)
    for y in range(MAP_HEIGHT) ]
        for x in range(MAP_WIDTH) ]

The tile class:

class Tile:
    #a tile of the map and its properties
    def __init__(self, blocked, type, owner, block_sight = None):
        self.blocked = blocked
        self.type = type
        self.owner = owner 
        if block_sight is None: block_sight = blocked
        self.block_sight = block_sight

I attempted to have the program read a text file character by character to create a map. It would insert an object at the coordinates provided by mapx and mapy into the map.

mapx = 0
mapy = 0
filename = str(mapn) + '.txt'
new_map = [[ Tile(True, 0, 0)
         for y in range(MAP_HEIGHT) ]
       for x in range(MAP_WIDTH) ]
with open(filename) as f:
    while True:
        c = f.read(1)
        if not c:
            return new_map
        elif (c == '#'):
            new_map[mapx][mapy].blocked = False
            new_map[mapx][mapy].block_sight = True
            new_map[mapx][mapy].type = 0
            new_map[mapx][mapy].owner = 0

(After several more elifs)

if(mapx < MAP_WIDTH):
    mapx += 1
elif(mapy < MAP_HEIGHT):
    mapy += 1
    mapx = 0

When running this, I get this error: IndexError: list index out of range. It says the line

 new_map[mapx][mapy].blocked = False 

is to fault for this. Any idea what I'm doing wrong?

Upvotes: 1

Views: 973

Answers (2)

Dvx
Dvx

Reputation: 279

It would be more pythonic if you first read the file and create a list [ ... (xi, yi) ... ] and then create a loop over the (xi,yi) to instanciate the Tile objects. This way, you would avoid to have to think about the list indices.

Just my 2 cts...

Upvotes: 0

TAS
TAS

Reputation: 2079

The after initialization the outer list will have have MAP_WIDTH elements with indices from 0 to MAP_WIDTH-1. Similarly, each inner list will have indices from 0 to MAP_HEIGHT-1.

Consider what happens when mapx = MAP_WIDTH-1; ie is at the end of the list using your code:

if(mapx < MAP_WIDTH):
    mapx += 1
....

The value of mapx will become larger than the upper bound of the list.

The test should be mapx < MAP_WIDTH-1 to resolve this. The test in the elif also needs to be changed accordingly.

Upvotes: 2

Related Questions