gpt4 book ai didi

python - 检查药水使用情况的更好方法?

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:38 27 4
gpt4 key购买 nike

在我的游戏中,我遇到了药水问题。如果某个房间里有药水,我会创建 Potion() 类的一个新实例,如下所示:

potion = Potion()

问题在于,用户可以根据需要多次调用此函数并治愈自己,直到其生命值最大化,因为 raw_input() 处于无限循环中。我通过使用 del 删除实例解决了这个问题。

我的下一个问题是包含不止一种药水的房间。这是我的解决方案

potion = Potion()
potion_exist = True
potion2 = Potion()
potion2_exist = True
potion3 = Potion()
potion3_exist = True

并在循环中:

if next == "potion":
if potion_exist:
print "Potion 1"
potion.heal(You)
del potion
potion_exist = False
elif potion2_exist:
print "Potion 2"
potion2.heal(You)
del potion2
potion2_exist = False
elif potion3_exist:
print "Potion 3"
potion3.heal(You)
del potion3
potion3_exist = False
else:
print "There is no potion to use."

这对我来说似乎是一个相当冗长的方法,但它确实有效。我只是想知道我是否忽略了另一种更简单的方法来做到这一点。如果没有,我可以使用这种格式,但如果我可以清理我的代码,我宁愿这样做。谢谢!

最佳答案

使用列表来存储药水实例。在你的 main 函数中像这样定义它。

potions = []
for i in range(3): # append 3 potions to the list
potions.append(Potion())

循环中的代码看起来像这样(它总是使用列表中的第零个部分):

if next == "potion":
if (len(potions) > 0): # if there are potions left
print "potion"
potions[0].heal(You) # heal using zeroth potion from the list
potions.pop(0) # remove zeroth item from the list

关于python - 检查药水使用情况的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com