Skip to content

Instantly share code, notes, and snippets.

@joshka
Created April 13, 2013 16:21
Show Gist options
  • Save joshka/5379053 to your computer and use it in GitHub Desktop.
Save joshka/5379053 to your computer and use it in GitHub Desktop.
Game of life in C#
using System.Collections.Generic;
namespace GameOfLife1
{
struct Cell
{
public Cell(int x, int y) : this()
{
Y = y;
X = x;
}
int X;
int Y;
public IEnumerable<Cell> Neighbours
{
get
{
return new[]
{
new Cell(X - 1, Y - 1), new Cell(X, Y - 1), new Cell(X + 1, Y - 1),
new Cell(X - 1, Y), new Cell(X + 1, Y),
new Cell(X - 1, Y + 1), new Cell(X, Y + 1), new Cell(X + 1, Y + 1),
};
}
}
public override string ToString()
{
return string.Format("({0},{1})", X, Y);
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace GameOfLife1
{
class Generation
{
public IEnumerable<Cell> LiveCells { get; set; }
bool IsAlive(Cell cell)
{
return LiveCells.Contains(cell);
}
bool IsDead(Cell cell)
{
return !IsAlive(cell);
}
int NumberOfLiveNeighbours(Cell cell)
{
return cell.Neighbours.Where(IsAlive).Count();
}
bool StaysAlive(Cell cell)
{
var numberOfLiveNeighbours = NumberOfLiveNeighbours(cell);
return numberOfLiveNeighbours == 2 || numberOfLiveNeighbours == 3;
}
IEnumerable<Cell> CellsThatSurvive()
{
return LiveCells.Where(StaysAlive);
}
IEnumerable<Cell> NeighboursOfLiveCells()
{
return LiveCells.SelectMany(c => c.Neighbours).Distinct();
}
bool BecomesAlive(Cell cell)
{
return IsDead(cell) && NumberOfLiveNeighbours(cell) == 3;
}
IEnumerable<Cell> CellsThatReproduce()
{
return NeighboursOfLiveCells().Where(BecomesAlive);
}
public Generation NextGeneration()
{
return new Generation { LiveCells = CellsThatSurvive().Concat(CellsThatReproduce()) };
}
public override string ToString()
{
return string.Join(" ", LiveCells);
}
}
}
using System;
namespace GameOfLife1
{
class Program
{
static void Main()
{
var g = new Generation
{
LiveCells = new[]
{
new Cell(0, 1), new Cell(1, 1), new Cell(2, 1),
}
};
Console.WriteLine(g);
g = g.NextGeneration();
Console.WriteLine(g);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment