conway's game of life in csharp

Conway's Game of Life is a classic cellular automaton that simulates the evolution of a group of cells on a grid based on simple rules. Here's an implementation in C#:

main.cs
using System;

class GameOfLife {
    int[,] board;
    int size;

    public GameOfLife(int size) {
        board = new int[size, size];
        this.size = size;
    }

    public void initBoard() {
        Random r = new Random();
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                board[i, j] = r.Next(2);
            }
        }
    }

    public void printBoard() {
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                Console.Write(board[i, j] == 1 ? "#" : ".");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }

    public void nextGeneration() {
        int[,] newBoard = new int[size, size];
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                int neighbors = countNeighbors(i, j);
                if ((board[i, j] == 1) && (neighbors < 2))
                    newBoard[i, j] = 0;
                else if ((board[i, j] == 1) && (neighbors > 3))
                    newBoard[i, j] = 0;
                else if ((board[i, j] == 0) && (neighbors == 3))
                    newBoard[i, j] = 1;
                else
                    newBoard[i, j] = board[i, j];
            }
        }
        board = newBoard;
    }

    private int countNeighbors(int x, int y) {
        int count = 0;
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                int row = (x + i + size) % size;
                int col = (y + j + size) % size;
                count += board[row, col];
            }
        }
        count -= board[x, y];
        return count;
    }
}

class Program {
    static void Main() {
        int size = 20;
        GameOfLife gol = new GameOfLife(size);
        gol.initBoard();
        for (int i = 0; i < 10; i++) {
            gol.printBoard();
            gol.nextGeneration();
            System.Threading.Thread.Sleep(1000);
        }
    }
}
2006 chars
75 lines

This program defines a GameOfLife class that implements the basic logic of the simulation. The initBoard() method initializes the board with random values, and the printBoard() method prints the board to the console.

The nextGeneration() method computes the next generation of the board based on the number of neighbors each cell has. The countNeighbors() method computes the number of live neighbors of a given cell, accounting for the wrap-around edges of the grid.

Finally, the Main() method creates a GameOfLife object, initializes the board and runs the simulation for 10 generations, printing the board and waiting for one second between each generation.

gistlibby LogSnag