First

Welcome to WordPress. This is your first post. !!!! Edit or delete it, then start writing!

const canvas = document.getElementById(“game-of-life”); const ctx = canvas.getContext(“2d”); let grid = []; // Array to store cell states let gridSize = 100; // Initial grid size let speed = 5; // Initial speed // Function to create a new grid of random cells function createGrid() { grid = []; for (let i = 0; i < gridSize; i++) { grid[i] = []; for (let j = 0; j < gridSize; j++) { grid[i][j] = Math.random() < 0.5; // Randomly assign live or dead cells } } } // Function to draw the grid function drawGrid() { ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#000"; for (let i = 0; i < gridSize; i++) { for (let j = 0; j < gridSize; j++) { if (grid[i][j]) { ctx.fillRect(j * (canvas.width / gridSize), i * (canvas.height / gridSize), canvas.width / gridSize, canvas.height / gridSize); } } } } // Function to apply the Game of Life rules function updateGrid() { const nextGrid = []; for (let i = 0; i < gridSize; i++) { nextGrid[i] = []; for (let j = 0; j < gridSize; j++) { let aliveNeighbors = 0; for (let di = -1; di <= 1; di++) { for (let dj = -1; dj <= 1; dj++) { if (!(di === 0 && dj === 0) && grid[(i + di + gridSize) % gridSize][(j + dj + gridSize) % gridSize]) { aliveNeighbors++; } } } if (grid[i][j]) { nextGrid[i][j] = aliveNeighbors === 2 || aliveNeighbors === 3; // Survival rules } else { nextGrid[i][j] = aliveNeighbors === 3; // Birth rule } } } grid = nextGrid; } // Function to handle user interactions function handleControls() { const speedSlider = document.getElementById("speed-slider"); const startButton = document.getElementById("start-button"); const pauseButton = document.getElementById("pause-button"); const resetButton = document.getElementById("reset-button"); speedSlider.addEventListener("change", (event) => { speed = event.target.value; }); startButton.addEventListener(“click”, () => { setInterval(updateGrid, 1000 / speed); // Adjust speed based on slider value }); pauseButton.addEventListener(“click”, () => { clearInterval(updateGrid); }); resetButton.addEventListener(“click”, () => { createGrid(); drawGrid(); }); } createGrid(); // Create initial grid drawGrid(); // Draw initial grid handleControls(); // Set up user interactions

Comments

One response to “First”

  1. Hi, this is a comment.
    To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
    Commenter avatars come from Gravatar.

Leave a Reply

Your email address will not be published. Required fields are marked *