从列表中随机选择一个函数,然后将条件应用于结果



在下面的代码中,abc是预定义的函数,是更大代码的一部分。代码始终返回elif部分,即使选择enemy_def。我尝试打印每一个,但没有任何反应。

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]
enemyresponse = random.choice(d)()
#print(enemyresponse)
if enemyresponse == b :
   thing.health = thing.health - 0.25
   #print(enemyresponse)
elif enemyresponse != b :
     #print(enemyresponse)
     thing.health = thing.health - 1

enemy_reponse永远不会等于b *,因为enemy_reponse是函数的返回值,而不是函数本身。请注意如何在随机选择函数后立即调用它:

random.choice(d)()
#               ^Called it

在名为 chosen_function(或类似变量(的变量中保存选择的函数,然后检查该函数。

您可能是这样(未经测试(的意思:

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]
# Randomly get function from list
chosen_function = random.choice(d)
# Call it to get the return value
func_return = chosen_function()
print(func_return)
if chosen_function == b:
   thing.health = thing.health - 0.25
else:
   thing.health = thing.health - 1

*除非b自己返回,这似乎不太可能。

最新更新