1

I am trying to make a simple tetris ai in python(no genetic algorithms)

I want to count the gaps in the grid and make the best choice depending on it.

By gap I mean where you wont be able to place a piece without clearing some lines.

My grid is something like this:

[0, 0, 0, 0, 0]
['#ff0000', ....]
[...]

0 represents a blank space, while the hex code represents its covered by a block

I have tried to calculate gaps like this:

def grid_gaps(grid):
    gaps = 0
    for x in range(len(grid[0])):
        for y in range(len(grid)):
            if grid[y][x] == 0 and \
                (y > 0 and grid[y - 1][x] != 0):
                gaps += 1
    return gaps

It works good when the grid is like this:

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

1 is some color, it correctly tells me that there are 3 gaps but when the grid is someting like this:

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

It again returns 3 but I want it to return 6.

  • Can you explain what you mean by "gap" – Mark Lavin Aug 18 '21 at 16:36
  • @Mark Lavin Where you wont be able to place a piece without clearing some lines, I will edit my question accordingly – Random_Pythoneer59 Aug 18 '21 at 16:43
  • Sorry, I'm being thick... Is "gap" a number of squares, or a number of blocks of squares, or what? And... do we assume that the pieces consist of a single square? – Mark Lavin Aug 18 '21 at 16:46
  • @Mark Lavin My friend its just a block(or a cell) in the grid. And every piece in tetris covers four cells. So a gap would be a empty square which can not be covered without clearing some lines. – Random_Pythoneer59 Aug 18 '21 at 16:47

2 Answers2

1

I think the problem is that and grid[y - 1][x] != 0 is only looking at the cell directly above the current cell, so your bottom 3 cells in the second example aren't being counted.

One quick fix I can think of is to set a gap cell to some non-zero value once it's counted, that way the gap cells below will be counted too. (Then set them back to 0 after you're done, if you're using the same grid and not a copy for the rest of the game.)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

The problem is that you're looking "up" to see whether there's a blocker, but you're only looking up one row. I think you want to reorganize this so you iterate over columns, and for each column, iterate down until you hit a 1, and then continue iterating and add to the gap count for each 0 that's encountered.

Mark Lavin
  • 1,002
  • 1
  • 15
  • 30