private static void CreateLocation(IArrayBoardObject board, int row, int col) { Position position = new Position(row, col); ILocation location = BasicLocation.CreateLocation(position); board.SetLocation(location, row, col); }
public static ILocation GetLocation(IArrayBoardObject board, Position position) { int rowIndex = position.RowIndex; int colIndex = position.ColumnIndex; if (rowIndex < 0 || rowIndex >= board.Height || colIndex < 0 || colIndex >= board.Width) { throw new LocationOffBoardException(string.Format("Location {0} is not on a board of size ({1}, {2})", position.Id, board.Height, board.Width)); } return(board.GetLocation(rowIndex, colIndex)); }
public static AttackResult Attack(IArrayBoardObject board, Position attackLocation) { ILocation targetLocation = GetLocationOnArrayBoard.GetLocation(board, attackLocation); try { return(targetLocation.Attack()); } catch (LocationAlreadyAttackedException) { throw new PositionAlreadyAttackedException(string.Format("Position {0} has already been attacked previously.", targetLocation.GetPositionId())); } }
public static bool IsGameOver(IArrayBoardObject board) { bool hasUnsunkenShip = false; foreach (ILocation loc in board.Locations) { if (loc.IsOccupied() && loc.GetStatus() != AttackStatus.Hit) { hasUnsunkenShip = true; break; } } return(!hasUnsunkenShip); //if all battleships have been sunk, the game is over }
public static void PositionShip(IArrayBoardObject board, IShip battleship, Position battleshipPosition, Orientation battleshipOrientation) { // collate positional information Position shipEndPosition = battleship.CalculateEndPosition(battleshipPosition, battleshipOrientation); // traverse in reverse order, to immediately throw an exception if the ship is not entirely on the board List <ILocation> shipLocations = new List <ILocation>(); List <ILocation> occupiedLocations = new List <ILocation>(); try { for (int r = shipEndPosition.RowIndex; r >= battleshipPosition.RowIndex; r--) { for (int c = shipEndPosition.ColumnIndex; c >= battleshipPosition.ColumnIndex; c--) { ILocation foundLocation = GetLocationOnArrayBoard.GetLocation(board, new Position(r, c)); shipLocations.Add(foundLocation); if (foundLocation.IsOccupied()) { occupiedLocations.Add(foundLocation); } } } } catch (LocationOffBoardException ex) { throw new ShipPlacedOffBoardException("Ship is not entirely on the board.", ex); } // if any of the Locations are already occupied, we cannot place the ship on the board if (occupiedLocations.Count > 0) { ThrowOverlappingShipException(occupiedLocations); } // occupy each of the Locations where the ship belongs foreach (ILocation locations in shipLocations) { locations.Occupy(battleship); } }
private ArrayBoard(int height, int width) { _board = CreateArrayBoardObject.Create(height, width); }