Python: Confusion on the Way I Might Pull This List Comprehention Off
Hello,
I was messing around with some RPG style code out of boredom. Many other questions will follow as I continue to make it.
Anyway, I was coding an inventory type system. The inventory is lain out as follows:
The inventory it's self is a dictionary in the player class, helpfully labeled inventory,
The keys are the item object its self and the value is the amount of that item.
Name is stored in the item's object, and I've come up with a passable system that's is a bit to conveluded to lay out here, but it involves inheritance for different item types. More or less, there is a class for containers.
Now my issue is when I'm trying to search the entirety of the inventory for an item.
Obviously, I could just do item in self.inventory.keys(), but you know, the small issue of having containers in my inventory.
My original function was going to be:
# Note that this is inside the player class, hence the indentation level.
def search_inventory(self, item, quantity):
# Returns item object if found, None otherwise.
for key, value in self.inventory.keys(), self.inventory.values():
if item == key.name:
return key
# Otherwise, it's not on the surface level, so we need to check, one, if the current item is a container, and if so, loop through it's contents.
if isinstance(key, Container) && item in key.contents.keys() && quantity >= key.contents[item]: # Container is imported above.
return key
return None
Note that this doesn't follow my normal standards, it's really messy, but I wrote it by hand.
Anyway, I'd like to do this a lot cleaner, and I assumed that list comprehension would work for something like this, but I've never used comprehension with nested things, and wasn't sure exactly how to get this to work out. Any suggestions? Am I aproaching this entire thing wrong?
P.S. Bonus challenge, somehow I'd like to make some recursive way to search a found container for internal containers, and search those and etc etc.
Thanks for suggestions.
-- Audiogames-reflector mailing list Audiogames-reflector@sabahattin-gucukoglu.com https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector