Objects all have the same x/y values

The function reset is shown below:

def reset(ar,ob,num):
  ar = [];
  a = 0
  while a <= num-1:
      ar[a] = ob
      a +=1
  return ar

With this function, the array coins has several objects appended to it like so-

coins = reset(coins, p(0, 0, "5", 0, [12], []), coinnum)

Then, each of those objects in the coins array has their x/y properties randomly generated with the function spawn().

for a in range(len(coins)):

The thing is, every single one of those objects is set to the exact same x/y values.
Here’s a link- https://replit.com/@arn5891/py-workspace#main.py

1 Like

@QwertyQwerty88 sorry, this topic was set to the wrong category. If you could move it to the Python section, it’d be appreciated.

1 Like

Could you please show the code for spawn()?

1 Like

Let me understand, you want to reset ar to a list containing num times ob ?

This is just done with ar = [ob] * num , so your finction is just:

def reset(ar,ob,num):
  return ar = [ob] * num

Because this is what your reset does.

@whileTRUEpass thx for shortening it, each object should be a new object, but it seems like they’re all treated like the same one.

@Firepup650 this is spawn():

 def spawn(self):
    randx = random.randint(0, len(grid.ar[0]) - 1)
    if randx > len(grid.ar[0]) - 0.5:
      self.x = math.floor(randx)
      self.x = round(randx)

    randy = random.randint(0, len(grid.ar) - 1)
    if randy > len(grid.ar) - 0.5:
      self.y = math.floor(randy)
      self.y = round(randy)

Yes they are. when you write something like ar[i] = ob, you are doing what is called a shallow copy, you are just copying the memory link to where the object is.
You need to make a deep copy, either by hand or by using copy or deepcopy.

this thread on stack exchange might help understanding the issue



Thanks. Took some editing, but it works.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.