Skip to content

Instantly share code, notes, and snippets.

@DCCoder90 DCCoder90/GOL.cs
Created Jul 16, 2019

Embed
What would you like to do?
Simple Game of Life. Need to test to make sure it's following all the rules.
internal class GOL
{
private int _genCounter = 0;
private bool[,] _board;
private int _boardSize;
public void Play()
{
Initialize(30);
PrintBoard();
while(true)
Tick();
}
private void Initialize(int boardSize)
{
_boardSize = boardSize;
_board = new bool[boardSize,boardSize];
var rand = new Random();
for(int x=0;x<boardSize;x++)
for (int y = 0; y < boardSize; y++)
{
_board[x, y] = rand.Next() % 9 == 0;
}
}
private void Tick()
{
_genCounter++;
var newStates = _board;
for(int x =0;x<_boardSize;x++)
for (int y = 0; y < _boardSize; y++)
{
var state = _board[x, y];
newStates[x, y] = GetStatus(x, y, state);
}
_board = newStates;
PrintBoard();
}
private bool GetStatus(int x, int y, bool currentState)
{
int neighborCount = 0;
if ((x - 1) > 0)
{
if (_board[x - 1, y])
neighborCount++;
if ((y - 1) > 0 && _board[x - 1, y - 1])
neighborCount++;
if ((y + 1) < _boardSize && _board[x - 1, y + 1])
neighborCount++;
}
if((y-1) > 0 && _board[x, y - 1]) neighborCount++;
if((y+1)<_boardSize && _board[x, y + 1]) neighborCount++;
if ((x + 1) < _boardSize)
{
if((y-1) > 0 && _board[x + 1, y - 1]) neighborCount++;
if (_board[x + 1, y])
neighborCount++;
if((y+1)<_boardSize && _board[x + 1, y + 1]) neighborCount++;
}
/*
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with more than three live neighbours dies, as if by overpopulation.
Any dead cell with three live neighbours becomes a live cell, as if by reproduction.
*/
if (neighborCount < 2) return false;
if (neighborCount == 2) return currentState;
if (neighborCount == 3) return true;
return false;
}
public void PrintBoard()
{
Console.SetCursorPosition(0,0);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"Generation: {_genCounter}\n");
for(int x=0; x < _boardSize; x++)
{
for (int y = 0; y < _boardSize; y++)
{
if (_board[x, y] == true)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write('0');
}
else
{
Console.ForegroundColor = ConsoleColor.Black;
Console.Write('0');
}
}
Console.Write('\n');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.