检查药剂使用的更好方法

2024-09-30 23:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

potion = Potion()

问题是,用户可以根据自己的需要多次调用它,并自行修复,直到他们的健康状况达到最大值,因为原始的\u 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."

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


Tags: 实例youfalsetrueifexist房间print
1条回答
网友
1楼 · 发布于 2024-09-30 23:44:00

使用列表存储药剂实例。在主函数中这样定义它。你知道吗

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

循环中的代码如下所示(它总是使用列表中的第0个药剂):

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

相关问题 更多 >