conway's game in javascript

Here's a simple implementation of Conway's Game of Life using JavaScript and HTML canvas:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Conway's Game of Life</title>
	<style type="text/css">
		canvas {
			background-color: #333;
		}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>
	<script>
		var canvas = document.getElementById("canvas");
		var ctx = canvas.getContext("2d");

		var grid = [];
		var cellSize = 10;
		var numRows = canvas.height / cellSize;
		var numCols = canvas.width / cellSize;

		// Initialize the grid with random cells
		for (var i = 0; i < numRows; i++) {
			grid[i] = [];
			for (var j = 0; j < numCols; j++) {
				grid[i][j] = Math.floor(Math.random() * 2);
			}
		}

		// Draw the grid on the canvas
		function drawGrid() {
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			ctx.fillStyle = "#fff";
			for (var i = 0; i < numRows; i++) {
				for (var j = 0; j < numCols; j++) {
					if (grid[i][j] === 1) {
						ctx.fillRect(j * cellSize, i * cellSize, cellSize, cellSize);
					}
				}
			}
		}

		// Get the number of neighbors for a given cell
		function getNumNeighbors(row, col) {
			var numNeighbors = 0;
			for (var i = -1; i <= 1; i++) {
				for (var j = -1; j <= 1; j++) {
					if (i === 0 && j === 0) {
						continue;
					}
					if (row + i < 0 || row + i >= numRows || col + j < 0 || col + j >= numCols) {
						continue;
					}
					if (grid[row + i][col + j] === 1) {
						numNeighbors++;
					}
				}
			}
			return numNeighbors;
		}

		// Update the grid according to the rules of the game
		function updateGrid() {
			var newGrid = [];
			for (var i = 0; i < numRows; i++) {
				newGrid[i] = [];
				for (var j = 0; j < numCols; j++) {
					var numNeighbors = getNumNeighbors(i, j);
					if (grid[i][j] === 1) {
						if (numNeighbors < 2 || numNeighbors > 3) {
							newGrid[i][j] = 0;
						} else {
							newGrid[i][j] = 1;
						}
					} else {
						if (numNeighbors === 3) {
							newGrid[i][j] = 1;
						} else {
							newGrid[i][j] = 0;
						}
					}
				}
			}
			grid = newGrid;
		}

		// Run the game loop
		function gameLoop() {
			drawGrid();
			updateGrid();
			setTimeout(gameLoop, 100);
		}

		gameLoop();
	</script>
</body>
</html>
2143 chars
99 lines

This implementation creates a grid of cells with random initial states, and updates the grid on a loop according to the rules of the Game of Life. The HTML canvas is used to display the grid. The drawGrid function draws the cells on the canvas, and the updateGrid function determines the state of each cell based on the number of neighbors it has. The loop is controlled by the gameLoop function, which repeats the process every 100 milliseconds.

gistlibby LogSnag