When I try to run the program I get the error:
line 26, in
if map_objets[POSITION_X] == coordinate_x and map_objets[POSITION_Y] == coordinate_y:
TypeError: 'int' object is not subscriptable"
and since I am a self-taught learner I find myself without ways to find a possible solution that works for my case.
import os
import readchar
POSITION_X = 0
POSITION_Y = 0
MAP_WIDTH = 20
MAP_HEIGHT = 15
my_position = [4, 5]
map_objets = [[1, 3], [5, 8], [8, 9]]
while True:
# Draw_map
print("+" + "-" * MAP_WIDTH * 3 + "+")
for coordinate_y in range(MAP_HEIGHT):
print("|", end="")
for coordinate_x in range(MAP_WIDTH):
char_to_draw = " "
objet_in_cel = None
for map_objets in map_objets:
if map_objets[POSITION_X] == coordinate_x and map_objets[POSITION_Y] == coordinate_y:
char_to_draw = "o"
objet_in_cel = map_objets
if my_position[POSITION_X] == coordinate_x and my_position[POSITION_Y] == coordinate_y:
char_to_draw = "@"
if objet_in_cel:
map_objets.remove(objet_in_cel)
print(" {} ".format(char_to_draw), end="")
print("|")
print("+" + "-" * MAP_WIDTH * 3 + "+")
# ask user where he wants to move
direction = readchar.readchar()
if direction == "w":
my_position[POSITION_Y] -= 1
my_position[POSITION_Y] %= MAP_HEIGHT
elif direction == "s":
my_position[POSITION_Y] += 1
my_position[POSITION_Y] %= MAP_HEIGHT
elif direction == "a":
my_position[POSITION_X] -= 1
my_position[POSITION_X] %= MAP_WIDTH
elif direction == "d":
my_position[POSITION_X] += 1
my_position[POSITION_X] %= MAP_WIDTH
elif direction == "q":
break
os.system('clear')
Your problem lies in this line
Since you are naming the iteration variable the same as your original variable
And this causes the following
But after the third one, since you reassigned the
map_objets
real one[[1, 3], [5, 8], [8, 9]]
to themap_objets
iteration one, now youmaps_objects
are now the last iterator, that is,map_objets= [8, 9]
so when you return to enter it now iterates over this arrayNamely
map_objects = [8, 9] for map_objects in map_objects: ....
So when trying to do this
i was actually trying to do this
8[POSITION_x]
The solution
Just change the name of the variable.
Hello, if you validate the object is not subscriptable error, you want to indicate that variable is incompatible with what you want to do
Try the following in this way you avoid that error and give more readability to the code