simulate conway's game of life in csharp

Here's a possible implementation of Conway's Game of Life in C#, using a multidimensional array to represent the grid of cells:

main.cs
class GameOfLife {
    private int[,] grid;
    private int size;
    
    public GameOfLife(int size) {
        this.size = size;
        this.grid = new int[size, size];
    }
    
    public void Randomize() {
        Random rnd = new Random();
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                grid[row, col] = rnd.Next(2);
            }
        }
    }
    
    public void Run(int steps) {
        while (steps > 0) {
            int[,] nextGrid = new int[size, size];
            for (int row = 0; row < size; row++) {
                for (int col = 0; col < size; col++) {
                    int neighbors = CountNeighbors(row, col);
                    if (grid[row, col] == 1) {
                        if (neighbors < 2 || neighbors > 3) {
                            nextGrid[row, col] = 0;
                        } else {
                            nextGrid[row, col] = 1;
                        }
                    } else {
                        if (neighbors == 3) {
                            nextGrid[row, col] = 1;
                        } else {
                            nextGrid[row, col] = 0;
                        }
                    }
                }
            }
            grid = nextGrid;
            steps--;
        }
    }
    
    private int CountNeighbors(int row, int col) {
        int count = 0;
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) continue;
                int r = row + i;
                int c = col + j;
                if (r < 0 || r >= size || c < 0 || c >= size) continue;
                if (grid[r, c] == 1) count++;
            }
        }
        return count;
    }
    
    public void Print() {
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                Console.Write(grid[row, col] == 1 ? "X" : ".");
            }
            Console.WriteLine();
        }
    }
}
2042 chars
68 lines

Here's how you can use it to simulate a 10x10 grid for 10 steps:

main.cs
GameOfLife game = new GameOfLife(10);
game.Randomize();
game.Print();
game.Run(10);
game.Print();
98 chars
6 lines

This will print the initial state of the grid, run 10 steps of the simulation, and print the final state of the grid. You can adjust the size of the grid and the number of steps to simulate as needed.

gistlibby LogSnag