Example #1
0
        public Boolean AddAShipToBoard(Battleship ship)
        {
            if (IsBoardReadyToPlay || ship.ShipNumber <= 0)
            {
                return(false);
            }

            if (BattleShips.ContainsKey(ship.ShipNumber))
            {
                ReportTool.WriteLine("ShipNumber is already in board.");
                return(false);
            }

            if (ship.Deployment.Count > boardSize || ship.Deployment.Count <= 0)
            {
                ReportTool.WriteLine("Ship must fit entirely on the board");
                return(false);
            }

            if (!ship.IsValidDeployment())
            {
                ReportTool.WriteLine("The ship should be 1-by-n sized");
                return(false);
            }

            // check if ship position had been occupied by another ship
            foreach (Coordinate location in ship.Deployment)
            {
                if (Board[location.X, location.Y].State == CoordinateState.OCCUPIED)
                {
                    ReportTool.WriteLine("Ship can't overlap another ship. {location}");
                    return(false);
                }
            }

            // put ship on the board
            foreach (Coordinate location in ship.Deployment)
            {
                BoardCell cell = Board[location.X, location.Y];
                cell.State      = CoordinateState.OCCUPIED;
                cell.ShipNumber = ship.ShipNumber;
            }

            BattleShips.Add(ship.ShipNumber, ship);
            return(true);
        }