So, I was making a simple 2D game in pygame, and was making the map (following a tutorial video, don’t judge me, I’m new to pygame) and using replit.com, and that error showed up in the console.
here’s my code for it:
JavaScript
x
42
42
1
import pygame, sys
2
W = 0
3
S = 1
4
G = 2
5
F = 3
6
7
BLUE = (0,0,255)
8
SAND = (194,176,128)
9
GRASS = (124,252,0)
10
FOREST = (0,100,0)
11
12
TileColor = {W : BLUE,
13
S : SAND,
14
G : GRASS,
15
F : FOREST
16
}
17
18
map1 = {(W, S, G, F, F, F, G, S, W, W, W, W),
19
[W, S, S, G, G, G, G, F, F, W, W, W],
20
[W, S, G, G, G, F, F, F, F, F, W, W],
21
[W, S, S, G, G, G, G, G, F, F, F, W]
22
}
23
24
TILESIZE = 40
25
MAPWIDTH = 12
26
MAPHEIGHT = 4
27
28
pygame.init()
29
DISPLAY = pygame.display.set_mode((MAPWIDTH * TILESIZE,MAPHEIGHT * TILESIZE))
30
31
while True:
32
for event in pygame.event.get():
33
if event.type == pygame.QUIT:
34
pygame.quit()
35
sys.exit()
36
37
for row in range(MAPHEIGHT):
38
for col in range(MAPWIDTH):
39
pygame.draw.rect(DISPLAY,TileColor[map1[row][col]],(col * TILESIZE,row * TILESIZE,TILESIZE,TILESIZE))
40
41
pygame.display.update
42
if anyone has any suggestions for changing my code, please say, and I am sticking with replit.com
Advertisement
Answer
You’re pretty much correct already. I’m just guessing at how your code is supposed to work, but using a python dictionary for the tile colours with integer-variables as keys is what’s causing the issue.
If you change your tile keys to a letter:
JavaScript
1
5
1
TileColor = { 'W' : BLUE,
2
'S' : SAND,
3
'G' : GRASS,
4
'F' : FOREST }
5
And then in your map, use letters too:
JavaScript
1
5
1
map1 = [ "WSGFFFGSWWWW",
2
"WSSGGGGFFWWW",
3
"WSGGGFFFFFWW",
4
"WSSGGGGGFFFW" ]
5
It works pretty much perfectly:
Full code:
JavaScript
1
36
36
1
import pygame, sys
2
3
BLUE = (0,0,255)
4
SAND = (194,176,128)
5
GRASS = (124,252,0)
6
FOREST = (0,100,0)
7
8
TileColor = {'W' : BLUE,
9
'S' : SAND,
10
'G' : GRASS,
11
'F' : FOREST }
12
13
map1 = [ "WSGFFFGSWWWW",
14
"WSSGGGGFFWWW",
15
"WSGGGFFFFFWW",
16
"WSSGGGGGFFFW" ]
17
18
TILESIZE = 40
19
MAPWIDTH = 12
20
MAPHEIGHT = 4
21
22
pygame.init()
23
DISPLAY = pygame.display.set_mode((MAPWIDTH * TILESIZE,MAPHEIGHT * TILESIZE))
24
25
while True:
26
for event in pygame.event.get():
27
if event.type == pygame.QUIT:
28
pygame.quit()
29
sys.exit()
30
31
for row in range(MAPHEIGHT):
32
for col in range(MAPWIDTH):
33
pygame.draw.rect(DISPLAY,TileColor[map1[row][col]],(col * TILESIZE,row * TILESIZE,TILESIZE,TILESIZE))
34
35
pygame.display.update()
36