JSFiddle - React, Tailwind, and code Playground
JavaScript
// Check if the figure can be placed at a specific row and column
const canPlaceFigure = (figure, field, startRow, startCol) => {
for (let i = 0; i < figure.length; i++) {
for (let j = 0; j < figure[0].length; j++) {
if (figure[i][j] === 1 && field[startRow + i][startCol + j] === 1) {
return false; // Conflict detected
}
}
}
return true; // Placement is possible
};
// Merge the figure into the field at a specific position
const mergeFigure = (figure, field, startRow, startCol) => {
const newField = JSON.parse(JSON.stringify(field)); // Create a deep copy
for (let i = 0; i < figure.length; i++) {
for (let j = 0; j < figure[0].length; j++) {
if (figure[i][j] === 1) {
newField[startRow + i][startCol + j] = 1;
}
}
}
return newField;
};
// Check if any row in the field is fully occupied
const hasFullRow = (field) => {
for (let row = 0; row < field.length; row++) {
if (field[row].every(cell => cell === 1)) {
return true; // Full row found
}
}
return false; // No full rows
};
// Calculate the landing row for the figure in a given column
const dropCol = (figure, field, column) => {
const maxRow = field.length - figure.length;
for (let row = 0; row <= maxRow; row++) {
if (!canPlaceFigure(figure, field, row, column)) {
return row - 1; // Figure landed above the conflict
}
}
return field.length - figure.length; // Figure landed at the bottom
};
// Find the best column to drop the figure
const drop = (figure, field) => {
const fieldWidth = field[0].length;
const figureWidth = figure[0].length;
const maxDropCol = fieldWidth - figureWidth + 1;
for (let col = 0; col < maxDropCol; col++) {
const landingRow = dropCol(figure, field, col);
if (landingRow !== -1) {
const newField = mergeFigure(figure, field,...