diff --git a/56_Life_for_Two/csharp/Game.cs b/56_Life_for_Two/csharp/Game.cs index caa613f3..de6cb5a5 100644 --- a/56_Life_for_Two/csharp/Game.cs +++ b/56_Life_for_Two/csharp/Game.cs @@ -11,34 +11,16 @@ internal class Game { _io.Write(Streams.Title); - var generation = Generation.Create(_io); + var life = new Life(_io); - _io.Write(generation); + _io.Write(life.FirstGeneration); - while(true) + foreach (var generation in life) { - generation = generation.CalculateNextGeneration(); _io.WriteLine(); _io.Write(generation); - - if (generation.Result is not null) { break; } - - var player1Coordinate = _io.ReadCoordinates(1, generation.Board); - var player2Coordinate = _io.ReadCoordinates(2, generation.Board); - - if (player1Coordinate == player2Coordinate) - { - _io.Write(Streams.SameCoords); - // This is a bug existing in the original code. The line should be _board[_coordinates[_player]] = 0; - generation.Board.ClearCell(player1Coordinate + 1); - } - else - { - generation.Board.AddPlayer1Piece(player1Coordinate); - generation.Board.AddPlayer2Piece(player2Coordinate); - } } - _io.WriteLine(generation.Result); + _io.WriteLine(life.Result ?? "No result"); } } diff --git a/56_Life_for_Two/csharp/Generation.cs b/56_Life_for_Two/csharp/Generation.cs index 1335df34..26f8189e 100644 --- a/56_Life_for_Two/csharp/Generation.cs +++ b/56_Life_for_Two/csharp/Generation.cs @@ -55,6 +55,24 @@ internal class Generation return new(board); } + + public void AddPieces(IReadWrite io) + { + var player1Coordinate = io.ReadCoordinates(1, _board); + var player2Coordinate = io.ReadCoordinates(2, _board); + + if (player1Coordinate == player2Coordinate) + { + io.Write(Streams.SameCoords); + // This is a bug existing in the original code. The line should be _board[_coordinates[_player]] = 0; + _board.ClearCell(player1Coordinate + 1); + } + else + { + _board.AddPlayer1Piece(player1Coordinate); + _board.AddPlayer2Piece(player2Coordinate); + } + } private void CountNeighbours() { diff --git a/56_Life_for_Two/csharp/Life.cs b/56_Life_for_Two/csharp/Life.cs new file mode 100644 index 00000000..7848a348 --- /dev/null +++ b/56_Life_for_Two/csharp/Life.cs @@ -0,0 +1,31 @@ +using System.Collections; + +internal class Life : IEnumerable +{ + private readonly IReadWrite _io; + + public Life(IReadWrite io) + { + _io = io; + FirstGeneration = Generation.Create(io); + } + + public Generation FirstGeneration { get; } + public string? Result { get; private set; } + + public IEnumerator GetEnumerator() + { + var current = FirstGeneration; + while (current.Result is null) + { + current = current.CalculateNextGeneration(); + yield return current; + + if (current.Result is null) { current.AddPieces(_io); } + } + + Result = current.Result; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} \ No newline at end of file