Created
March 6, 2025 14:34
-
-
Save andrewstellman/4fd91f6fe5f0e1c8233cb043a1f9f804 to your computer and use it in GitHub Desktop.
Conway's Game of Life in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Parse command line arguments for width, height, density, and delay | |
| var width = args?.Length > 0 && int.TryParse(args[0], out int w) && w > 0 ? w : 70; | |
| var height = args?.Length > 1 && int.TryParse(args[1], out int h) && h > 0 ? h : 30; | |
| var density = args?.Length > 2 && double.TryParse(args[2], out double d) && d > 0 && d <= 1 ? d : 0.3; | |
| var delay = args?.Length > 3 && int.TryParse(args[3], out int ms) && ms >= 0 ? ms : 100; | |
| // Initialize the grid with random cells | |
| var grid = new bool[height, width]; | |
| // Fill cells randomly based on density parameter | |
| for (int y = 0; y < height; y++) | |
| for (int x = 0; x < width; x++) | |
| grid[y, x] = Random.Shared.NextDouble() < density; | |
| // Run the simulation (infinite loop) | |
| var generation = 0; | |
| while (true) | |
| { | |
| Console.Clear(); | |
| Console.WriteLine($"Conway's Game of Life - Generation {++generation} - Density: {density:F2} - Delay: {delay}ms"); | |
| // Display current state | |
| for (int y = 0; y < height; y++) | |
| { | |
| for (int x = 0; x < width; x++) | |
| Console.Write(grid[y, x] ? "█" : " "); | |
| Console.WriteLine(); | |
| } | |
| // Compute next generation | |
| var newGrid = new bool[height, width]; | |
| for (int y = 0; y < height; y++) | |
| { | |
| for (int x = 0; x < width; x++) | |
| { | |
| // Count live neighbors (8-way) | |
| int neighbors = 0; | |
| for (int dy = -1; dy <= 1; dy++) | |
| { | |
| for (int dx = -1; dx <= 1; dx++) | |
| { | |
| if (dx == 0 && dy == 0) continue; | |
| int nx = (x + dx + width) % width; | |
| int ny = (y + dy + height) % height; | |
| if (grid[ny, nx]) neighbors++; | |
| } | |
| } | |
| // Apply Game of Life rules | |
| newGrid[y, x] = neighbors == 3 || (grid[y, x] && neighbors == 2); | |
| } | |
| } | |
| // Update grid for next frame | |
| grid = newGrid; | |
| Thread.Sleep(delay); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
life.mov