如何在Python游戏清单系统中正确使用循环?

2024-04-26 06:01:35 发布

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

我正在为一个化妆游戏(Python/Ren'py)建立一个库存系统,我被困在最后一个关卡。我将库存对象、服装对象和物品都设置为:

class Clothing(store.object):
    def __init__(self,name,desc,place):
        self.name = name
        self.desc = desc
        self.place = place
        place = []

class Inventory(store.object):
    def __init__(self, name):
        self.name=name
        self.wearing=[]


    def wear(self,item):
        self.wearing.append(item)
        return

    def is_wearing(self, item):
        if item in self.wearing:
            return True
        else:
            return False

    def remove(self,item):
        if item in self.wearing:
            self.wearing.remove(item)
        return

    def drop(self, item):
        self.wearing.remove(item)

    def remove_all(self):
        list = [item for item in self.wearing]
        if list!=[]:
            for item in list:
                self.wearing.remove(item)
        return

player_inv = Inventory("Player")
wardrobe_inv = Inventory("Wardrobe")

jeans = Clothing(name="Jeans", desc="blue jeans", place=["legs"])
tshirt = Clothing(name="T-shirt", desc="white tee", place=["torso"])
boxers = Clothing(name="Boxer shorts", desc="white boxer shorts", place=["crotch"])
dress = Clothing(name="Dress", desc="a pretty pink dress", place=["legs", "torso"])
socks = Clothing(name="Socks", desc="sports socks", place=["shins"])
sneakers = Clothing(name="Sneakers", desc="beat up old sneakers", place=["feet"])
heels = Clothing(name="High Heels", desc="sky high stilettos", place=["feet"])
towel = Clothing(name="Towel", desc="a basic towel", place=["torso", "chest", "legs", "crotch", "shins", "feet"])

wardrobe_inv.wear(towel)
wardrobe_inv.wear(heels)
wardrobe_inv.wear(dress)

player_inv.wear(jeans)
player_inv.wear(tshirt)
player_inv.wear(boxers)
player_inv.wear(socks)
player_inv.wear(sneakers)

到目前为止一切进展顺利。但是上面一个非常重要的部分是在每个衣服对象中设置的“位置”标签。原因是,假设一名球员穿着牛仔裤(位置:腿部)和T恤(位置:躯干),他们想穿上一件连衣裙,他们必须先脱下牛仔裤和T恤(换句话说,我需要一个功能来扫描这些位置标签,并在他们穿上新的物品之前,将带有匹配标签的物品从玩家发送到衣柜

我几乎做到了(好吧,我说‘我’——下面的许多内容实际上是一个善良的灵魂在另一个论坛上提出的)。但我觉得我的善意正在流失,我很快就要让它发挥作用了。是的,我到目前为止已经做到了:

def try_on(self,item):
        for all_clothes in self.wearing:
            for matching_tags in all_clothes.place:
                if matching_tags in item.place:
                    wardrobe_inv.wear(all_clothes)
                    self.remove(all_clothes)
        self.wearing.append(item)
        wardrobe_inv.remove(item)
        return

而且它几乎是功能齐全的。按照预期,它会扫描标签并将物品送回衣柜。唯一的问题是,它只会将一件物品送回衣柜,这是它遇到的第一件带有匹配标签的物品。我知道一定有一种非常简单的方法让代码在特定的se中循环然后,把每一个匹配的标签移到衣柜里,然后继续剩下的。但我一辈子都搞不清楚它是什么!我试过在item.place中制作“if match_tags in item.place:”另一个for loop,但这似乎会让各种奇怪的古怪意外事件发生

(请记住,我从网上找到的几个不同的例子中拼凑了清单,并在周末参加了Python强化速成班,但我仍然是一个完全的初学者,在这里我真的不懂!我只想在我头上还留着一些头发的时候让清单工作起来!)所以,请有人-是否有办法确保该试用功能按预期工作,并将每个带有匹配“位置”标签的物品发送回衣柜,而不仅仅是它遇到的第一件

提前谢谢你,很抱歉有这么多的文字。我真的不知道如何更简洁地解释这个问题


Tags: nameinselfreturndefplace标签item