0

I have a list of rect objects which is randomly generated and i want to take a specific element out of the list with .remove(), how would I be able to do something like that? Here's the snippet:

map = [(x, y) for x in range(0,20) for y in range(0,20)]

def cellGen():
    global mObj
    xr = random.randint(1,21)
    yr = random.randint(1,21)
    tp = (xr,yr)
    if tp in map:
        cell = pygame.Rect(tp\[0\]\*20, tp\[1\]\*20, 20, 20)
        pygame.draw.rect(window, (0,0,0), cell)
        mObj.append(cell)

.

.

.

#k2 is a set of dictionary keys in a list; valCel is all the valid rectangles' coordinates (tuples )in a list
for values in k2:

    if (values[0],values[1]) in valCel:
    
        valCel.remove((values[0],values[1]))
        #if (values[0],values[1]) in mObj:
        mObj.remove((values[0],values[1],20,20))

ValueError: list.remove(x): x not in list

here's mObj's output: [<rect(300, 200, 20, 20)>, <rect(160, 300, 20, 20)>, <rect(380, 120, 20, 20)>, <rect(300, 300, 20, 20)>, <rect(60, 140, 20, 20)>, <rect(100, 20, 20, 20)>, <rect(100, 140, 20, 20)>, <rect(80, 280, 20, 20)>, <rect(320, 380, 20, 20)>, <rect(40, 380, 20, 20)>, <rect(220, 160, 20, 20)>, <rect(140, 200, 20, 20)>, <rect(40, 20, 20, 20)>, <rect(240, 120, 20, 20)>, <rect(100, 220, 20, 20)>, <rect(200, 200, 20, 20)>, <rect(40, 240, 20, 20)>, <rect(100, 40, 20, 20)>, <rect(380, 20, 20, 20)>, <rect(320, 220, 20, 20)>, <rect(60, 260, 20, 20)>, <rect(60, 20, 20, 20)>, <rect(360, 40, 20, 20)>, <rect(360, 320, 20, 20)>, <rect(40, 260, 20, 20)>, <rect(220, 20, 20, 20)>, <rect(160, 140, 20, 20)>, <rect(160, 380, 20, 20)>, <rect(100, 240, 20, 20)>, <rect(300, 260, 20, 20)>, <rect(180, 380, 20, 20)>, <rect(380, 380, 20, 20)>, <rect(240, 60, 20, 20)>, <rect(60, 40, 20, 20)>, <rect(100, 60, 20, 20)>, <rect(160, 260, 20, 20)>, <rect(360, 300, 20, 20)>, <rect(300, 40, 20, 20)>, <rect(160, 360, 20, 20)>, <rect(40, 140, 20, 20)>, <rect(280, 380, 20, 20)>, <rect(380, 60, 20, 20)>]

How would i be able to take <rect(40, 140, 20, 20)> out of the list without calling the index of the element?

1 Answers1

0

The objects in list are of the type pygame.Rect so you have to pass the right object type to it be found. I suggest check if object is in list before call the remove function also.

for values in k2:

    if (values[0],values[1]) in valCel:
    
        valCel.remove((values[0],values[1]))
        object = pygame.Rect(values[0], values[1], 20, 20)
        if object in mObj:
        mObj.remove(object)