Changing an object's attribute on a specific list

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
Message
Author
Cazad0ra
Newbie
Posts: 22
Joined: Wed May 19, 2021 3:53 pm
Contact:

Changing an object's attribute on a specific list

#1 Post by Cazad0ra »

Hi! I'm going to try to explain the situation as best as possible:
I'm working on a storage system to go with an inventory system, so basically, I have those two different lists of game items. Transfering items is no big deal in general, my issue comes with a specific type of item that has an attribute "charges", which basically stacks for example 5 potions into 1 with 5 charges.

That's when my issue comes, since I can transfer that first potion, but I don't know how to add charges to that item specifically in the storage list.

Here's the code I currently have on the function to add the item to the storage list:

Code: Select all

def deposit(self, target):
            if self in target: #Where self is the item and target is the list
                self.charges += 1  #Here's where I need to tell RenPy to perform this action in the storage list

            else:
                target.append(self)
I hope this makes sense ^^"

User avatar
Ocelot
Lemma-Class Veteran
Posts: 2400
Joined: Tue Aug 23, 2016 10:35 am
Github: MiiNiPaa
Discord: MiiNiPaa#4384
Contact:

Re: Changing an object's attribute on a specific list

#2 Post by Ocelot »

if self in target this line will cause problem for custom objects unless you properly redefined comparison operators.
Example:

Code: Select all

class foo:
    def __init__(self):
        self.bar = 5
 
a = foo()
b = foo()
c = []
c.append(a)
a in c # True
b in c # False
As you can see, even though both a and b contain same data, one of it is considered to be in a list, and other is not. This is because default behavior of == operator is to check identity, not equality.

Now, when this is out of the way, you can search for item in list and update its value manually:

Code: Select all

for idx in range(0, len(target)):
    if target[idx].name == self.name: # Or whatever condition you use to determine if it is an item you want.
        target[idx].charges += 1
        break
else: # Yes, this else belongs to for loop, not if statement
    target.append(self)
< < insert Rick Cook quote here > >

Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Rhapsy