Reputation: 61
I'm using python 2.5 (I know it's an old version) and I keep getting a very frustrating 'List index out of range' exception. I'm working on a tile based game, and bellow is the code for creating the map I'm having issues with:
#Creates the list
def setMapSize(self):
l = raw_input('Custom Map length: ')
h = raw_input('Custom Map height: ')
if not(l=='')and not(h==''):
self.length = int(l)
self.height = int(h)
self.tileMap = [[i]*self.length for i in xrange(self.height)]
print self.tileMap
#Load each element of the list from a text file
def loadMap(self,filePath='template.txt'):
loadPath = raw_input('Load the map: ')
if loadPath =='':
self.directory = 'c:/Python25/PYGAME/TileRpg/Maps/' + filePath
print 'Loading map from ',self.directory
readFile = open(self.directory,'r')
for y in xrange(self.height):
for x in xrange(self.length):
#reads only 1 byte (1 char)
print '---Location: ',x,y
print self.tileMap
self.tileMap[x][y]=int(readFile.read(1))
print 'Loaded map:',self.tileMap
readFile.close()
print 'Map loaded\n'
Here is the output and error message I get, please tell me if you know what's going on:
Main began
Map began initialization
Map initialized
Custom Map length: 2
Custom Map height: 5
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
Load the map:
Loading map from c:/Python25/PYGAME/TileRpg/Maps/template.txt
---Location: 0 0
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
---Location: 1 0
[[9, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
---Location: 0 1
[[9, 0], [9, 0], [0, 0], [0, 0], [0, 0]]
---Location: 1 1
[[9, 9], [9, 0], [0, 0], [0, 0], [0, 0]]
---Location: 0 2
[[9, 9], [9, 9], [0, 0], [0, 0], [0, 0]]
Traceback (most recent call last):
File "C:\Python25\PYGAME\TileRpg\LevelEditorMain.py", line 7, in <module>
class Main():
File "C:\Python25\PYGAME\TileRpg\LevelEditorMain.py", line 17, in Main
tileMap.loadMap()
File "C:\Python25\PYGAME\TileRpg\Map.py", line 48, in loadMap
self.tileMap[x][y]=int(readFile.read(1))
IndexError: list assignment index out of range
As you can see, the index I'm assigning to seems to exist, but I still get this error.
Upvotes: 0
Views: 988
Reputation: 1121226
You swapped height and width; the outer list is of length height
, not the inner. self.tileMap[0]
is a list of length 2, so the maximum index you can use on it is 1
, not 2
.
Swapping x
and y
would solve this:
for x in xrange(self.height):
for y in xrange(self.length):
#reads only 1 byte (1 char)
print '---Location: ',x,y
print self.tileMap
self.tileMap[x][y]=int(readFile.read(1))
Not that you need to use indices here, you can alter the lists directly:
for row in self.tileMap:
row[:] = [readFile.read(1) for _ in row]
You can read a row at a time:
for row in self.tileMap:
row[:] = map(int, readFile.read(self.length))
Upvotes: 2