带有int条目的Python dict与int的比较



晚上好!我正试图弄清楚如何将变量和字典中的int条目进行比较。我正在编程一个街机游戏,我有x和y坐标存储在dict(x:y(和playerx和playery变量中。我想做一个比较,这样如果玩家达到dict中指定的坐标,它就会有所作为。我该怎么做呢?

我想象的是:

if playerx in dict:
if playery in dict[x]:
dosomething()

但我不太明白怎样才能把它做好。

也许您可以使用元组列表

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.")

也许这就是您所需要的:

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?")

考虑到字典的速度,它是一个非常快的python数据结构。但是如果您想直观地可视化坐标,请尝试创建一个空间(x,y(元组。假设所有位置都由您的游戏方案正确管理。

#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")

解释:玩家1现在将进入睡眠状态,因为玩家1的位置和村庄位置现在匹配,存储在"reachedVillage"变量。

使用的技巧:按值而不是键检查字典。

最新更新