Skip to content

Board Index

Rainer Stropek edited this page Oct 9, 2020 · 3 revisions

The BoardIndex Struct

Introduction

The BoardIndex structure is used as an index in Battleship game boards.

Basic Usage

IReadOnlyBoard board; // Assuption: `board` is any battleship board (`IReadOnlyBoard` or derived type)
// ...

var ix = new BoardIndex("B1");
Console.WriteLine(board[ix]);

// BoardIndex can be created from a string, so you can also write:
Console.WriteLine(board["B1"]);

Creation

// Constructors
var ix1 = new BoardIndex();         // Index referring to first square (A1)
var ix2 = new BoardIndex(10);       // Zero-based index; refers to square A2
var ix3 = new BoardIndex(0, 1);     // Zero-based column and row index; refers to A2
var ix4 = new BoardIndex("A1");     // Speaks for itself
var ix5 = new BoardIndex('A', 1);   // Speaks for itself

// Parsing
var location = "A1";
if (BoardIndex.TryParse(location, out var ix6)) { /* ... */ }

Conversion

var ix7 = (BoardIndex)"A1";
var squareNumber = (int)ix7;        // Turns BoardIndex into zero-based square number
var (col, row) = ix7;               // Deconstruction

Comparison

if (ix6 == ix7) { /* ... */ }
if (ix6 != ix7) { /* ... */ }

Navigation

var ix = new BoardIndex();          // A1
ix = ix.Next();                     // Moves to B1 (will wrap between rows)
ix++;                               // Moves to C1 (will wrap between rows)
ix = ix.NextColumn();               // Moves to D1
ix = ix.NextRow();                  // Moves to D2

ix = ix.PreviousRow();              // Moves to D1
ix = ix.PreviousColumn();           // Moves to C1
ix--;                               // Moves to B1 (will wrap between rows)
ix = ix.Previous();                 // Moves to A1 (will wrap between rows)

if (TryNext(Direction.Horizontal, out var next)) { /* ... */ }
if (TryPrevious(Direction.Horizontal, out var prev)) { /* ... */ }

BoardIndexRange

BoardIndexRange is a helper class related to BoardIndex. With BoardIndexRange, you can store a range of cells on the board by specifying start index and end index. BoardIndex is typically used to represent the location of a ship on a board.

BoardIndex implements IEnumerable<BoardIndex>. Therefore you can enumerate the board index values between start and end of the range.

var shipRange = new BoardIndexRange(new BoardIndex("A1"), new BoardIndex("C1"));
Console.WriteLine(shipRange.Length); // Will print 3

// The next loop will print the board index of the cells A1, B1, and C1.
foreach(var ix in shipRange)
{
    Console.WriteLine(ix);
}
Clone this wiki locally