# Pygame 2d map error [closed]

I'm writing a Legend of Zelda like game in pygame.

I have this code for loading a map from a text file.

#Load maps
f = open ("map1","r")#This file is a text file containing only: 1
map01 = f.read()

terrains = [{"sprite": dirt}, {"sprite": mountian}, {"sprite": water}]

themap = [[-1 for x in range(150)] for y in range (150)]

for x in range (0,150):
for y in range (0,150):
themap[x][y] = terrains[map01]#if I replace map01 here with a number or random.randint(0,2) it works as expected

for x in range (0, 150):
for y in range (0, 150):
screen.blit(themap[x][y]["sprite"], [x * 16, y * 16])


But that gives me:

\$ python map.py
Traceback (most recent call last):
File "map.py", line 17, in <module>
themap[x][y] = terrains[map01]
TypeError: list indices must be integers, not str


Ok I'm making this a bit clearer I want to make a file called map1 that looks like this

1, 2, 1, 0 etc.


I can make a random screen with random.randint:

and I can make it a solid texture:

but I can't figure out how to predefine a map.

• While you are making a game, the question you're asking is not specific to game development. It's a general programming question. Those questions should be asked on stackoverflow.com – MichaelHouse Sep 30 '13 at 15:43
• Now that I've figured it out does it still need to be moved. Is there something a Mod can do to move the whole question? – Cnorwood7641 Oct 1 '13 at 18:03
• It appears I can't move it. You might want to check if it's possible for you to post questions on stackoverflow.com – MichaelHouse Oct 1 '13 at 23:59

## 2 Answers

The read() function in this line:

map01 = f.read()


doesn't do any format checking to try determine what the text is. It just returns raw bytes as a string. You need to convert it to a number explicitly:

map01 = int(f.read())

• That worked. But I can't make it like 1, 1 ,0, 0, 1 or it gives me an error. I can only use one character any idea how to fix that part? – Cnorwood7641 Sep 30 '13 at 16:56
• Byte56's comment is correct, you're asking a Python programming question, not a game question. That's better asked on SO. Be sure to take some time going over the Python docs on reading text from files before you ask. The SO folks will want to see that you've done some research. – Michael Kristofik Sep 30 '13 at 18:42

Ok I managed to fix it myself so I'll go ahead and put what I got.

Instead of loading a text file I made a map_data.py file and put a two dimensional array inside. then I imported the array in my main file:

from map_data import map1


and then I changed this line to:

for x in range (0,150):
for y in range (0,150):
themap[x][y] = terrains[map1[x][y]]

/\
I had random.randint(0, 2) here before.