Reputation: 95
Good evening! I am trying to figure out how to compare a variable with the int entries in a dictionary. I am programming an arcade game and I have x and y coordinates stored in a dict (x:y) and playerx and playery variables. I would like to make a comparison so that if the player ever reaches coordinates specified in the dict, it would do something. How could I go about doing this?
I imagine something along the lines of:
if playerx in dict:
if playery in dict[x]:
dosomething()
But I cannot quite figure out how to do it properly.
Upvotes: 1
Views: 87
Reputation: 2684
given the speed of dictionaries its a very fast python data structure. but if you want to really visualize coordinates intuitively , try creating a spatial(x,y) tuple. assuming all locations are managed properly by your game scheme.
#Code
d={"VillageLocation":(1,1)}
player1_location=(1,1)
player2_location=(2,2)
#check by values
reachedVillage = player1_location in d.values() #returns True #method for checking by values
if (reachedVillage == True):
goToSleep("player1")
Explanation: Player 1 will now go to sleep because player1's location and village location now match which is stored as 'True' in the "reachedVillage "variable.
Trick Used: checking in dictionary by values instead of keys.
Upvotes: 2
Reputation: 1141
Perhaps this is what you need:
player=(0,1)
your_dict = {0:1,1:2,2:3}
if player[0] in your_dict:
if player[1] == your_dict[player[0]]:
print("hello, is it me you're looking for?")
Upvotes: 2
Reputation: 1511
Maybe you can use a list of tuples
l_coord = [(1, 2), (2, 3), (4, 5)]
player_x = 2
player_y = 3
player = (player_x, player_y)
if player in l_coord:
print("I am here.")
Upvotes: 3