63 lines
1.9 KiB
JavaScript
63 lines
1.9 KiB
JavaScript
|
class GameOfLife {
|
||
|
constructor(width, height) {
|
||
|
this.width = width;
|
||
|
this.height = height;
|
||
|
this.grid = new Array(height).fill(null).map(() => new Array(width).fill(0));
|
||
|
}
|
||
|
|
||
|
// Initialise la grille avec l'état de départ
|
||
|
setInitialState(initialStateString) {
|
||
|
this.grid = new Array(this.height).fill(null).map(() => new Array(this.width).fill(0));
|
||
|
const liveCells = initialStateString.split(';').map(cell => cell.split(','));
|
||
|
liveCells.forEach(([x, y]) => {
|
||
|
const cellX = parseInt(x);
|
||
|
const cellY = parseInt(y);
|
||
|
if (cellX >= 0 && cellX < this.width && cellY >= 0 && cellY < this.height) {
|
||
|
this.grid[cellY][cellX] = 1;
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// Calcule le nombre de voisins vivants d'une cellule
|
||
|
getNumberActiveNeighbourCells(x, y) {
|
||
|
let count = 0;
|
||
|
for (let i = -1; i <= 1; i++) {
|
||
|
for (let j = -1; j <= 1; j++) {
|
||
|
if (i === 0 && j === 0) continue;
|
||
|
|
||
|
const neighborX = x + j;
|
||
|
const neighborY = y + i;
|
||
|
|
||
|
if (neighborX >= 0 && neighborX < this.width && neighborY >= 0 && neighborY < this.height) {
|
||
|
count += this.grid[neighborY][neighborX];
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return count;
|
||
|
}
|
||
|
|
||
|
// Calcule la génération suivante
|
||
|
computeNextGeneration() {
|
||
|
const nextGrid = new Array(this.height).fill(null).map(() => new Array(this.width).fill(0));
|
||
|
|
||
|
for (let y = 0; y < this.height; y++) {
|
||
|
for (let x = 0; x < this.width; x++) {
|
||
|
const liveNeighbors = this.getNumberActiveNeighbourCells(x, y);
|
||
|
const cellState = this.grid[y][x];
|
||
|
|
||
|
if (cellState === 1) {
|
||
|
// Règle 2 : Cellule vivante
|
||
|
if (liveNeighbors === 2 || liveNeighbors === 3) {
|
||
|
nextGrid[y][x] = 1;
|
||
|
}
|
||
|
} else {
|
||
|
// Règle 1 : Cellule morte
|
||
|
if (liveNeighbors === 3) {
|
||
|
nextGrid[y][x] = 1;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
this.grid = nextGrid;
|
||
|
}
|
||
|
}
|