Skip to content

Commit

Permalink
Add AI to automatically arrange Polyomino blocks (#16)
Browse files Browse the repository at this point in the history
* Add files via upload

* fix duplicate MainApp call

---------

Co-authored-by: Viet Nguyen <77735678+Viet281101@users.noreply.github.com>
  • Loading branch information
D-TheProgrammer and Viet281101 authored Jun 1, 2024
1 parent 7d2d3a0 commit 8ccd054
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
57 changes: 57 additions & 0 deletions 2D/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,63 @@ class MainApp {
this.redraw();
}
};

//IA POUR TILING
autoTiling() {
const polyominoes = [...this.polyominoes]; // Clone des polyominos pour ne pas les modifier
polyominoes.sort((a, b) => b.shape.flat().reduce((acc, val) => acc + val) - a.shape.flat().reduce((acc, val) => acc + val)); // trie par taille
if (this.tryPlacePolyominoes(0, polyominoes)) {
console.log("Pavage Reussi!");
} else {
console.log("Pavage Echouer!");
}
};

tryPlacePolyominoes(index, polyominoes) {
if (index >= polyominoes.length) {
return true; // Tous les polyominos sont place
}

const polyomino = polyominoes[index];

for (let row = 0; row < this.gridBoard.rows; row++) {
for (let col = 0; col < this.gridBoard.cols; col++) {
const originalX = polyomino.x;
const originalY = polyomino.y;
polyomino.x = col * this.gridSize + this.gridBoard.gridOffsetX;
polyomino.y = row * this.gridSize + this.gridBoard.gridOffsetY;

if (this.gridBoard.isInBounds(polyomino) && !this.gridBoard.isOverlapping(polyomino)) {
this.placePolyomino(polyomino);
if (this.tryPlacePolyominoes(index + 1, polyominoes)) {
return true;
}
this.gridBoard.removePolyomino(polyomino);
}

polyomino.x = originalX;
polyomino.y = originalY;
}
}

return false;
};
};

const main_app = new MainApp();
window.onload = () => {
const iaButton = document.createElement('button');
iaButton.innerText = 'IA';
iaButton.id = 'ia-button';
iaButton.style.position = 'fixed';
iaButton.style.bottom = '10px';
iaButton.style.right = '10px';
iaButton.style.padding = '10px 20px';
iaButton.style.fontSize = '16px';
iaButton.style.backgroundColor = 'blue';
iaButton.style.color = 'white';
iaButton.style.border = 'none';
iaButton.style.borderRadius = '5px';
iaButton.addEventListener('click', () => main_app.autoTiling());
document.body.appendChild(iaButton);
};
4 changes: 3 additions & 1 deletion 2D/js/polyomino.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ export const SHAPES = {
TROMINO: [[1, 1, 1]],
TETROMINO_I: [[1, 1, 1, 1]],
TETROMINO_O: [[1, 1], [1, 1]],
TETROMINO_S: [[0, 1, 1], [1, 1, 0]],
TETROMINO_T: [[0, 1, 0], [1, 1, 1]],
TETROMINO_L: [[1, 0, 0], [1, 1, 1]],
TETROMINO_J: [ [1, 1, 1], [1, 0, 0]],
TETROMINO_S: [[0, 1, 1], [1, 1, 0]],
TETROMINO_Z: [[1, 1, 0], [0, 1, 1]],
};

0 comments on commit 8ccd054

Please sign in to comment.