I am putting together a terminal-based RPG where the map is 2D. Presently, I am attempting to find the index of the player’s position, which I will later use to move said player either north/south/east/west (based on the player’s action).
Here is my issue: the only indexes/indices that are stored (or this code works for) are [0][0], [1][1], and [2][2]. The error I receive is with line 20 (ValueError: ‘P’ is not in list). What can I do to adjust/edit my code so that I can find the index of "P" in other spots, such as [0][2] or [2][3]?
—————————Code Below———————————
-
A sample world map as a 2D array
-
P represents the player’s position
-
F represents part of a forest/a forest biome
-
To represents a town
world_map = [[" ", " ", "F", "To"], [" ", " ", "F", "F"], [" ", "P", "", "F"]]
-
This global variable stores the previous value of a given index before the player moves –> use later for when player moves
current_position = " "
-
This function iterates through the larger list and then the smaller lists/arrays
def go_east(): for x in range(len(world_map)): for y in range(len(world_map[x])): print(world_map[x][y]) if (world_map[x][y] == "P"): position_x = world_map[x].index("P") position_y = world_map[y].index("P") print(position_x, position_y) print(world_map[x][y].index("P")) go_east()
As said before, when I move "P" to a position that does not coincide with double digits (i.e. [1][1]), I receive a ValueError in relation to position_y (‘P’ is not in list). Changing the position of "P" to most other positions gives me the same error.
I am using Python 3.11.4 and Visual Studio Code.
2
Answers
your problem lies in these rows:
you are looking for p in the same index, so unless x == y you can’t find it.
moreover, you have already found the indices of x an y through the loops so you can change the above lines to:
or, if you prefer:
also, whether you set the value of P manually or generate it randomly, i would suggest to save it to a variable and the moment of generation and the the movement will be just adding or subtracting the values of x and y
You’re referring to some wrong positions by accessing
world_map[x].index("P")
andworld_map[y].index("P")
– these two does not do what you expect them to do.Since you’re iterating in the nested loop with known
x
andy
value at each step, you should use these values when assigning the position:or just use these values directly.
I have simplified your code just a bit and added 3 simple examples showing that the code works (aka "test on the go with semi-random values"):