Move neighbour count to generation calculation

This commit is contained in:
Andrew Cooper
2022-09-09 07:57:51 +10:00
parent 3042247e06
commit 8994d9b03c
3 changed files with 21 additions and 12 deletions

View File

@@ -34,6 +34,8 @@ internal class Board
public int Player1Count => _cellCounts[Player1];
public int Player2Count => _cellCounts[Player2];
internal bool IsEmptyAt(Coordinates coordinates) => (this[coordinates] & PieceMask) == Empty;
public string? Result =>
(Player1Count, Player2Count) switch
{
@@ -43,6 +45,12 @@ internal class Board
_ => null
};
internal void ClearCell(Coordinates coordinates) => this[coordinates] = Empty;
internal void AddPlayer1Piece(Coordinates coordinates) => this[coordinates] = Player1;
internal void AddPlayer2Piece(Coordinates coordinates) => this[coordinates] = Player2;
public void CalculateNextGeneration()
{
_cellCounts[Empty] = _cellCounts[Player1] = _cellCounts[Player2] = 0;
@@ -63,9 +71,11 @@ internal class Board
_cellCounts[newValue]++;
}
}
CountNeighbours();
}
public void CalculateNeighbours()
private void CountNeighbours()
{
for (var x = 1; x <= 5; x++)
{
@@ -97,7 +107,7 @@ internal class Board
}
private string GetDisplay(int x, int y) =>
(x, y, this[x, y]) switch
(x, y, this[x, y] & PieceMask) switch
{
(0 or 6, _, _) => $" {y % 6} ",
(_, 0 or 6, _) => $" {x % 6} ",

View File

@@ -1,18 +1,18 @@
internal class Game
{
private readonly IReadWrite _io;
private readonly Board _board;
public Game(IReadWrite io)
{
_io = io;
_board = new Board();
}
public void Play()
{
_io.Write(Streams.Title);
var _board = new Board();
for (var _player = 1; _player <= 2; _player++)
{
var P1 = _player == 2 ? 0x30 : 0x03;
@@ -28,9 +28,8 @@ internal class Game
while(true)
{
_io.WriteLine();
_board.CalculateNeighbours();
_board.CalculateNextGeneration();
_io.WriteLine();
_board.Display(_io);
if (_board.Result is not null) { break; }
@@ -42,12 +41,12 @@ internal class Game
{
_io.Write(Streams.SameCoords);
// This is a bug existing in the original code. The line should be _board[_coordinates[_player]] = 0;
_board[player1Coordinate + 1] = 0;
_board.ClearCell(player1Coordinate + 1);
}
else
{
_board[player1Coordinate] = 0x0100;
_board[player2Coordinate] = 0x1000;
_board.AddPlayer1Piece(player1Coordinate);
_board.AddPlayer2Piece(player2Coordinate);
}
}

View File

@@ -12,7 +12,7 @@ internal static class IOExtensions
{
io.WriteLine("X,Y");
var values = io.Read2Numbers("&&&&&&\r");
if (Coordinates.TryCreate(values, out var coordinates) && board[coordinates] == 0)
if (Coordinates.TryCreate(values, out var coordinates) && board.IsEmptyAt(coordinates))
{
return coordinates;
}