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:
JavaScript
x
19
19
1
class Brick:
2
size = 5
3
bricks = [[0] * size for i in range(size)]
4
5
def __init__(self, x, y):
6
self.x = x
7
self.y = y
8
9
def createBricks(self):
10
for x in range(self.size):
11
for y in range(self.size):
12
self.bricks[x][y] = Brick(x * 70, y * 40)
13
14
def draw(self):
15
for bricks in self.bricks:
16
for brick in bricks:
17
rect(brick.x, brick.y, 50, 20)
18
19
In the following method, I want to remove the specific element:
JavaScript
1
8
1
#In my main class
2
3
def removeBrick():
4
for elem in brick.bricks:
5
for _brick in elem:
6
if ball.touchesBrick(_brick.x, _brick.y):
7
#Here I want to remove the element
8
I have tried many ways with remove() and del but as a result, I couldn’t solve it.
Thanks in advance.
Advertisement
Answer
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:
JavaScript
1
6
1
def removeBrick():
2
for elem in brick.bricks:
3
for i, _brick in enumerate(elem):
4
if ball.touchesBrick(_brick.x, _brick.y):
5
_brick.pop(i)
6