Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const grid = document.getElementById("grid");
- const gridSize = 20;
- let cells = [];
- function createGrid() {
- for (let y = 0; y < gridSize; y++) {
- cells[y] = [];
- for (let x = 0; x < gridSize; x++) {
- const cell = document.createElement("div");
- cell.className = 'cell dead';
- cell.addEventListener('click', () => toggleCell(x, y));
- grid.appendChild(cell);
- cells[y][x] = 'dead';
- }
- }
- }
- function toggleCell(x, y) {
- const cellTypes = ['dead', 'introvert', 'extrovert', 'reproducer', 'killer'];
- let currentIndex = cellTypes.indexOf(cells[y][x]);
- let nextIndex = (currentIndex + 1) % cellTypes.length;
- cells[y][x] = cellTypes[nextIndex];
- document.querySelectorAll('.cell')[y * gridSize + x].className = `cell ${cellTypes[nextIndex]}`;
- }
- function nextGeneration() {
- const newCells = JSON.parse(JSON.stringify(cells));
- for (let y = 0; y < gridSize; y++) {
- for (let x = 0; x < gridSize; x++) {
- const neighbors = getNeighbors(x, y);
- const currentType = cells[y][x];
- const countType = countNeighborTypes(neighbors);
- switch (currentType) {
- case 'dead':
- if (countType.reproducer >= 1) newCells[y][x] = 'dead'; // Dead cells are revived only by reproducers
- break;
- case 'introvert':
- if (countType.introvert + countType.extrovert + countType.reproducer + countType.killer > 3 ||
- countType.killer > 0) newCells[y][x] = 'dead';
- break;
- case 'extrovert':
- if (neighbors.length === 0) newCells[y][x] = 'dead';
- break;
- case 'reproducer':
- if (neighbors.length === 0) newCells[y][x] = 'dead';
- else newCells[y][x] = 'reproducer'; // Reproducers clone themselves but die if isolated
- break;
- case 'killer':
- if (neighbors.length <= 2 || countType.introvert + countType.extrovert + countType.reproducer + countType.killer >= 3)
- newCells[y][x] = 'dead'; // Killers die if overcrowded or insufficient neighbors
- break;
- }
- }
- }
- cells = newCells;
- updateGrid();
- }
- function getNeighbors(x, y) {
- const neighbors = [];
- for (let dx = -1; dx <= 1; dx++) {
- for (let dy = -1; dy <= 1; dy++) {
- let nx = x + dx, ny = y + dy;
- if (dx === 0 && dy === 0) continue;
- if (nx >= 0 && ny >= 0 && nx < gridSize && ny < gridSize) {
- neighbors.push(cells[ny][nx]);
- }
- }
- }
- return neighbors;
- }
- function countNeighborTypes(neighbors) {
- let count = { introvert: 0, extrovert: 0, reproducer: 0, killer: 0, dead:0 };
- for (const type of neighbors) {
- if (count.hasOwnProperty(type)) {
- count[type]++;
- }
- }
- return count;
- }
- function updateGrid() {
- for (let y = 0; y < gridSize; y++) {
- for (let x = 0; x < gridSize; x++) {
- const cellIndex = y * gridSize + x;
- const cellType = cells[y][x];
- document.querySelectorAll('.cell')[cellIndex].className = `cell ${cellType}`;
- }
- }
- }
- createGrid();
Advertisement
Add Comment
Please, Sign In to add comment