From 41bd08f25c22fa2b31067e7ee380a7fa628e8d80 Mon Sep 17 00:00:00 2001 From: Andreas Schaafsma Date: Sat, 4 Oct 2025 01:12:34 +0200 Subject: [PATCH] Implement line clearing --- tetris.c | 43 +++++++++++++++++++++++++++++++++++++++++++ tetris.h | 3 +++ 2 files changed, 46 insertions(+) diff --git a/tetris.c b/tetris.c index 5688f58..2454c39 100644 --- a/tetris.c +++ b/tetris.c @@ -93,6 +93,48 @@ void zero_piece_mask(){ } } +void bool_array_fill(bool* target, int len, bool val){ + for(int i = 0; i < len; i++){ + target[i] = val; + } +} + +void get_filled_lines(bool* target){ + bool_array_fill(target, BOARD_HEIGHT, 0); + bool filled_line_array[BOARD_WIDTH] = {[0 ... BOARD_WIDTH-1] = 1}; + // loop over board lines + for(int iter_y = 0; iter_y < BOARD_HEIGHT; iter_y++){ + if(memcmp(board_mask[iter_y], filled_line_array, sizeof(bool)*BOARD_WIDTH) == 0){ + target[iter_y] = 1; + continue; + } + } +} + +void clear_lines(){ + bool filled_lines[BOARD_HEIGHT] = {0}; + get_filled_lines(filled_lines); + int offset_lines = 0; // count the offset we need to keep when checking the rest of the lines + for(int line = BOARD_HEIGHT - 1; line > 0; line--){ + + int hitline = line+offset_lines; + if(!filled_lines[line]) // The line we are iterating over is not filled + { + continue; + } + + // shift all lines down one starting at hitline + for(int shift_line = hitline; shift_line > 0; shift_line--){ + for(int iter_x = 0; iter_x < BOARD_WIDTH; iter_x++){ + board[shift_line][iter_x] = board[shift_line-1][iter_x]; + board_mask[shift_line][iter_x] = board_mask[shift_line-1][iter_x]; + } + } + // All the lines are now shifted down (moved to higher index) so we need to start shifting offset by +1 now. + offset_lines++; + } +} + void populate_board_mask(){ for(int i = 0; i < BOARD_HEIGHT; i++){ for(int j = 0; j < BOARD_WIDTH; j++){ @@ -399,6 +441,7 @@ void game_tick(){ place_piece(); zero_piece_mask(); populate_board_mask(); + clear_lines(); spawn_piece(); } diff --git a/tetris.h b/tetris.h index a0882e8..be94811 100644 --- a/tetris.h +++ b/tetris.h @@ -161,6 +161,9 @@ void game_tick(); void debugDraw(int x, int y, Color color); void debug_draw_blocks(Vector2 block_vecs[], Color color); void debug_draw_blocks_on_axis(Vector2 block_vecs[], Color color); +void bool_array_fill(bool* target, int len, bool val); +void get_filled_lines(bool* target); +void clear_lines(); void draw(); void update(); void init_game();