pla-01/Life/Automaton/GameOfLife.cs
2019-10-28 21:29:41 +01:00

82 lines
2.1 KiB
C#

using System;
using System.Linq;
namespace Life.Automaton
{
[Serializable]
public class GameOfLife : IAutomaton
{
[Serializable]
public class StandardRule : IRule
{
private string survive;
private string born;
public StandardRule(string born, string survive)
{
this.born = born;
this.survive = survive;
}
bool WillSurvive(int neighbours) => survive.Contains(neighbours.ToString());
bool WillBorn(int neighbours) => born.Contains(neighbours.ToString());
public Cell[,] Next(IField 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 override string ToString()
{
return $"{born}/{survive}";
}
}
public GameOfLife(int width, int height)
{
Field = new MooreField(width, height);
}
public IRule Rule { get; set; } = new StandardRule("3", "32");
public int Iteration { get; private set; }
public IField Field { get; private set; }
public void Advance()
{
Field.Transform(Rule);
Iteration++;
}
public void ReplaceField(IField field)
{
Field = field;
}
public void Reset()
{
Iteration = 0;
foreach (var cell in Field.Cells)
cell.IsAlive = false;
Field.Notify();
}
}
}