0

I am new to Python and now I'm trying to create a game called Pong

Everything looks to work fine but unfortunately, I can't remove a specific element from 2D-Array /List once the ball touches a brick.

Here is my code:

class Brick:
    size = 5
    bricks = [[0] * size for i in range(size)] 

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def createBricks(self):
        for x in range(self.size):
            for y in range(self.size):
                self.bricks[x][y] = Brick(x * 70, y * 40)

    def draw(self):
        for bricks in self.bricks:
            for brick in bricks:
                 rect(brick.x, brick.y, 50, 20)

In the following method, I want to remove the specific element:

#In my main class

def removeBrick():
    for elem in brick.bricks:
        for _brick in elem:
            if ball.touchesBrick(_brick.x, _brick.y):
               #Here I want to remove the element

I have tried many ways with remove() and del but as a result, I couldn't solve it.

Thanks in advance.

1 Answer 1

1

using for loops just gives you a copy to the element (so you can't modify it directly). To solve this problem, you should use the enumerate class:

def removeBrick():
    for elem in brick.bricks:
        for i, _brick in enumerate(elem):
            if ball.touchesBrick(_brick.x, _brick.y):
               _brick.pop(i)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer but, after running your solution it throws the following error: AttributeError: Brick instance has no attribute 'pop'
I think Amin should have written elem.pop(i) (elem is the list of Brick from which you want to remove stuff while _brick is an element of it so it doesn't have a pop method implemented).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.