All files grid.ts

100% Statements 28/28
100% Branches 6/6
100% Functions 11/11
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 4612x   1x 17x   8x   1x   1x 1x 4x 1x       1x 2x   2x 6x           2x       1x 1x   1x 1x 14x 6x 3x 3x 3x       1x    
// TODO optimization: use '' for empty blocks, undefined as a sentinel
 
export const create = (width, height) =>
    Array(height).fill([]).map(() => Array(width).fill(undefined))
 
export const clone = grid => [...grid.map(row => [...row])]
 
export const draw = (grid, x: number, y: number, block, rotation: number, color) => {
    // TODO doesn't need to be pure, clone in caller
    const bucket1 = clone(grid)
    block.coords[rotation].forEach(([xx, yy]) =>
        bucket1[y + yy][x + xx] = color)
    return bucket1
}
 
// check for free, return true if so
export const check = (grid, x, y, block, rotation) => {
    const [width, height] = [grid[0].length, grid.length]
 
    const predicate = ([xx, yy]) =>
        x + xx >= 0 &&
        x + xx < width &&
        y + yy >= 0 &&
        y + yy < height &&
        grid[y + yy][x + xx] === undefined
 
    return block.coords[rotation].every(predicate)
}
 
// clear full lines (non pure)
export const sweep = grid => {
    let linesCleared = 0
 
    const width = grid[0].length
    for (const [rowIndex, row] of grid.entries()) {
        const full = row.every(cell => cell !== undefined)
        if (full) {
            grid.splice(rowIndex, 1)
            grid.unshift(new Array(width).fill(undefined))
            linesCleared++
        }
    }
 
    return linesCleared
}