Read the original article:Automatically trimming empty borders from generated boards
Question
How can we automatically remove fully empty rows and columns from a generated board to ensure that the playable area is centered and visually balanced?
Short Answer
This functionality is achieved through the trimEmptyBorders() method, which scans the outermost rows and columns of the board to detect completely empty sections. If any borders (top, bottom, left, or right) contain only empty cells, they are trimmed, and a new, smaller Board object is created using only the active area. This results in a compact and centered board that eliminates unnecessary empty space.
The updated code iterates over each edge of the board to determine whether it’s entirely empty, then recalculates the start and end positions for the new board dimensions. By creating a new board instance and copying only the meaningful cells, the playable area becomes properly centered.
Compared to a version without this logic, the new implementation ensures that boards do not appear off-center or surrounded by blank space, which improves both layout alignment and visual consistency.
private compactBoard(board: Board): Board {
let topEmpty = true;
let bottomEmpty = true;
let leftEmpty = true;
let rightEmpty = true;
for (let col = 0; col < board.width; col++) {
if (board.cells[0][col].getType() !== CellType.EMPTY) {
topEmpty = false;
}
if (board.cells[board.height - 1][col].getType() !== CellType.EMPTY) {
bottomEmpty = false;
}
}
for (let row = 0; row < board.height; row++) {
if (board.cells[row][0].getType() !== CellType.EMPTY) {
leftEmpty = false;
}
if (board.cells[row][board.width - 1].getType() !== CellType.EMPTY) {
rightEmpty = false;
}
}
const startRow = topEmpty ? 1 : 0;
const endRow = board.height - (bottomEmpty ? 1 : 0);
const startCol = leftEmpty ? 1 : 0;
const endCol = board.width - (rightEmpty ? 1 : 0);
if (startRow === 0 && endRow === board.height && startCol === 0 && endCol === board.width) {
return board;
}
const newWidth = endCol - startCol;
const newHeight = endRow - startRow;
const newBoard = new Board(newWidth, newHeight);
for (let row = 0; row < newHeight; row++) {
for (let col = 0; col < newWidth; col++) {
newBoard.cells[row][col] = board.cells[row + startRow][col + startCol];
}
}
return newBoard;
}
Applicable Scenarios
- When the generated board includes fully empty rows or columns around the playable area.
- To ensure that the active gameplay region remains centered on screen and visually proportional.
- To optimize rendering by reducing unnecessary empty grid cells.
- During level generation or layout adjustments, where dynamically sized boards might include unneeded empty padding.
Top comments (0)