2

I've been looking at this problem for awhile now and have draw a blank so would appreciate some help.

I'm making a simple Tetris clone using Python and Pygame. The problem is that the process of detecting completed rows sometimes adds a cloned row to the new GRID so anything effecting the original also effects the cloned row too.

here is the code for removing completed rows:

# create an empty grid
newGRID = []

fullRowsCount = 0
for row in reversed(GRID):
    # count number of non-zero blocks in row
    rowBlockCount = sum(col > 0 for col in row)
    
    # if number of non-zero blocks is less than the width of grid then copy to newGRID
    if rowBlockCount < GRID_SIZE.width:

        # insert non-full row into newGRID
        newGRID.insert(0, row)

    else:
        # increment this counter in order to know number of blank rows to add to top of newGRID
        fullRowsCount += 1

# if there are any full rows then they're not included in newGRID so blank rows need adding to the top
if fullRowsCount:
    newGRID = [[0] * GRID_SIZE.width] * fullRowsCount + newGRID
    # update GRID to the newGRID
    GRID = newGRID

Thank you for your time :)

cookertron
  • 188
  • 12
  • Basically there's a 2D list called GRID which contains the stack data. By stack I mean once a shape has stopped it's data is added to the GRID so basic collision detection can take place. Even if newGRID.insert(0, row[:]) is used wouldn't that still be creating a clone albeit not entangled with the orignal? – cookertron Apr 25 '21 at 14:50
  • This is the full code https://pastebin.com/W1xXjMCU. The code above starts at line 362 – cookertron Apr 25 '21 at 14:54

1 Answers1

2

The statement

newGRID = [[0] * GRID_SIZE.width] * fullRowsCount + newGRID

does not do what you expect. It creates 1 column, which is shared by all rows in the grid.

Note, the output of the following code

newGRID = [[0] * 3] * 3
newGRID[0][0] = 1
print(newGRID)

is

[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

You have to create a new column for each row:

newGRID = [[0] * GRID_SIZE.width for _ in range(fullRowsCount + newGRID)]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174