I am trying to make a Tetris clone in Pygame. Whenever my piece locks, I have an annoying black flicker for one frame where neither the piece sprite nor the grid sprite displaying all the pieces draws the piece.
the described problem above
My current implementation works as follows: first, there’s a Piece class that generates its image and rect on the first and draws it to the screen using that. Second, there’s a Grid class that stores all the locked minos in a Numpy array. When a Piece is locked, a method in the Grid class is called to update the image of the Grid based on the contents of the numpy array, so it can be drawn to the screen. Finally, the Piece is killed. The Piece locking is detected by a Tetris class that manages both the Piece and Grid classes, and calls the relevant methods for the Grid class. Relevant code:
Inside the Piece class, when the piece is locked:
if self.lock_delay <= 0:
self.lock()
self.kill()
Inside the Tetris class, when a piece is locked:
def update_game_state(self):
if self.current_piece.locked:
self.score += self.grid.clear_lines()
self.grid.update_visual()
self.spawn_piece()
The update_visual() method of the Grid class:
def update_visual(self):
#vars for where to draw block
x_draw = 0
y_draw = 0
#copy based on cached images
for row in self.grid:
for val in row:
self.update_surface.blit(self.block_cache[val], (x_draw, y_draw))
x_draw += self.block_width
y_draw += self.block_width
x_draw = 0
self.image, self.rect = self.update_surface, self.update_surface.get_rect()
self.rect.bottomleft = (self.x,self.y)
And finally, the drawing and updating part of my game loop:
#update gamestate
tetris_game.update_game_state()
#update sprites
allsprites.update()
#draw
screen.blit(background, (0, 0))
allsprites.draw(screen)
pygame.display.flip()
I’ve tried placing the call to the kill method for the piece inside the Tetris class’ update method, but it made no difference.
cadcrafter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.