Created
March 6, 2025 14:26
-
-
Save andrewstellman/2f943fb845fdc16abbd11960f455b513 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 frames | |
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 frames = args?.Length > 3 && int.TryParse(args[3], out int f) && f > 0 ? f : 500; | |
// Initialize the grid with random cells | |
var grid = new bool[height, width]; | |
var random = new Random(); | |
// 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.NextDouble() < density; | |
// Run the simulation | |
for (int frame = 0; frame < frames; frame++) | |
{ | |
Console.Clear(); | |
Console.WriteLine($"Conway's Game of Life - Frame {frame + 1} - Density: {density:F2}"); | |
// 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(100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment