private static Point getNeighborPointByDirection(Point point, ShipDirection direction)
        {
            Point neighbor = new Point();

            switch (direction)
            {
            case ShipDirection.North:
                neighbor.X = point.X;
                neighbor.Y = point.Y - 1;
                break;

            case ShipDirection.East:
                neighbor.X = point.X + 1;
                neighbor.Y = point.Y;
                break;

            case ShipDirection.South:
                neighbor.X = point.X;
                neighbor.Y = point.Y + 1;
                break;

            case ShipDirection.West:
                neighbor.X = point.X - 1;
                neighbor.Y = point.Y;
                break;

            default:
                break;
            }

            return(neighbor);
        }
Example #2
0
        /// <summary>
        /// Adjusts the given coordinate one space toward the given direction.
        /// </summary>
        /// <param name="coords">The coordinates to adjust</param>
        /// <param name="fireDirection">The direction to adjust them</param>
        /// <returns>A new coordinate objerct moved one place toward the given direction</returns>
        protected Coordinate GetNextCoordinateTowards(Coordinate coords, ShipDirection fireDirection)
        {
            Coordinate newCoords = new Coordinate(coords.XCoordinate, coords.YCoordinate);

            switch (fireDirection)
            {
            case ShipDirection.Down:
                newCoords.YCoordinate += 1;
                break;

            case ShipDirection.Up:
                newCoords.YCoordinate -= 1;
                break;

            case ShipDirection.Left:
                newCoords.XCoordinate -= 1;
                break;

            default:
                newCoords.XCoordinate += 1;
                break;
            }

            return(newCoords);
        }
        private async Task <Ship> FillCells(BattleBoard board, Point startPoint, ShipDirection direction)
        {
            var ship = new Ship
            {
                Direction = direction,
                Cells     = new List <BoardCell>()
            };

            if (direction == ShipDirection.Horizontal)
            {
                for (int i = startPoint.X; i < startPoint.X + board.ShipLength; i++)
                {
                    board.Cells[i, startPoint.Y].Status = CellStatus.HasShip;
                    ship.Cells.Add(board.Cells[i, startPoint.Y]);
                }

                board.Ships.Add(ship);
                _logger.LogInformation($"Filled in the cells from cell ({startPoint.X},{startPoint.Y}) to cell ({startPoint.X + board.ShipLength},{startPoint.Y})");
            }
            else
            {
                for (int j = startPoint.Y; j < startPoint.Y + board.ShipLength; j++)
                {
                    board.Cells[startPoint.X, j].Status = CellStatus.HasShip;
                    ship.Cells.Add(board.Cells[startPoint.X, j]);
                }
                board.Ships.Add(ship);
                _logger.LogInformation($"Filled in the cells from cell ({startPoint.X},{startPoint.Y}) to cell ({startPoint.X },{startPoint.Y + board.ShipLength})");
            }
            return(await Task.FromResult(ship));
        }
Example #4
0
        //if valid input, sets ship direction to UP, Dow, Left, or Right and returns the ship direction
        public ShipDirection GetDirectionFromPlayer()
        {
            while (true)
            {
                Console.Write("Please Enter a direction ( U, D, L, R) for your ship U = UP, D = Down, R = Right, L = Left:  ");
                string lower = Console.ReadLine().ToLower();


                switch (lower)
                {
                case "u":
                    return(_direction = ShipDirection.Up);


                case "d":
                    return(_direction = ShipDirection.Down);


                case "l":
                    return(_direction = ShipDirection.Left);

                case "r":
                    return(_direction = ShipDirection.Right);


                default:
                    Console.WriteLine("That is invalid input, please try again");
                    break;
                }
            }
        }
Example #5
0
        public Ship(Point p, ShipType type, ShipDirection direction)
        {
            this.type      = type;
            this.direction = direction;

            GenerateBody(p);
        }
Example #6
0
        public ShipDirection GetShipDirection()
        {
            valid = false;
            while (valid == false)
            {
                // Gets and preps ship direction from user
                Console.WriteLine("\nEnter ship direction (Up, Down, Left, or Right)");
                c1p1ShipDirection = Console.ReadLine();
                c1p1ShipDirection = myTI.ToTitleCase(c1p1ShipDirection);
                if (!(c1p1ShipDirection == "Up" ||
                      c1p1ShipDirection == "Down" ||
                      c1p1ShipDirection == "Left" ||
                      c1p1ShipDirection == "Right"))
                {
                    Console.WriteLine("Not a valid direction. Try again.");
                }
                else
                {
                    valid = true;
                }
            }
            ShipDirection shipDirection = (ShipDirection)Enum.Parse(typeof(ShipDirection), c1p1ShipDirection);

            return(shipDirection);
        }
Example #7
0
 public void SetLocation(Pos pos, ShipDirection direction)
 {
     ShipStatuses = GenStatusBlocks(Size);
     ShipPos      = new Pos(pos);
     Direction    = direction;
     IsPlaced     = true;
 }
Example #8
0
        internal static ShipDirection GetDir(string playerName, ShipType s)

        {
            Console.WriteLine($"{playerName} please enter your {s} direction. Enter '0' for 'Down', '1' for 'Up', '2' for 'Left' and '3' for 'Right': ");
            string        input    = Console.ReadLine();
            ShipDirection ShipGood = new ShipDirection();

            if (input == "")
            {
                Console.WriteLine("You must enter a value here.");
            }
            else
            {
                switch (input)
                {
                case "0":
                    ShipGood = ShipDirection.Down;
                    break;

                case "1":
                    ShipGood = ShipDirection.Up;
                    break;

                case "2":
                    ShipGood = ShipDirection.Left;
                    break;

                case "3":
                    ShipGood = ShipDirection.Right;
                    break;
                }
            }
            return(ShipGood);
        }
