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?
mapx * mapycharacters?mapxis never resetted to0, and with the next loop its value isMAP_WIDTHwhich is out of range. Adding anelse: breakorelse: mapx = 0should solve theIndexError(even though I think there is a smarter way to read that file to avoid this thing).