Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andrewstellman/fd0838d1ccf81c3b39c99f7db5f45990 to your computer and use it in GitHub Desktop.
Save andrewstellman/fd0838d1ccf81c3b39c99f7db5f45990 to your computer and use it in GitHub Desktop.
Conway's Game of Life in C#
// Parse command line arguments for width, height, density, and frames
int width = args?.Length > 0 && int.TryParse(args[0], out int w) && w > 0 ? w : 70;
int height = args?.Length > 1 && int.TryParse(args[1], out int h) && h > 0 ? h : 30;
double density = args?.Length > 2 && double.TryParse(args[2], out double d) && d > 0 && d <= 1 ? d : 0.3;
int frames = args?.Length > 3 && int.TryParse(args[3], out int f) && f > 0 ? f : 500;
// Initialize the grid with random cells
bool[,] grid = new bool[height, width];
Random 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
bool[,] 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);
}
@andrewstellman
Copy link
Author

life.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment