67 lines
1.8 KiB
C#
67 lines
1.8 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 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;
|
|
}
|
|
}
|
|
} |