Drops figure into field, checks for full rows
JavaScript
const canPlaceFigure = (figure, field, row, col) => {
for (let i = 0; i < figure.length; i++) {
for (let j = 0; j < figure[0].length; j++) {
if (figure[i][j] === 1 && field[row + i][col + j] === 1) {
// Blocked.
return false;
}
}
}
return true;
};
const dropCol = (figure, field, col) => {
const maxRow = field.length - figure.length;
for (let row = 0; row <= maxRow; row++) {
if (!canPlaceFigure(figure, field, row, col)) {
// Return the last row that was valid.
return row - 1;
}
}
// Return the bottom row where figure landed.
return field.length - figure.length;
};
const mergeFigure = (figure, field, row, col) => {
const newField = JSON.parse(JSON.stringify(field));
for (let i = 0; i < figure.length; i++) {
for (let j = 0; j < figure[0].length; j++) {
if (figure[i][j] === 1) {
newField[row + i][col + j] = 1;
}
}
}
return newField;
};
const hasFullRow = field => {
for (let row = 0; row < field.length; row++) {
// Check if every cell in this row is 1.
if (field[row].every(cell => cell === 1)) {
return true;
}
}
return false;
};
const drop = (figure, field) => {
const figureHeight = figure.length;
const figureWidth = figure[0].length;
const fieldHeight = field.length
const fieldWidth = field[0].length;
const maxDropCol = fieldWidth - figureWidth + 1;
for (let col = 0; col < maxDropCol; col++) {
const landingRow = dropCol(figure, field, col);
if (landingRow !== -1) {
// Merge the figure into the field at this row and col.
const newField = mergeFigure(figure, field, landingRow, col);
if (hasFullRow(newField)) {
return col;
}
}
}
return -1;
};
field = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 0, 0],
[1, 1, 0]];
figure = [[0, 0, 1],
[0, 1, 1],
[0, 0, 1]];
...