Example #9
0
 //method to reset position and status
 public void Reset()
 {
     Sunk      = false;
     position  = new Position();
     direction = new ShipDirection();
     positionList.Clear();
 }
Example #10
0
        public static bool CheckIfIntersect(Ship ship, Pos newPos, int newSize, ShipDirection newDirection)
        {
            // Ship hasn't been placed yet
            if (ship.ShipPos == null)
            {
                return(false);
            }

            var padding = ActiveGame.GetRuleVal(RuleType.ShipPadding);

            // This is one retarded way of doing it, but hey, it works...
            for (int offset = 0; offset < newSize; offset++)
            {
                var newPosOffsetX = newPos.X + (newDirection == ShipDirection.Right ? offset : 0);
                var newPosOffsetY = newPos.Y + (newDirection == ShipDirection.Right ? 0 : offset);

                for (int i = 0; i < ship.Size; i++)
                {
                    var shipPosX = ship.ShipPos.X + (ship.Direction == ShipDirection.Right ? i : 0);
                    var shipPosY = ship.ShipPos.Y + (ship.Direction == ShipDirection.Right ? 0 : i);

                    if (shipPosX >= newPosOffsetX - padding && shipPosX <= newPosOffsetX + padding &&
                        shipPosY >= newPosOffsetY - padding && shipPosY <= newPosOffsetY + padding)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        public async Task <Ship> CreateShip(Point startPoint, ShipDirection direction)
        {
            _logger.LogInformation($"Creating a ship at the point {startPoint.ToString()}");

            if ((int)_game.Status > 1)
            {
                throw new InCreatableShipException("The game has to be new to add more ships. The ship hasn't been created");
            }

            if (!IsValidPoint(_game.Board, startPoint) || !IsShipCreatable(_game.Board, startPoint, direction))
            {
                throw new InCreatableShipException("Ship can't be created ");
            }

            if (_game.Board.CurrentShips >= _game.Board.MaxShips)
            {
                throw new InCreatableShipException("The ocean is too busy at the moment, can't fit more ships");
            }

            var ship = await FillCells(_game.Board, startPoint, direction);

            _logger.LogInformation($"Created a ship at the point {startPoint.ToString()}");
            _game.Board.CurrentShips++;
            return(ship);
        }
Example #12
0
        public Board GameSetUp()
        {
            //create board instance for current player
            //create placementRequest
            Board            playerBoard      = new Board();
            PlaceShipRequest placementRequest = new PlaceShipRequest();
            int shipsPlaced = 0;

            while (shipsPlaced < 5)
            {
                //populate ships on board for current player based on their input
                //get ship type
                ShipType ship = ConsoleInput.GetShipType();
                placementRequest.ShipType = ship;

                //get coordinates
                Coordinate shipCoordinates = GetShipCoordinates();
                placementRequest.Coordinate = shipCoordinates;

                //get ship direction
                ShipDirection direction = ConsoleInput.GetShipDirection();
                placementRequest.Direction = direction;

                ShipPlacement response = playerBoard.PlaceShip(placementRequest);
                ConsoleOutput.DisplayShipPlacementResult(response);
                if (response == ShipPlacement.Ok)
                {
                    shipsPlaced++;
                }
            }
            Console.Clear();
            return(playerBoard);
        }
Example #13
0
        public void PlaceShipsOnBoard(IPlayer player)
        {
            try
            {
                _log.Info("BTG - trying to place ships on board!");

                var ships = new[] { ShipType.Battleship, ShipType.Destroyer, ShipType.Destroyer };
                var i     = 0;
                foreach (var ship in ships)
                {
                    _ship          = _shipFactory.CreateShip(ship);
                    _shipDirection = _randomManager.GetDirection();
                    do
                    {
                        _coordinate = _coordinateManager.GetRandomCoordinate();
                    }while (!_board.IsValidCoordinate(_coordinate, _shipDirection, _ship.Coordinates.Length) ||
                            _board.IsOverlap(player.Board.Ships, _coordinate));

                    _ship = PlaceShip();

                    player.Board.Ships[i++] = _ship;
                }

                _outputManager.WriteLine($"Ships for {player.Name} placed - completed!", ConsoleColor.Yellow);
            }
            catch (Exception e)
            {
                _log.Error($"BTG - Error when trying to place the ships on board: {e}");
            }
        }
Example #14
0
        //Checks if the ship fits in the specified area.
        //Backend only.
        private bool CheckShipAreaBackEnd(int x, int y, ShipDirection orientation, int size)
        {
            bool doesFit = false;

            if (orientation == ShipDirection.Left)
            {
                if (y - size + 1 > 0)
                {
                    doesFit = true;
                }
            }
            else if (orientation == ShipDirection.Right)
            {
                if (y + size - 1 <= 10)
                {
                    doesFit = true;
                }
            }
            else if (orientation == ShipDirection.Up)
            {
                if (x - size + 1 > 0)
                {
                    doesFit = true;
                }
            }
            else if (orientation == ShipDirection.Down)
            {
                if (x + size - 1 <= 10)
                {
                    doesFit = true;
                }
            }

            return(doesFit);
        }
Example #15
0
        /// <summary>
        /// Used to place ship on a map, returns false if the given coordinate is invalid
        /// </summary>
        public bool PlaceShip(Ship ship, int x, int y, ShipDirection shipDirection)
        {
            // Checks if the fields is water, if not return false
            for (int i = 0; i < ship.Size; i++)
            {
                if ((shipDirection == ShipDirection.Horizontal) && (map.GetFieldValue(x + i, y) != (int)Field.Water))
                {
                    return(false);
                }
                else if ((shipDirection == ShipDirection.Vertical) && (map.GetFieldValue(x, y + i) != (int)Field.Water))
                {
                    return(false);
                }
            }

            // Places ship on fields
            for (int i = 0; i < ship.Size; i++)
            {
                if (shipDirection == ShipDirection.Horizontal)
                {
                    map.SetFieldValue(x + i, y, ship.FieldValueHorizontal + i);
                }
                else
                {
                    map.SetFieldValue(x, y + i, ship.FieldValueVertical + i);
                }
            }
            return(true);
        }
Example #16
0
        private void promptForShipCoordinate(string _firstPlayer, Board board, ShipType type)
        {
            PlaceShipRequest placeRequest = new PlaceShipRequest();

            while (true)
            {
                Console.WriteLine($"{_firstPlayer}, enter coordinates to place your {type}");

                Coordinate    coordinate = _gameIn.GetSuperSecretCoordinates();
                ShipDirection direction  = _gameIn.GetShipDirection();

                placeRequest.Coordinate = coordinate;
                placeRequest.Direction  = direction;
                placeRequest.ShipType   = type;

                ShipPlacement validate = board.PlaceShip(placeRequest);

                switch (validate)
                {
                case ShipPlacement.NotEnoughSpace:
                    Console.WriteLine("Sorry, it isn't valid due to the coordinate being off the board.");
                    break;

                case ShipPlacement.Overlap:
                    Console.WriteLine("Two ships cannot share the same space...why?...Boundary issues");
                    break;

                case ShipPlacement.Ok:
                    Console.WriteLine("Good! This space is available");
                    return;
                }
            }
        }
Example #17
0
        internal static ShipDirection GetDirection(string PlayerName, ShipType s)
        {
            Console.WriteLine($"{PlayerName}, please enter a direction for your ship {s}; use the directions u=up,d=down, L=left, and R=right: ");
            Console.WriteLine();

            string UserInput = Console.ReadLine();

            ShipDirection ship = new ShipDirection();

            switch (UserInput)
            {
            case "U":
                ship = ShipDirection.Up;
                break;

            case "D":
                ship = ShipDirection.Down;
                break;

            case "L":
                ship = ShipDirection.Left;
                break;

            case "R":
                ship = ShipDirection.Right;
                break;

            default:
                ship = ShipDirection.Down;
                break;
            }
            return(ship);
        }
Example #18
0
        /// <summary>
        /// Validates propposed placement
        /// </summary>
        /// <param name="position"></param>
        /// <param name="orientation"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        public bool IsPlacementValid(Coordinates position, ShipDirection orientation, int width)
        {
            int endcolumn = position.Column;
            int endrow    = position.Row;

            if (orientation == ShipDirection.Horizontal)
            {
                endcolumn += width - 1;
            }
            else
            {
                endrow += width - 1;
            }

            //We cannot place ships beyond the boundaries of the board
            if (endrow > GRID_SIZE || endcolumn > GRID_SIZE)
            {
                return(false);
            }
            else
            {
                //Check if specified Cells are occupied
                var affectedCells = this.Cells.ExtendedRange(position.Row, position.Column, endrow, endcolumn);
                if (affectedCells.Any(x => x.IsOccupied))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
Example #19
0
        public ShipDirection shipDirection()
        {
            Console.Write("Please select the direction for your ship (up, down, left, right): ");
            string        input         = Console.ReadLine();
            ShipDirection shipDirection = new ShipDirection();

            switch (input.ToUpper())
            {
            case "UP":
                shipDirection = ShipDirection.Up;
                return(shipDirection);

            case "DOWN":
                shipDirection = ShipDirection.Down;
                return(shipDirection);

            case "LEFT":
                shipDirection = ShipDirection.Left;
                return(shipDirection);

            case "RIGHT":
                shipDirection = ShipDirection.Right;
                return(shipDirection);

            default:
                Console.WriteLine("Invalid Input");
                break;
            }
            Console.ReadLine();
            return(shipDirection);
        }
Example #20
0
        /// <summary>
        /// Used to get user to place ship on the controller map, returns false if the given coordinate is invalid
        /// </summary>
        public bool UserPlaceShip(ShipType shipType, int x, int y, ShipDirection shipDirection)
        {
            bool placeState = false;

            if (userShipPlaced[(int)shipType] == false)
            {
                placeState = controllerUser.UserPlaceShip(shipType, x, y, shipDirection);
                if (placeState == true)
                {
                    userShipPlaced[(int)shipType] = true;
                }
            }
            int count = 0;

            for (int i = 0; i < 5; i++)
            {
                if (userShipPlaced[i] == true)
                {
                    count++;
                }
            }

            if (count == 5)
            {
                readyToAttack = true;
            }

            return(placeState);
        }
Example #21
0
        /// <summary>
        /// Called once at start to load content
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            background = Content.Load <Texture2D>("DiceTexture.png");
            CardImage  = Content.Load <Texture2D>("Fighter.png");
            CardBack   = Content.Load <Texture2D>("CardBack.png");
            Assassin   = Content.Load <Texture2D>("Assassin.png");
            Archer     = Content.Load <Texture2D>("Archer.png");
            cShip      = Content.Load <Texture2D>("Ship.png");

            cShipDir     = ShipDirection.Straight;
            cShipUseKeys = true;
            cShipShow    = false;

            ConsoleRect = new Texture2D(graphics.GraphicsDevice, 1, 1);
            ConsoleRect.SetData(new[] { Color.DarkGray });

            cFont = new TextureFont(Content.Load <Texture2D>("Font.png"));

            TestCont                = new Container(GraphicsDevice, background, 20, 250, 100, 200);
            TestCont.OpenEffect     = DisplayEffect.SlideRight;
            TestCont.CloseEffect    = DisplayEffect.SlideLeft;
            TestCont.EffectDuration = 500;

            TestCard                 = new CardDisplay(GraphicsDevice, 350, 250, cFont);
            TestCard.Top             = 105;
            TestCard.Left            = 325;
            TestCard.SendMouseEvents = true;
            TestCard.MouseDown      += new ContainerMouseButtonEventHandler(MouseLeftDown);

            cCard            = new CardInfo(CardType.Monster);
            cCard.Background = Content.Load <Texture2D>("CardBase.png");
            cCard.Image      = CardImage;
            cCard.Title      = "Shield Maiden";

            List <string> Lines = new List <string>();

            Lines.Add("Health: 5");
            Lines.Add("Attack: 3");
            Lines.Add("");
            Lines.Add("Women of Rohan");
            cCard.Description = Lines;
            cCard.Changed     = true;

            TestCard.Card = cCard;

            NestedCont = new Container(GraphicsDevice, null, 350, 600, 100, 100);
            NestedCont.BackgroundColor = Color.BurlyWood;
            NestedCont.Visible         = true;

            cTextTest = new TextBox(GraphicsDevice, null, GraphicsDevice.Viewport.Height - 150, GraphicsDevice.Viewport.Width - 200, 125, 175);
            cTextTest.BackgroundColor = Color.CornflowerBlue;
            cTextTest.FontColor       = Color.Bisque;
            cTextTest.Font            = cFont;
            cTextTest.Visible         = true;

            DevConsole.AddText("Viewport Bounds: X=" + GraphicsDevice.Viewport.Bounds.X + " Y=" + GraphicsDevice.Viewport.Bounds.Y + " Width=" + GraphicsDevice.Viewport.Bounds.Width + " Height=" + GraphicsDevice.Viewport.Bounds.Height);
        }
Example #22
0
        public static ShipDirection PickADirection()
        {
            string        directionTemp = "";
            ShipDirection Direction     = new ShipDirection();

            Console.WriteLine("Pick a direction");
            directionTemp = ConsoleInput.ReadLine();


            if (directionTemp == "Up" || directionTemp == "up")
            {
                Direction = ShipDirection.Up;
            }
            else if (directionTemp == "Down" || directionTemp == "down")
            {
                Direction = ShipDirection.Down;
            }
            else if (directionTemp == "Right" || directionTemp == "right")
            {
                Direction = ShipDirection.Right;
            }
            else if (directionTemp == "Left" || directionTemp == "left")
            {
                Direction = ShipDirection.Left;
            }
            else
            {
                Console.WriteLine("Invalid use, try again");
                Console.ReadKey();
                PickADirection();
            }
            return(Direction);
        }
Example #23
0
        //Requests a direction from the player.
        //Redundant//Deprecated
        private ShipDirection RequestOrientation(Player player, string prompt)
        {
            ShipDirection orientation = ShipDirection.Up;
            int           selector    = 0;
            bool          valid       = false;

            do
            {
                string stringDirection = null;

                PlayerShipDisplay(player, prompt);

                Console.WriteLine("Please choose an orientation for your ship.");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("(Hint: Select by pressing the space bar.)");
                Console.ForegroundColor = ConsoleColor.Green;

                switch (selector)
                {
                case 0:
                    stringDirection = "Up";
                    orientation     = ShipDirection.Up;
                    break;

                case 1:
                    stringDirection = "Down";
                    orientation     = ShipDirection.Down;
                    break;

                case 2:
                    stringDirection = "Left";
                    orientation     = ShipDirection.Left;
                    break;

                case 3:
                    stringDirection = "Right";
                    orientation     = ShipDirection.Right;
                    break;

                default:
                    stringDirection = "Bad Direction --> See DirectionString()";
                    break;
                }

                Console.Write("Current Direction is: ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"{stringDirection}");
                Console.ForegroundColor = ConsoleColor.Green;
                ConsoleKeyInfo keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.Enter)
                {
                    valid = true;
                }

                //Increments the selector, but keeps it below 4.
                selector = ((selector + 1) % 4);
            } while (!valid);

            return(orientation);
        }
Example #24
0
 public void PlaceShips()
 {
     foreach (ShipType i in Enum.GetValues(typeof(ShipType)))
     {
         Coordinate       coord   = GetPlacementCoord(i);
         ShipDirection    dir     = GetShipDirection();
         PlaceShipRequest request = new PlaceShipRequest()
         {
             Coordinate = coord,
             Direction  = dir,
             ShipType   = i
         };
         DisplayPlacementBoard();
         PlaceShip(request);
         DisplayPlacementBoard();
     }
     Console.WriteLine($"{game.Players[game.CurrentPlayer].Name}, your ships are in place. Press any key to continue.");
     Console.ReadLine();
     if (game.CurrentPlayer == 0)
     {
         game.CurrentPlayer = 1;
         game.OtherPlayer   = 0;
         return;
     }
     else
     {
         game.CurrentPlayer = 0;
         game.OtherPlayer   = 1;
         return;
     }
 }
Example #25
0
        public void IsShipDirectionValid_ValidPointSizeDirection()
        {
            Point         point         = new Point(4, 6);
            int           shipSize      = 5;
            ShipDirection shipDirection = ShipDirection.Right;

            Assert.IsTrue(GridValidator.IsShipDirectionValid(shipSize, point, shipDirection));
        }
 public SelectedBlocks(int xpos, int ypos, int length, ShipDirection direction)
     : base(SeaType.EmptySea, xpos, ypos, length, direction, 0, false, "+", "Selected")
 {
     foreach (Block b in this.blocks)
     {
         b.selected = true;
     }
 }
Example #27
0
 public Ship(int x, int y, int size, ShipDirection direction, Player owner)
 {
     X         = x;
     Y         = y;
     Size      = size; //A DamagedParts-ot is inicializálja
     Direction = direction;
     Owner     = owner;
 }
Example #28
0
 public Ship(ShipDirection direction, SquareType shipType)
 {
     ShipName   = shipType.ToString();
     Direction  = direction;
     SquareType = shipType;
     IsSunk     = false;
     Size       = ShipSize();
 }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Ship"/> class.
 /// </summary>
 /// <param name="bow">The ship's bow.</param>
 /// <param name="type">The ship type.</param>
 /// <param name="direction">The ship direction.</param>
 public Ship(Bow bow, ShipType type, ShipDirection direction)
 {
     this.Bow = bow;
     this.Type = type;
     this.IsSunk = false;
     this.Direction = direction;
     this.Size = this.GetSize(type);
 }
Example #30
0
        public void IsShipDirectionValid_ValidPointValidSizeRightDirection()
        {
            Point         point         = new Point(9, 6);
            int           shipSize      = 4;
            ShipDirection shipDirection = ShipDirection.Right;

            Assert.IsFalse(GridValidator.IsShipDirectionValid(shipSize, point, shipDirection));
        }
Example #31
0
        public void IsShipDirectionValid_ValidPointValidSizeLeftDirection()
        {
            Point         point         = new Point(9, 1);
            int           shipSize      = 5;
            ShipDirection shipDirection = ShipDirection.Left;

            Assert.IsTrue(GridValidator.IsShipDirectionValid(shipSize, point, shipDirection));
        }
Example #32
0
        public void IsShipDirectionValid_ValidPointValidSizeDownDirection()
        {
            Point         point         = new Point(9, 6);
            int           shipSize      = 4;
            ShipDirection shipDirection = ShipDirection.Down;

            Assert.IsTrue(GridValidator.IsShipDirectionValid(shipSize, point, shipDirection));
        }
        private BoardCoordinate? FindNextFreeSpace(CellStatus[,] workingSet, BoardCoordinate cellToStartSearch, ShipDirection direction, int shipLength)
        {
            // the free space must be a cluster of cells with 'Free' status, such that
            // they can be contiguous and none of the cells of the new ship lands on
            // a 'not available for placement' or 'ship part' field.
            for (var row = cellToStartSearch.Row; row < _gameConfiguration.BoardSize; row++)
            {
                for (var column = cellToStartSearch.Column; column < _gameConfiguration.BoardSize; column++)
                {
                    if (workingSet[row, column] == CellStatus.Free)
                    {
                        if (direction == ShipDirection.Horizontal)
                        {
                            // first - check if there is enough room to place the ship in the current row/column
                            if (column + shipLength > _gameConfiguration.BoardSize - 1)
                                continue;

                            // next, check if the entire span of the next few cells is available
                            var spanAvailable = true;
                            for (var c = column; c < column + shipLength; c++)
                            {
                                if (workingSet[row, c] != CellStatus.Free)
                                {
                                    spanAvailable = false;
                                    break;
                                }
                            }
                            if (!spanAvailable)
                                continue;
                        }
                        else
                        {
                            if (row + shipLength > _gameConfiguration.BoardSize - 1)
                                continue;

                            var spanAvailable = true;
                            for (var r = row; r < row + shipLength; r++)
                            {
                                if (workingSet[r, column] != CellStatus.Free)
                                {
                                    spanAvailable = false;
                                    break;
                                }
                            }
                            if (!spanAvailable)
                                continue;
                        }

                        return new BoardCoordinate(row, column);
                    }
                }
            }

            return null;
        }
Example #34
0
 public Ship Get(string shipType, ShipDirection direction)
 {
     switch (shipType)
     {
         case "Battleship":
             return new Battleship(direction);
         case "Destructor":
             return new Destructor(direction);
         default:
             throw new InvalidOperationException("The ship type is invalid");
     }
 }
Example #35
0
        public void AddShip(int numberOfCells, ShipDirection direction, Coordinates startingPoint)
        {
            List<Cell> shipCells = new List<Cell>();
            for (int i = 0; i < numberOfCells; i++)
            {
                var matchedCell = direction == ShipDirection.Horizontal ? Map.Where(c => c.X == startingPoint.x + i && c.Y == startingPoint.y).FirstOrDefault() : Map.Where(c => c.X == startingPoint.x && c.Y == startingPoint.y + i).FirstOrDefault();

                if (matchedCell != null)
                {
                    matchedCell.State = CellState.Ship;
                    shipCells.Add(matchedCell);
                }
            }

            ShipsOnMap.Add(new Ship() { Cells = shipCells });
        }
Example #36
0
        public ShipDirection PointShip(string inMessage)
        {
            while (!_isInputValid)
            {
                Console.Write(inMessage);
                string _userInput = Console.ReadLine();

                if ((string.IsNullOrWhiteSpace(_userInput)) || (_userInput.Length > 1))
                    Console.WriteLine(_invalidInputMessage);

                else
                {
                    if (_userInput.Length == 1)
                    {
                        string c = _userInput.ToUpper();

                        if (c == "L")
                        {
                            _shipDir = ShipDirection.Left;
                            _isInputValid = true;
                        }

                        else if (c == "R")
                        {
                            _shipDir = ShipDirection.Right;
                            _isInputValid = true;
                        }

                        else if (c == "U")
                        {
                            _shipDir = ShipDirection.Up;
                            _isInputValid = true;
                        }

                        else if (c == "D")
                        {
                            _shipDir = ShipDirection.Down;
                            _isInputValid = true;
                        }

                        else Console.WriteLine(_invalidInputMessage + "input not L,R,U,D");
                    }
                }
            }

            return _shipDir;
        }
        private Position GetRandomShipPosition(ShipDirection direction, int shipLength, int rowsCount, int colsCount)
        {
            int x;
            int y;

            if (direction == ShipDirection.Horizontal)
            {
                x = _random.Next(0, rowsCount);
                y = _random.Next(0, colsCount - shipLength);
            }
            else
            {
                x = _random.Next(0, rowsCount - shipLength);
                y = _random.Next(0, colsCount);
            }

            return new Position(x, y);
        }
Example #38
0
        //constructor
        public Ship(SeaType shipType, int xpos, int ypos, int length, ShipDirection direction, int timesHit, bool sunk, string printchar, string name)
        {
            this.shipType = shipType;

            this.blocks = new Block[length];

            for (int i = 0; i < length; i++)
            {
                if (direction == ShipDirection.Horizontal)
                    blocks[i] = new Block(shipType, xpos + i, ypos, printchar, name);
                else
                    blocks[i] = new Block(shipType, xpos, ypos + i, printchar, name);
            }

            this.length = length;

            this.direction = direction;
            this.timesHit = timesHit;

            this.sunk = sunk;
        }
Example #39
0
        private void CheckDirection(Coordinate coordinate, ShipDirection direction, int numberOfSlots)
        {
            Coordinates = new Coordinate[numberOfSlots];

            Coordinates[0] = coordinate;

            switch (direction)
            {
                case ShipDirection.Up:
                    for (int i = 1; i < numberOfSlots; i++)
                    {
                        Coordinates[i] = new Coordinate(coordinate.XCoordinate, coordinate.YCoordinate - i);
                    }
                    break;

                case ShipDirection.Down:
                    for (int i = 1; i < numberOfSlots; i++)
                    {
                        Coordinates[i] = new Coordinate(coordinate.XCoordinate, coordinate.YCoordinate + i);
                    }
                    break;

                case ShipDirection.Left:
                    for (int i = 1; i < numberOfSlots; i++)
                    {
                        Coordinates[i] = new Coordinate(coordinate.XCoordinate - i, coordinate.YCoordinate);
                    }
                    break;

                case ShipDirection.Right:
                    for (int i = 1; i < numberOfSlots; i++)
                    {
                        Coordinates[i] = new Coordinate(coordinate.XCoordinate + i, coordinate.YCoordinate);
                    }
                    break;
            }
        }
Example #40
0
 private ShipDirection AskDirection()
 {
     bool validDirection = false;
     ShipDirection dir = new ShipDirection();
     do
     {
         Console.WriteLine("Which duration should the ship go when placed?\n(Up, Down, Left, or Right)");
         string direction = Console.ReadLine();
         if (direction == "Up")
         {
             validDirection = true;
             dir = ShipDirection.Up;
         }
         else if (direction == "Down")
         {
             validDirection = true;
             dir = ShipDirection.Down;
         }
         else if (direction == "Right")
         {
             validDirection = true;
             dir = ShipDirection.Right;
         }
         else if (direction == "Left")
         {
             validDirection = true;
             dir = ShipDirection.Left;
         }
         else
         {
             Console.WriteLine("Not a valid direction, try again.\n");
         }
     } while (!validDirection);
     Console.WriteLine();
     return dir;
 }
        private void PlaceShipOnMap(CellStatus[,] workingSet, int lengthOfNextShipToPosition, ShipDirection directionOfPositioning, BoardCoordinate position)
        {
            // first mark everything on and around cells where the ship will be as unavailable
            var startingCoordinateX = Math.Max(position.Column - 1, 0);
            var startingCoordinateY = Math.Max(position.Row - 1, 0);
            var endCoordinateX = directionOfPositioning == ShipDirection.Horizontal ?
                Math.Min(position.Column + lengthOfNextShipToPosition, _gameConfiguration.BoardSize - 1) :
                Math.Min(position.Column + 1, _gameConfiguration.BoardSize - 1);
            var endCoordinateY = directionOfPositioning == ShipDirection.Vertical ?
                Math.Min(position.Row + lengthOfNextShipToPosition, _gameConfiguration.BoardSize - 1) :
                Math.Min(position.Row + 1, _gameConfiguration.BoardSize - 1);

            for (var row = startingCoordinateY; row <= endCoordinateY; row++)
                for (var column = startingCoordinateX; column <= endCoordinateX; column++)
                    workingSet[row, column] = CellStatus.NotAvailableForPlacement;

            //Debug.WriteLine(RepresentWorkingSet(workingSet));

            // next mark where the ship actually is
            for (int i = 0; i < lengthOfNextShipToPosition; i++)
            {
                var row = directionOfPositioning == ShipDirection.Horizontal ? position.Row : Math.Min(position.Row + i, _gameConfiguration.BoardSize - 1);
                var column = directionOfPositioning == ShipDirection.Vertical ? position.Column : Math.Min(position.Column + i, _gameConfiguration.BoardSize - 1);

                workingSet[row, column] = CellStatus.ShipPart;
            }

            // finally, add the positioned ship to the collection of positioned ships
            var shipsPositionedSoFar = _shipPositioningParametersPerShipLevel.Count;
            var currentlyPositionedShipPositioningParameters = new ShipPositioningParameters
            {
                ShipCoordinate = position,
                ShipDirection = directionOfPositioning
            };
            _shipPositioningParametersPerShipLevel.Add(shipsPositionedSoFar, currentlyPositionedShipPositioningParameters);

            //Debug.WriteLine(RepresentWorkingSet(workingSet));
        }
 public BattleShip(int xpos, int ypos, ShipDirection direction)
     : base(SeaType.BattleShip, xpos, ypos, ShipConstants.BATTLESHIP_LENGTH, direction, 0, false, "B", "Battleship")
 {
 }
Example #43
0
        public void askshipspot()
        {
            Console.Clear();
            ShipPlacement placement;
            bool validCoord = false;
            bool validLength = false;

            do
            {
                Console.WriteLine("Where would you like your starting Submarine coordinate to be, {0}", currentPlayer.name);
                string PlayerInput = Console.ReadLine().ToUpper();
                if (validLength = (PlayerInput.Length > 0))
                {
                    string letter = PlayerInput.Substring(0, 1);
                    string number = PlayerInput.Substring(1);
                    ShipType shiptype = new ShipType();
                    shiptype = ShipType.Submarine;

                    if (validCoord = (letter == "A" || letter == "B" || letter == "C" || letter == "D" || letter == "E" || letter == "F" || letter == "G" || letter == "H" || letter == "I" || letter == "J") && (number == "1" || number == "2" || number == "3" || number == "4" || number == "5" || number == "6" || number == "7" || number == "8" || number == "9" || number == "10"))
                    {

                        int xNum = ParseLetter(letter);
                        int yNum = ParseNumber(number);

                        if (yNum <= 10)
                        {
                            Coordinate coord = new Coordinate(yNum, xNum);
                            shipRequest.Coordinate = coord;

                            ShipDirection shipDirection = new ShipDirection();
                            shipDirection = directions();
                            shipRequest.Direction = shipDirection;
                            shipRequest.ShipType = shiptype;
                            placement = currentPlayer.theirBoard.PlaceShip(shipRequest);

                            if (placement == ShipPlacement.NotEnoughSpace)
                            {
                                Console.WriteLine("Crap shot placement, not enough space, choose wiser!");
                                validCoord = false;
                            }
                            if (placement == ShipPlacement.Overlap)
                            {
                                Console.WriteLine("Can't do that, you already have a boat there, choose wiser!");
                                validCoord = true;
                            }
                        }
                        else
                        {
                            validCoord = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("That was not a valid input!");
                        validCoord = false;
                    }
                }
                else
                {
                    Console.WriteLine("That was not a valid input, do better!");

                }

            } while (!validCoord || !validLength);

            do
            {
                Console.WriteLine("Where would you like your starting Destroyer coordinate to be, {0}", currentPlayer.name);
                string PlayerInput = Console.ReadLine().ToUpper();
                if (validLength = (PlayerInput.Length > 0))
                {
                    string letter = PlayerInput.Substring(0, 1);
                    string number = PlayerInput.Substring(1);
                    ShipType shiptype = new ShipType();
                    shiptype = ShipType.Destroyer;
                    bool ship = false;

                    if (validCoord = (letter == "A" || letter == "B" || letter == "C" || letter == "D" || letter == "E" || letter == "F" || letter == "G" || letter == "H" || letter == "I" || letter == "J") && (number == "1" || number == "2" || number == "3" || number == "4" || number == "5" || number == "6" || number == "7" || number == "8" || number == "9" || number == "10"))
                    {
                        int xNum = ParseLetter(letter);
                        int yNum = ParseNumber(number);

                        Coordinate coord = new Coordinate(yNum, xNum);
                        shipRequest.Coordinate = coord;

                        ShipDirection shipDirection = new ShipDirection();
                        shipDirection = directions();
                        shipRequest.Direction = shipDirection;
                        shipRequest.ShipType = shiptype;
                        placement = currentPlayer.theirBoard.PlaceShip(shipRequest);

                        if (placement == ShipPlacement.NotEnoughSpace)
                        {
                            Console.WriteLine("Crap shot placement, enough space, choose wiser!");
                            validCoord = false;
                        }
                        if (placement == ShipPlacement.Overlap)
                        {
                            Console.WriteLine("Can't do that, you already have a boat there, choose wiser!");
                            validCoord = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("That was not a valid spot, do better!");
                    }
                }
                else
                {
                    Console.WriteLine("That was not a valid input!");
                    validCoord = false;

                }

            } while (!validCoord);

            do
            {
                Console.WriteLine("Where would you like your starting Carrier coordinate to be, {0}", currentPlayer.name);
                string playerInput = Console.ReadLine().ToUpper();
                if (validLength = (playerInput.Length > 0))
                {
                    string letter = playerInput.Substring(0, 1);
                    string number = playerInput.Substring(1);
                    ShipType shiptype = new ShipType();
                    shiptype = ShipType.Carrier;
                    bool ship = false;

                    if (validCoord = (letter == "A" || letter == "B" || letter == "C" || letter == "D" || letter == "E" || letter == "F" || letter == "G" || letter == "H" || letter == "I" || letter == "J") && (number == "1" || number == "2" || number == "3" || number == "4" || number == "5" || number == "6" || number == "7" || number == "8" || number == "9" || number == "10"))
                    {
                        int xNum = ParseLetter(letter);
                        int yNum = ParseNumber(number);

                        Coordinate coord = new Coordinate(yNum, xNum);
                        shipRequest.Coordinate = coord;

                        ShipDirection shipDirection = new ShipDirection();
                        shipDirection = directions();
                        shipRequest.Direction = shipDirection;
                        shipRequest.ShipType = shiptype;
                        placement = currentPlayer.theirBoard.PlaceShip(shipRequest);

                        if (placement == ShipPlacement.NotEnoughSpace)
                        {
                            Console.WriteLine("Crap shot placement, enough space, choose wiser!");
                            validCoord = false;
                        }
                        if (placement == ShipPlacement.Overlap)
                        {
                            Console.WriteLine("Can't do that, you already have a boat there, choose wiser!");
                            validCoord = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("That was not a valid spot, do better!");
                    }
                }
                else
                {
                    Console.WriteLine("That was not a valid input!");
                    validCoord = false;

                }

            } while (!validCoord);

            do
            {
                Console.WriteLine("Where would you like your starting Battleship coordinate to be, {0}", currentPlayer.name);
                string playerInput = Console.ReadLine().ToUpper();
                if (validLength = (playerInput.Length > 0))
                {
                    string letter = playerInput.Substring(0, 1);
                    string number = playerInput.Substring(1);
                    ShipType shiptype = new ShipType();
                    shiptype = ShipType.Battleship;

                    if (validCoord = (letter == "A" || letter == "B" || letter == "C" || letter == "D" || letter == "E" || letter == "F" || letter == "G" || letter == "H" || letter == "I" || letter == "J") && (number == "1" || number == "2" || number == "3" || number == "4" || number == "5" || number == "6" || number == "7" || number == "8" || number == "9" || number == "10"))
                    {
                        int xNum = ParseLetter(letter);
                        int yNum = ParseNumber(number);

                        Coordinate coord = new Coordinate(yNum, xNum);
                        shipRequest.Coordinate = coord;

                        ShipDirection shipDirection = new ShipDirection();
                        shipDirection = directions();
                        shipRequest.Direction = shipDirection;
                        shipRequest.ShipType = shiptype;
                        placement = currentPlayer.theirBoard.PlaceShip(shipRequest);

                        if (placement == ShipPlacement.NotEnoughSpace)
                        {
                            Console.WriteLine("Crap shot placement, enough space, choose wiser!");
                            validCoord = false;
                        }
                        if (placement == ShipPlacement.Overlap)
                        {
                            Console.WriteLine("Can't do that, you already have a boat there, choose wiser!");
                            validCoord = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("That was not a valid spot, do better!");
                    }
                }
                else
                {
                    Console.WriteLine("That was not a valid input!");
                    validCoord = false;

                }

            } while (!validCoord);

            do
            {
                Console.WriteLine("Where would you like your starting Cruiser coordinate to be, {0}", currentPlayer.name);
                string playerInput = Console.ReadLine().ToUpper();
                if (validLength = (playerInput.Length > 0))
                {
                    string letter = playerInput.Substring(0, 1);
                    string number = playerInput.Substring(1);
                    ShipType shiptype = new ShipType();
                    shiptype = ShipType.Cruiser;

                    if (validCoord = (letter == "A" || letter == "B" || letter == "C" || letter == "D" || letter == "E" || letter == "F" || letter == "G" || letter == "H" || letter == "I" || letter == "J") && (number == "1" || number == "2" || number == "3" || number == "4" || number == "5" || number == "6" || number == "7" || number == "8" || number == "9" || number == "10"))
                    {
                        int xNum = ParseLetter(letter);
                        int yNum = ParseNumber(number);

                        Coordinate coord = new Coordinate(yNum, xNum);
                        shipRequest.Coordinate = coord;

                        ShipDirection shipDirection = new ShipDirection();
                        shipDirection = directions();
                        shipRequest.Direction = shipDirection;
                        shipRequest.ShipType = shiptype;
                        placement = currentPlayer.theirBoard.PlaceShip(shipRequest);

                        if (placement == ShipPlacement.NotEnoughSpace)
                        {
                            Console.WriteLine("Crap shot placement, enough space, choose wiser!");
                            validCoord = false;
                        }
                        if (placement == ShipPlacement.Overlap)
                        {
                            Console.WriteLine("Can't do that, you already have a boat there, choose wiser!");
                            validCoord = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("That was not a valid spot, do better!");
                    }
                }
                else
                {
                    Console.WriteLine("That was not a valid input!");
                    validCoord = false;
                }

            } while (!validCoord);
        }
 public PlaceShipRequest(Coordinate coord, ShipDirection direction, ShipType type)
 {
     Coordinate = coord;
     Direction = direction;
     ShipType = type;
 }
Example #45
0
 public Destructor(ShipDirection direction): base(direction){ }
Example #46
0
 private void ValidateShipDirection()
 {
     while (!DirectionDecode.ContainsKey(_direction))
     {
         Console.Write("That is not a valid direction. Please enter U, D, R or L: ");
         _direction = Console.ReadLine().ToUpper();
     }
     _shipDirection = DirectionDecode[_direction];
 }
 public Rowing_Boat(int xpos, int ypos, ShipDirection direction)
     : base(SeaType.Rowing_Boat, xpos, ypos, ShipConstants.ROWING_BOAT_LENGTH, direction, 0, false, "R", "Rowing Boat")
 {
 }
Example #48
0
 public Battleship(ShipDirection direction): base(direction){}
Example #49
0
 public Ship(int size, ShipDirection direction, char shipSymbol, Position topLeft)
     : this(size, direction, shipSymbol)
 {
     this.TopLeft = topLeft;
 }
Example #50
0
 protected Ship(ShipDirection direction)
 {
     Direction = direction;
 }
Example #51
0
 public Destroyer(ShipDirection direction, Position topLeft)
     : base(GlobalConstants.DestroyerSize, direction, GlobalConstants.DestroyerSymbol, topLeft)
 {
 }
Example #52
0
 public Destroyer(ShipDirection direction)
     : base(GlobalConstants.DestroyerSize, direction, GlobalConstants.DestroyerSymbol)
 {
 }
 public Cruiser(int xpos, int ypos, ShipDirection direction)
     : base(SeaType.Cruiser, xpos, ypos, ShipConstants.CRUISER_LENGTH, direction, 0, false, "C", "Cruiser")
 {
 }
 public Submarine(int xpos, int ypos, ShipDirection direction)
     : base(SeaType.Submarine, xpos, ypos, ShipConstants.SUBMARINE_LENGTH, direction, 0, false, "S", "Submarine")
 {
 }
Example #55
0
 public Ship(int size, ShipDirection direction, char shipSymbol)
 {
     this.Size = size;
     this.Direction = direction;
     this.Image = shipSymbol;
 }