Zasada jako interfejs a nie delegat

"
This commit is contained in:
Kacper Donat 2019-10-28 18:44:10 +01:00
parent af2568a913
commit 5240ef7ce6
6 changed files with 31 additions and 20 deletions

View File

@ -13,6 +13,7 @@
<e p="GameOfLife.cs" t="Include" />
<e p="IAutomaton.cs" t="Include" />
<e p="IField.cs" t="Include" />
<e p="IRule.cs" t="Include" />
<e p="MooreField.cs" t="Include" />
</e>
<e p="AutomatonField.xaml" t="Include" />

View File

@ -40,9 +40,9 @@ namespace Life.Automaton
public abstract IEnumerable<Cell> Neighbours(int x, int y);
public void Transform(Rule transform)
public void Transform(IRule rule)
{
_cells = transform(this);
_cells = rule.Next(this);
Notify();
}

View File

@ -1,24 +1,27 @@
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)
[Serializable]
public class StandardRule : IRule
{
Field = new MooreField(width, height);
}
private string survive;
private string born;
public StandardRule(string born, string survive)
{
this.born = born;
this.survive = survive;
}
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 =>
public Cell[,] Next(IField field)
{
var @new = new Cell[field.Size.Width, field.Size.Height];
@ -36,10 +39,15 @@ namespace Life.Automaton
}
return @new;
};
}
}
public GameOfLife(int width, int height)
{
Field = new MooreField(width, height);
}
public Rule Rule { get; set; } = MakeRule("3", "32");
public IRule Rule { get; set; } = new StandardRule("3", "32");
public int Iteration { get; private set; }

View File

@ -4,7 +4,6 @@ using Life.Misc;
namespace Life.Automaton
{
public delegate Cell[,] Rule(IField old);
public interface IField : IObservable<IField>
{
@ -16,7 +15,7 @@ namespace Life.Automaton
IEnumerable<Cell> Neighbours(int x, int y);
void Transform(Rule rule);
void Transform(IRule rule);
void Notify();
void Resize(int width, int height);

7
Life/Automaton/IRule.cs Normal file
View File

@ -0,0 +1,7 @@
namespace Life.Automaton
{
public interface IRule
{
Cell[,] Next(IField old);
}
}

View File

@ -147,11 +147,7 @@ namespace Life.ViewModel
if (dialog.ShowDialog() == true)
{
using var file = dialog.OpenFile();
var field = _formatter.Deserialize(file) as IField;
Automaton.ReplaceField(field);
OnPropertyChanged(nameof(Field));
Automaton = _formatter.Deserialize(file) as IAutomaton;
}
}
@ -162,7 +158,7 @@ namespace Life.ViewModel
if (dialog.ShowDialog() == true)
{
using var file = dialog.OpenFile();
_formatter.Serialize(file, Field);
_formatter.Serialize(file, Automaton);
}
}
}