implement conway's game of life in csharp

Conway's Game of Life is a classic simulation that demonstrates the concept of cellular automata. In this game, a grid of cells evolves over time based on a set of rules.

Here's one way to implement it in C#:

main.cs
using System;

class GameOfLife {
    static void Main() {
        int gridSize = 10;
        bool[,] grid = new bool[gridSize, gridSize];
        bool[,] newGrid = new bool[gridSize, gridSize];
        
        // initialize the grid with random values
        Random r = new Random();
        for (int i = 0; i < gridSize; i++) {
            for (int j = 0; j < gridSize; j++) {
                grid[i,j] = r.Next(2) == 0;
            }
        }
        
        // loop through generations
        while (true) {
            Console.Clear();
            DrawGrid(grid);
            
            // calculate new grid
            for (int i = 0; i < gridSize; i++) {
                for (int j = 0; j < gridSize; j++) {
                    int neighbors = CountNeighbors(grid, i, j);
                    if (grid[i,j]) {
                        newGrid[i,j] = neighbors == 2 || neighbors == 3;
                    } else {
                        newGrid[i,j] = neighbors == 3;
                    }
                }
            }
            
            // swap grids
            bool[,] temp = grid;
            grid = newGrid;
            newGrid = temp;
            
            // wait before drawing the next generation
            System.Threading.Thread.Sleep(100);
        }
    }
    
    static int CountNeighbors(bool[,] grid, int x, int y) {
        int count = 0;
        for (int i = x-1; i <= x+1; i++) {
            for (int j = y-1; j <= y+1; j++) {
                if (i >= 0 && i < grid.GetLength(0) &&
                    j >= 0 && j < grid.GetLength(1) &&
                    grid[i,j] && (i != x || j != y)) {
                    count++;
                }
            }
        }
        return count;
    }
    
    static void DrawGrid(bool[,] grid) {
        for (int i = 0; i < grid.GetLength(0); i++) {
            for (int j = 0; j < grid.GetLength(1); j++) {
                Console.Write(grid[i,j] ? "X" : ".");
            }
            Console.WriteLine();
        }
    }
}
2014 chars
67 lines

In this implementation, we use a 2D array to represent the grid. The CountNeighbors method counts the number of adjacent cells that are alive. The main loop calculates the next generation based on the current state of the grid, and then swaps the old and new grids before moving on to the next generation. Finally, we use the Console to display the grid on the console screen.

gistlibby LogSnag