using System; using System.IO; using System.Linq; using System.Runtime.Serialization; namespace Life.Automaton { [Serializable] public class GameOfLife : IAutomaton { public GameOfLife(int width, int height) { Field = 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 Advance() { Field.Transform(Rule); Iteration++; } public void ReplaceField(IField field) { Field = field; } } }