Skip to content

Instantly share code, notes, and snippets.

@wireddude
Created December 21, 2024 01:54
Show Gist options
  • Save wireddude/abdd8cad9245d2b8ccffa1cfce5db7fe to your computer and use it in GitHub Desktop.
Save wireddude/abdd8cad9245d2b8ccffa1cfce5db7fe to your computer and use it in GitHub Desktop.
life.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game of Life</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 100; // Number of cells in the grid (rows and columns)
const cellSize = 5; // Size of each cell in pixels
canvas.width = gridSize * cellSize;
canvas.height = gridSize * cellSize;
// Create a 2D array for the grid
let grid = Array.from({ length: gridSize }, () => Array(gridSize).fill(0));
// Initialize the grid with random live cells
function initializeGrid() {
for (let row = 0; row < gridSize; row++) {
for (let col = 0; col < gridSize; col++) {
grid[row][col] = Math.random() > 0.8 ? 1 : 0;
}
}
}
// Draw the grid
function drawGrid() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let row = 0; row < gridSize; row++) {
for (let col = 0; col < gridSize; col++) {
ctx.fillStyle = grid[row][col] === 1 ? '#000' : '#fff';
ctx.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
}
}
}
// Get the number of live neighbors for a cell
function getLiveNeighbors(row, col) {
let count = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) continue; // Skip the cell itself
const neighborRow = (row + i + gridSize) % gridSize;
const neighborCol = (col + j + gridSize) % gridSize;
count += grid[neighborRow][neighborCol];
}
}
return count;
}
// Update the grid based on the rules of the game
function updateGrid() {
const newGrid = grid.map(arr => [...arr]);
for (let row = 0; row < gridSize; row++) {
for (let col = 0; col < gridSize; col++) {
const liveNeighbors = getLiveNeighbors(row, col);
if (grid[row][col] === 1) {
newGrid[row][col] = liveNeighbors === 2 || liveNeighbors === 3 ? 1 : 0;
} else {
newGrid[row][col] = liveNeighbors === 3 ? 1 : 0;
}
}
}
grid = newGrid;
}
// Main loop
function gameLoop() {
updateGrid();
drawGrid();
requestAnimationFrame(gameLoop);
}
// Start the game
initializeGrid();
drawGrid();
gameLoop();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment