Page 1 of 1

help with invantory system !

Posted: Sat Dec 04, 2010 6:48 am
by filsduloup
Hi, i have a trouble with my version of inventory script !

i have the number of object, but i want in def buy the number of the item i have buy as +1, i use
"items.nbr += 1" but that dosent fuction !

Code: Select all

init python:
    class Item:
        def __init__(self, name, cost, nbr):
            self.name = name
            self.cost = cost
            self.nbr = nbr

    class Inventory:
        def __init__(self, money=10):
            self.money = money
            self.items = []

        def buy(self, item):
            if self.money >= item.cost:
                self.money -= item.cost
                self.items.append(item)
                return True
            else:
                return False

        def earn(self, amount):
            self.money += amount
thanks for advance !

Re: help with invantory system !

Posted: Sat Dec 04, 2010 12:46 pm
by DaFool
I seem to recall that saving values in arrays are not as robust as in individual variables.
You could try creating a temporary variable, incrementing that, then storing into the array.

Re: help with invantory system !

Posted: Sat Dec 04, 2010 1:35 pm
by Bocom
You can't do 'items.nbr', since items is a list and nbr is an attribute of Item. You'll have to access the item in the list first. For example:
(This snippet assumes that you have instantiated the Inventory class as "inv")

Code: Select all

$ inv.items[0].nbr += 1
If you're just going to increase it in the buy function, then this'll do:

Code: Select all

[...]
        def buy(self, item):
            if self.money >= item.cost:
                self.money -= item.cost
                self.items.append(item)
                self.items[-1].nbr += 1 # This accesses the last element of the list
                return True
            else:
                return False
[...]
However, this is a bit useless since if you already have an item in your list, it won't add the to the nbr of the existing item, it'll just add another item. You could solve that like this:

Code: Select all

[...]
        def buy(self, item):
            if self.money >= item.cost:
                self.money -= item.cost
                if item in self.items:
                    self.items[self.items.index(item)].nbr += 1 # The item is already in the list, so find it and increase the nbr.
                else:
                    self.items.append(item)
                    self.items[-1].nbr = 1 # This accesses the last element of the list
                return True
            else:
                return False
[...]