pla-01/Life/Automaton/GameOfLife.cs
2019-10-26 19:23:37 +02:00

55 lines
1.5 KiB
C#

using System.Linq;
namespace Life.Automaton
{
public class GameOfLife : IAutomaton
{
public GameOfLife(int width, int height)
{
Initialize(new MooreField(width, height));
}
public static Rule MakeRule(string born, string survive)
{
bool WillSurvive(int neighbours) => survive.Contains(neighbours.ToString());
bool WillBorn(int neighbours) => born.Contains(neighbours.ToString());
return field =>
{
var @new = new Cell[field.Size.Width, field.Size.Height];
for (int i = 0; i < field.Size.Width; i++)
{
for (int j = 0; j < field.Size.Height; j++)
{
var neighbours = field.Neighbours(i, j).Count(c => c.IsAlive);
@new[i,j] = new Cell
{
IsAlive = field[i,j].IsAlive ? WillSurvive(neighbours) : WillBorn(neighbours)
};
}
}
return @new;
};
}
public Rule Rule { get; set; } = MakeRule("3", "32");
public int Iteration { get; private set; }
public IField Field { get; private set; }
public void Initialize(IField field)
{
Field = field;
}
public void Advance()
{
Field.Transform(Rule);
Iteration++;
}
}
}