private bool isBattleshipsOverlapping(Battleship battleship, ref Battleship battleshipIn)
        {
            bool overlapping = !(battleshipIn.StartPos.Y > battleship.EndPos.Y ||
                                 battleshipIn.EndPos.Y <battleship.StartPos.Y ||
                                                        battleshipIn.StartPos.X> battleship.EndPos.X ||
                                 battleshipIn.EndPos.X < battleship.StartPos.X);

            return(overlapping);
        }
Exemple #2
0
        public void AddBattleship(Coordinate startPos, int length, Battleship.BattleshipOrientation orientation)
        {
            Battleship battleship = new Battleship()
            {
                StartPos = startPos, Length = length, Orientation = orientation
            };

            if (battleboard != null)
            {
                battleboard.AddBattleShip(battleship);
            }
            else
            {
                throw new Exception("Battle board not created. Please create board first");
            }
        }
        public void AddBattleShip(Battleship battleshipIn)
        {
            //Check no battle ship at location then add else
            //raise battleshi[p exists at location exception
            if (battleshipIn.StartPos.X < BOARD_WIDTH && battleshipIn.StartPos.X >= 0 &&
                battleshipIn.StartPos.Y < BOARD_HEIGHT &&
                battleshipIn.StartPos.Y >= 0)
            {
                if ((battleshipIn.Orientation == Battleship.BattleshipOrientation.HORIZONTAL &&
                     battleshipIn.StartPos.X + battleshipIn.Length > BOARD_WIDTH - 1)
                    ||
                    (battleshipIn.Orientation == Battleship.BattleshipOrientation.VERTICAL &&
                     battleshipIn.StartPos.Y + battleshipIn.Length > BOARD_WIDTH - 1))
                {
                    throw new Exception("Battleship size does not fit board!");
                }

                battleshipIn.Deploy();

                bool overlapping = false;

                foreach (var battleship in battleships)
                {
                    overlapping = isBattleshipsOverlapping(battleship, ref battleshipIn);

                    if (overlapping)
                    {
                        break;
                    }
                }

                if (!overlapping)
                {
                    battleships.Add(battleshipIn);
                }
                else
                {
                    throw new Exception("Battleship deployment failed as overlapping with existing ones!");
                }
            }
            else
            {
                throw new Exception("Invalid start coordinates for battleship!");
            }
        }