Aearnus
Aearnus

Reputation: 541

Accessing tuples from a list in Python

So, I haven't been able to figure out how to do this yet. I'm making a map parser for a game, and so far I have a three dimensional list "mapData" in the module "maps". It stores tuples that contain the tile and floor ids. So, when I'm trying to draw the floor, I call

if maps.mapData[mapIndex][x][y][0] == 0: c.blit(maps.grass, tileRect)

to draw the grass for example, and to draw the tiles I call

if maps.mapData[mapIndex][x][y][1] == 1: c.blit(maps.tallGrass, tileRect)

to draw the tall grass. Though, the [0] and [1] is what I'm confused about. They are trying to reference the first and second element of the tuple respectively, but I suspect I am doing that wrong, as I am getting this error:

TypeError: 'int' object is not subscriptable

Just to help, the list "mapData" is initialized as follows:

mapData = [[[0 for y in range(19)] for x in range(25)] for m in range(mapAmount)]
mapData[mapIndex["spawn"]][5][5] = (0, 1)

with "mapIndex" being a dictionary of integers that specify what map is what.

So, I need to know how to get a specific element from a tuple, preferably without using x, y = tuple because that takes a bit more memory, as it has to store the variable. and this is in the rendering loop. If that is the only way to do it, then that is ok by me though. Thanks!

As a side question, does anyone have better idea of deciding what tile to draw other than making a giant if+elif statement in the rendering code?

EDIT: I tried this code:

 floor, tile = maps.mapData[mapIndex][x][y]

 #draw floor
 if floor == 0: c.blit(maps.grass, tileRect)

 #draw tiles
 if tile == 1: c.blit(maps.tallGrass, tileRect)

and got the error:

TypeError: 'int' object is not iterable

Upvotes: 1

Views: 190

Answers (1)

Aearnus
Aearnus

Reputation: 541

Thanks to @LukasGraf, the problem has been solved. Not all the variables in the list were initialized as tuples, so I changed this initialization code

mapData = [[[0 for y in range(19)] for x in range(25)] for m in range(mapAmount)]

to this

mapData = [[[(0, 0) for y in range(19)] for x in range(25)] for m in range(mapAmount)]

to make the default value in the list the tuple (0, 0) instead of 0.

Upvotes: 1

Related Questions