Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
With the game as it is now, when a row is completely filled (every cell in that row has a block), the row stays there. The board doesn’t clear the row, and blocks above don’t fall down. The play area fills up and the game becomes unplayable. So we need to detect full rows, remove those blocks, shift any blocks above down, and (optionally) add score.
Implement row clearing:
move("down") when you call update_board()), check whether any rows are full.y by 1).You can put this logic in a method like check_rows() or clear_rows() on Game, and call it from the piece’s move() when a piece has just locked (e.g. right after update_board() and before new_piece()).
check_rows() on Game (or a similar name):
game_area[1], one count per row).self.board, increment the count for that block’s row.game_area[0] (full row):
self.board every block whose row equals that row.block["location"] = (block["location"][0], block["location"][1] + 1) - but careful: if you clear multiple rows, you need to shift by how many rows were cleared below the block).check_rows() from the piece’s move() when a down collision has just happened - after update_board() and before new_piece() (so the board is up to date when we check).Game and increase it when rows are cleared; display it on the screen.rows = [0] * game_area[1]. Loop over self.board; for each block, get row = block["location"][1] and do rows[row] += 1. Then any index i where rows[i] >= game_area[0] is a full row.
full_rows = [i for i in range(len(rows)) if rows[i] >= game_area[0]]). Then: remove from self.board every block where block["location"][1] is in full_rows. Then for each remaining block, if its row r is above a cleared row, it must move down: count how many cleared rows are below r (cleared rows with index > r), and add that count to r when you set the new location.
new_row = old_row + (number of full rows that were below old_row). Option B is cleaner for multiple rows.
Play until you fill a row. When a row becomes full, it should disappear and blocks above should fall. That moment - the row vanishing and the score going up - is the payoff: you wrote the logic that makes it happen. Try clearing two or more rows at once (a “tetris”) and watch your code handle it. Compare with the solution when ready.
You’ve finished Tutorial 1.1. ← Back to Tutorial 1.1