Sliding Tiles Left
Learn how to define the rules of sliding tiles, implement compress_row, and test it thoroughly.
By the end of this lesson, you’ll be able to compress a single row for a left move. If you can do this for one row, you can apply the same logic to slide the entire board left, as shown in the illustration below.
Step 0: Starting point
We start from the end-of-lesson file from the previous lesson and highlight that compress_row is our target.
Python 3.10.4
# lesson4_compress_row_start.pyimport random# ===== Existing working functions =====def add_random_tile(board: list[list[int]]) -> None:empty_positions = [(r, c)for r in range(4)for c in range(4)if board[r][c] == 0]if not empty_positions:returnr, c = random.choice(empty_positions)board[r][c] = 4 if random.random() < 0.1 else 2def create_initial_board() -> list[list[int]]:board = [[0] * 4 for _ in range(4)]add_random_tile(board)add_random_tile(board)return boarddef render_board(board: list[list[int]]) -> str:size = len(board)cell_width = 5line = "+" + ("-" * cell_width + "+") * sizelines = [line]for r in range(size):row_text = "|"for c in range(size):val = board[r][c]text = "" if val == 0 else str(val)row_text += text.rjust(cell_width) + "|"lines.append(row_text)lines.append(line)return "\n".join(lines)# ===== Lesson 4 target function =====def compress_row(row: list[int]) -> list[int]:"""Slide non-zero tiles in the row to the LEFT, keeping their order,and move zeros to the right. Do NOT merge tiles here.Examples:[2, 0, 2, 4] -> [2, 2, 4, 0][0, 0, 2, 0] -> [2, 0, 0, 0][0, 4, 0, 4] -> [4, 4, 0, 0]"""# TODO: implement in this lessonraise NotImplementedError# ===== Still stubs for future lessons =====def merge_row(row: list[int]) -> tuple[list[int], int]:raise NotImplementedErrordef move_board(board: list[list[int]], direction: str) -> tuple[list[list[int]], int, bool]:raise NotImplementedErrordef check_game_state(board: list[list[int]], target: int = 2048) -> str:raise NotImplementedErrordef main():board = create_initial_board()score = 0print("Initial board:")print("Score:", score)print(render_board(board))# We'll add compress_row demos here later in the lesson.if __name__ == "__main__":main()
Running this will ...