【发布时间】:2020-09-18 02:37:28
【问题描述】:
我正在为我在学校的计算机科学/网络安全课程制作一个基于文本的无限生存游戏。我正在使用 Python 并有一个 inventory[] 列表,我使用 .append(item) 将项目和材料添加到库存列表中。然后我还使用单独的变量来实际赋予字符串含义,但这无关紧要。每个项目在库存清单中以“项目,(项目数量)”的格式写入。我需要知道是否可以使用 .index() 仅搜索列表中元素的“项目”部分,以便我只能编辑元素的(项目数量)部分,如果没有t 我需要知道是否有替代方案。最好不要撤消我正在使用的方法,其中清单是一个列表,因为大部分游戏都是围绕该方法构建的。
materials = ["log", "stone", "sticks", "string", "junk", "rocks", "cloth", "herbs"]
inventory = []
def material_gathering():
global health, hunger, log_amount, stone_amount, stick_amount, string_amount, junk_amount, rock_amount, cloth_amount, herb_amount
material_type = random.choice(materials)
material_amount = random.randint(2, 10)
health = health - material_amount
hunger = hunger + material_amount
if material_type == "log":
log_amount = log_amount + material_amount
print("You gathered " + str(material_amount) + " logs.")
if "log, " in inventory:
log_position = inventory.index("log, ")
inventory[log_position] = ("log, " + str(log_amount))
else:
inventory.append("log, " + str(log_amount))
【问题讨论】:
-
dict在这方面会比list好得多。键是项目名称,值是金额。这样您就不必再与字符串相互转换了。 -
我不知道您为什么要问我们“我可以使用它吗?”您拥有最终的权威 - 我们希望您在发布之前尝试。
-
如何在有限的计算机上制作无限游戏?
-
Green Cloak Guy,谢谢你的建议,Prune,我确实试过了我只是用错了我的问题,上面的代码不起作用我正在寻求解决方案
-
字符串没有“节”。如果您想搜索一个子字符串,那么您应该做的第一件事是查看文档 中的
.index方法,看看它是如何工作的。第二件事是提出规则,告诉您您要搜索的子字符串在哪里。或者,正如其他人建议的那样,您可以首先使用结构更合理的数据。