Add Life as a sequence of Gneerations

This commit is contained in:
Andrew Cooper
2022-09-13 07:56:27 +10:00
parent db186bb86e
commit a9ec4e3eb1
3 changed files with 53 additions and 22 deletions

View File

@@ -11,34 +11,16 @@ internal class Game
{ {
_io.Write(Streams.Title); _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.WriteLine();
_io.Write(generation); _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");
} }
} }

View File

@@ -56,6 +56,24 @@ internal class Generation
return new(board); 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() private void CountNeighbours()
{ {
for (var x = 1; x <= 5; x++) for (var x = 1; x <= 5; x++)

View File

@@ -0,0 +1,31 @@
using System.Collections;
internal class Life : IEnumerable<Generation>
{
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<Generation> 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();
}