-
Notifications
You must be signed in to change notification settings - Fork 4
Board Types
IReadOnlyBoard
is the base interface of types storing battleship boards.
- You can access the cells of the board with an index (see also
BoardIndex
type). -
IReadOnlyBoard
implementsIEnumerable<SquareContent>
. Therefore, you can iterate over the cells with e.g. aforeach
loop and you can use Linq to analyze the board content. - With
HasLost
you can find out whether all ships on a board are already sunken (i.e. player has lost).
Here are some examples for what you can do with IReadOnlyBoard
:
IReadOnlyBoard board;
// ...
// Access a square on the board using its index
if (board[new BoardIndex("A1")] == SquareContent.Ship)
{
// ...
}
// Iterate over board using foreach
foreach (var square in board)
{
if (square == SquareContent.Ship)
{
// ...
}
}
// Use Linq to analyze board content
var numberOfWaterCells = board.Count(s => s == SquareContent.Water);
If you want to know whether there is a ship on a given location on the board, you can use the TryFindShip
method. The method returns ShipFindingResult.NoShip
if there is no ship on the specified cell. It returns ShipFindingResult.PartialShip
if there is a ship on the specified cell, but it cannot be said for sure how long it is (because of SquareContent.Unknown
cells in front or behind the ship). If a ship was found and the size of the ship could be determined, the function returns ShipFindingResult.CompleteShip
.
IReadOnlyBoard board;
// ...
// Assumption: We have a ship on A1-C1 and we know that D1 is water.
var found = board.TryFindShip(new BoardIndex("B1"), out var shipRange);
if (found is ShipFindingResult.PartialShip or ShipFindingResult.CompleteShip)
{
Console.WriteLine($"We found a ship at location {shipRange.From}-{shipRange.To}");
}
BoardContent
implements IReadOnlyBoard
. It represents a battleship board that you can manipulate. You can assign values to square using an index. Additionally, you can generate a nicely formatted string representation of a board using ToString()
.
Note: Typically, you do not need to create a BoardContent
instance and write content to its cells. The battleship runtime maintains the board content for you and provides you with the corresponding IReadOnlyBoard
.
BoardContent board;
// ...
board[new BoardIndex("A1")] = SquareContent.Ship;