Example #1
0
        public static void PlaceCarrierP2(Board playerTwoBoard)
        {
            ASCIIBattleShip.Carrier();
            while (true)
            {
                int           CoorX;
                int           CoorY;
                ShipDirection DirectionOne;


                Console.WriteLine("We will set up the Carrier (5 spaces long) ship now.");
                GameFlowHelper.GetCoorFromUser("What row LETTER (A-J) AND column NUMBER (1-10) would you like to place your ship on?");
                CoorX = GameFlowHelper.GetXcoor();
                CoorY = GameFlowHelper.GetYCoor();

                DirectionOne = GameFlowHelper.GetDirectionFromUser("Great! Now what direction would you like to place your ship? (Up, Down, Left, Right");


                var request = new PlaceShipRequest()
                {
                    Coordinate = new Coordinate(CoorX, CoorY),
                    Direction  = DirectionOne,
                    ShipType   = ShipType.Carrier
                };
                ShipPlacement help = new ShipPlacement();
                help = playerTwoBoard.PlaceShip(request);
                switch (help)
                {
                case ShipPlacement.NotEnoughSpace:
                    Console.WriteLine("Not enough space, try again");
                    continue;

                case ShipPlacement.Overlap:
                    Console.WriteLine("Ship overlap, try again");
                    continue;

                case ShipPlacement.Ok:
                    break;
                }
                Console.Clear();
                break;
            }
        }
Example #2
0
        public static void PlaceShips(Player player)
        {
            for (ShipType s = ShipType.Destroyer; s <= ShipType.Carrier; s++)
            {
                PlaceShipRequest request = new PlaceShipRequest();
                request.ShipType = s;
                Console.WriteLine("Placing " + s);
                request.Coordinate = ConsoleInput.GetCoordinateFromUser();
                request.Direction  = ConsoleInput.GetDirectionFromUser();

                ShipPlacement result = player.board.PlaceShip(request);
                if (result != ShipPlacement.Ok)
                {
                    Console.WriteLine("Could not place " + s + " there because of a(n) " + result);
                    s--;
                }
            }
            Console.Clear();
        }
Example #3
0
        private void PutShipOnBoard(Player player, ShipType typeOfShip)
        {
            PlaceShipRequest newPlacement = new PlaceShipRequest
            {
                ShipType = typeOfShip
            };


            while (true)
            {
                newPlacement.Coordinate = InputAndValidateCoordinate(player, CoordinateRequestType.placement, typeOfShip);

                Console.WriteLine($"And which direction do you want to place it in, {player.name}?");
                Console.Write($"Enter 1 for Up, 2 for Down, 3 for Left or 4 for Right: ");

                string shipDirection  = Console.ReadLine();
                bool   validDirection = int.TryParse(shipDirection, out int result);
                if (!validDirection || (1 > result || result > 4))
                {
                    Console.WriteLine("Invalid entry. Try again.");
                    continue;
                }
                else
                {
                    newPlacement.Direction = (ShipDirection)result;
                    ShipPlacement attemptToPlaceShip = player.board.PlaceShip(newPlacement);
                    if (attemptToPlaceShip == ShipPlacement.NotEnoughSpace)
                    {
                        Console.WriteLine("Not enough space in that direction. Try again.");
                        continue;
                    }
                    else if (attemptToPlaceShip == ShipPlacement.Overlap)
                    {
                        Console.WriteLine("That overlaps with another ship. Try again.");
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
 public bool ValidShipPlacement(ShipPlacement currentPlacement)
 {
     if (currentPlacement == ShipPlacement.Ok)
     {
         return(false);
     }
     else if (currentPlacement == ShipPlacement.NotEnoughSpace)
     {
         Console.ForegroundColor = ConsoleColor.Green;
         Console.WriteLine("You do not have enough room to place that ship there");
         Console.ResetColor();
     }
     else if (currentPlacement == ShipPlacement.Overlap)
     {
         Console.ForegroundColor = ConsoleColor.Green;
         Console.WriteLine("You placement is overlapping with another ship");
         Console.ResetColor();
     }
     return(true);
 }
Example #5
0
        public void ShipSetup()
        {
            ResetBoard();
            UserIO.WriteLine($"Alright {Name}, let's setup your ships.");
            ShipType currentShip;

            for (int i = 0; i < 5; i++)
            {
                currentShip = (ShipType)i;
                UserIO.WriteLine($"Place your {currentShip.ToString()}.");

                PlaceShipRequest request = new PlaceShipRequest()
                {
                    Coordinate = UserIO.GetCoord(),
                    Direction  = UserIO.GetDirection(),
                    ShipType   = currentShip
                };

                ShipPlacement spotValidity = board.PlaceShip(request);
                switch (spotValidity)
                {
                case ShipPlacement.NotEnoughSpace:
                    i--;
                    UserIO.WriteLine("Not enough space to place a ship there!");
                    continue;

                case ShipPlacement.Overlap:
                    i--;
                    UserIO.WriteLine("This spot overlaps with another ship!");
                    break;

                case ShipPlacement.Ok:
                    UserIO.WriteLine("Ship placement works!");
                    break;

                default:
                    break;
                }
            }
            UserIO.Continue();
        }
Example #6
0
        private PlaceShipCommand PlaceShips(int mapWidth, int mapHeight)
        {
            var shipsToPlace = new List <Ship>
            {
                Ship.Battleship,
                Ship.Carrier,
                Ship.Cruiser,
                Ship.Destroyer,
                Ship.Submarine
            };

            List <ShipPlacement> MyShips = new List <ShipPlacement>();

            // for now randomly place ships
            foreach (Ship s in shipsToPlace)
            {
                bool   gotPosB = false;
                Random rnd     = new Random();

                while (gotPosB == false)
                {
                    int x = rnd.Next(0, mapWidth);
                    int y = rnd.Next(0, mapHeight);

                    var       v      = Enum.GetValues(typeof(Direction));
                    Direction newDir = (Direction)v.GetValue(rnd.Next(v.Length));

                    ShipPlacement newShip = new ShipPlacement(new Point(x, y), s, newDir);
                    if ((newShip.IsCollidedB(MyShips) == false) && (newShip.IsOffMapB(mapWidth, mapHeight) == false))
                    {
                        MyShips.Add(newShip);
                        gotPosB = true;
                    }
                }
            }

            return(new PlaceShipCommand
            {
                MyShips = MyShips
            });
        }
Example #7
0
        public static void PlaceShips(Board GameBoard)
        {
            int piecesize = 1;

            for (ShipType piece = ShipType.Destroyer; piece <= ShipType.Carrier; piece++)
            {
                if (piece == ShipType.Cruiser)
                {
                    piecesize = 3;
                }
                else
                {
                    piecesize++;
                }
                Console.Write($"Select a spot for the {piece} ({piecesize} spaces): ");

                Coordinate       shipCor = Input.GetCoordinate();
                ShipDirection    shipdr  = Input.GetShipDirection();
                PlaceShipRequest request = new PlaceShipRequest();
                request.Coordinate = shipCor;
                request.Direction  = shipdr;
                request.ShipType   = piece;
                ShipPlacement verify = GameBoard.PlaceShip(request);
                switch (verify)
                {
                case ShipPlacement.NotEnoughSpace:
                    Console.WriteLine("Ship placement failed.  Not enough space");
                    piece--;
                    piecesize--;
                    break;

                case ShipPlacement.Overlap:
                    Console.WriteLine("Ship placement failed.  Overlaps another ship");
                    piece--;
                    piecesize--;
                    break;
                }
            }
            Console.WriteLine("Board set complete.  Press any key to continue");
            Console.ReadKey();
        }
Example #8
0
        public void placeShipsInput(Board playerBoard, int playerNumber)
        {
            int  xValue;
            int  yValue;
            bool verified;

            PlaceShipRequest newShipRequest = new PlaceShipRequest();
            ShipPlacement    checkShip      = new ShipPlacement();

            foreach (var item in Enum.GetValues(typeof(ShipType)))
            {
                verified = false;
                while (verified == false)
                {
                    Console.WriteLine($"Player {playerNumber}, please enter the coordinates for your {item}.");
                    xValue = getXCoordinate();
                    yValue = getYCoordinate();
                    newShipRequest.Coordinate = coordinate(xValue, yValue);
                    newShipRequest.Direction  = directionType();
                    newShipRequest.ShipType   = (ShipType)item;
                    //place a ship and repeat if ship does not fit
                    checkShip = playerBoard.PlaceShip(newShipRequest);
                    if (checkShip == ShipPlacement.NotEnoughSpace)
                    {
                        Console.WriteLine("There is not enough space for that ship.");
                    }
                    else if (checkShip == ShipPlacement.Overlap)
                    {
                        Console.WriteLine("There is already a ship there!");
                    }
                    else if (checkShip == ShipPlacement.Ok)
                    {
                        Console.WriteLine();
                        verified = true;
                    }
                }
            }
            Console.Clear();
            Console.WriteLine("Press any key when you are ready to begin, Player {0}.", playerNumber);
            Console.ReadKey();
        }
Example #9
0
        //putShip method is called with createShip() after taking each player's names.
        private void putShips(string playerName, Board board, ShipType type)
        {
            Console.Clear();
            PlaceShipRequest request = new PlaceShipRequest();

            while (true)
            {
                //tell the user to place ship and what ship they are placing.
                //based on the ship eunm.
                Console.WriteLine($"{playerName} place your " + type);

                Coordinate    coordinate = ci.AskCoordinate(playerName);
                ShipDirection direction  = ci.AskShipDirection(playerName);
                request.ShipType = type;
                //call the coordinate method and the direction method for each ship placement
                request.Coordinate = coordinate;
                request.Direction  = direction;

                //using the ship placement enum in a switch statement to tell the user ship placement ok or not
                //if not keep asking until a valid input is made.

                ShipPlacement sp = board.PlaceShip(request);
                switch (sp)
                {
                case ShipPlacement.Ok:
                    return;

                case ShipPlacement.Overlap:
                    Console.WriteLine($"{playerName}, space taken. Please re-try");
                    break;

                case ShipPlacement.NotEnoughSpace:
                    Console.WriteLine($"{playerName}, not enough space. Please re-try ");
                    break;

                default:
                    Console.WriteLine("What happened?");
                    break;
                }
            }
        }
Example #10
0
        public bool isPlacementValid(ShipPlacement placement)
        {
            if (placement == ShipPlacement.Overlap)
            {
                Console.WriteLine("\nYour placement overlaps another ship.");
                Console.WriteLine("Press ENTER to try again...");
                Console.ReadLine();
                Console.Clear();
                return(false);
            }
            else if (placement == ShipPlacement.NotEnoughSpace)
            {
                Console.WriteLine("\nNot enough space.");
                Console.WriteLine("Press ENTER to try again...");
                Console.ReadLine();
                Console.Clear();
                return(false);
            }

            return(true);
        }
        public void AddBattleship_Fails_When_Board_isnull()
        {
            //Arrange
            var mockDataStore = new Mock <IInMemoryDataStore>();

            mockDataStore.Setup(x => x.GetPlayer(It.IsAny <string>()))
            .Returns(() => new Player("Alice"));


            var battleshipGameService = new BattleshipGameService(mockDataStore.Object);

            string        player        = "Alice";
            Ship          ship          = new Ship(2);
            Coordinates   startPosition = new Coordinates(1, 2);
            ShipPlacement shipPlacement = ShipPlacement.Row;


            var exception = Assert.Throws <BattleshipGameException>(() => battleshipGameService.AddBattleship(player, ship, startPosition, shipPlacement));

            Assert.Equal("Alice does not have a game Board.", exception.Message);
        }
Example #12
0
        public void CanNotPlaceShipOffBoard()
        {
            Board board = new Board();
            //PlaceShipRequest request = new PlaceShipRequest()
            //{
            //    Coordinate = new Coordinate(15, 10),
            //    Direction = ShipDirection.Up,
            //    ShipType = ShipType.Destroyer
            //};
            PlaceShipRequest request = new PlaceShipRequest();

            request.Direction  = ShipDirection.Up;
            request.ShipType   = ShipType.Destroyer;
            request.Coordinate = new Coordinate(15, 10);

            ShipPlacement response = new ShipPlacement();

            response = board.PlaceShip(request);

            Assert.AreEqual(ShipPlacement.NotEnoughSpace, response);
        }
Example #13
0
        public bool CanPlace(IBattlefield battlefield, ShipPlacement placement)
        {
            var shipPositions = _battleshipPlacement.GetShipPositions(placement);

            foreach (var shipPosition in shipPositions)
            {
                if (battlefield.Cells.TryGetValue(shipPosition, out var cell))
                {
                    if (cell.HasShipPlaced)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Example #14
0
        public void ShipSetup()
        {
            Console.WriteLine($"Alright {name}, lets setup your ships.");

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine($"Place your {Enum.GetName(typeof(ShipType), (ShipType)i)}.");

                PlaceShipRequest shipPlaceFromUsr = new PlaceShipRequest()
                {
                    Coordinate = ConsoleIO.GetCoord(),
                    Direction  = ConsoleIO.GetDirection(),
                    ShipType   = (ShipType)i
                };

                ShipPlacement spotValidity = board.PlaceShip(shipPlaceFromUsr);
                switch (spotValidity)
                {
                case ShipPlacement.NotEnoughSpace:
                    i--;
                    Console.WriteLine("Not enough Space to place a ship there!");
                    continue;

                case ShipPlacement.Overlap:
                    i--;
                    Console.WriteLine("This spot overlaps with another ship!");
                    break;

                case ShipPlacement.Ok:
                    Console.WriteLine("Ship placement works!");
                    break;

                default:
                    break;
                }
            }
            ConsoleIO.Continue();
        }
Example #15
0
        public static Ship[] PlaceShipTest2(Board x)

        {
            for (int k = 0; k < 5; k++)
            {
                bool             repeat     = true;
                PlaceShipRequest NewRequest = new PlaceShipRequest();
                do
                {
                    NewRequest = GameFlow.Request(x, k);


                    x.CheckCoordinate(NewRequest.Coordinate);


                    ShipPlacement Test = new ShipPlacement();

                    Test = x.PlaceShip(NewRequest);

                    if (Test == ShipPlacement.Overlap)
                    {
                        repeat = true;
                        Console.WriteLine("Oops, there was an overlap, let's try that again");
                    }
                    else if (Test == ShipPlacement.NotEnoughSpace)
                    {
                        repeat = true;
                        Console.WriteLine("No room there, try again");
                    }
                    else if (Test == ShipPlacement.Ok)
                    {
                        repeat = false;
                        Console.WriteLine("That works!");
                    }
                }while (repeat == true);
            }
            return(x.Ships);
        }
Example #16
0
        public static void PlaceShip(string name, Board board)
        {
            Console.WriteLine($"{name} Place your ship: ");

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine($"Place your {Enum.GetName(typeof(ShipType), (ShipType)i)}.");

                PlaceShipRequest request = new PlaceShipRequest();
                {
                    request.Coordinate = ConsoleIO.GetCoord();
                    request.Direction  = ConsoleIO.GetDirection();
                    request.ShipType   = (ShipType)i;
                };

                ShipPlacement spacevalidity = board.PlaceShip(request);
                switch (spacevalidity)
                {
                case ShipPlacement.NotEnoughSpace:
                    i--;
                    Console.WriteLine("Not enough space, place somewhere else.");
                    continue;

                case ShipPlacement.Overlap:
                    i--;
                    Console.WriteLine("Overlap another ship, place somewhere else.");
                    continue;

                case ShipPlacement.Ok:
                    Console.WriteLine("Good spot!");
                    break;

                default:
                    break;
                }
            }
        }
Example #17
0
        public ShipPlacement PlaceShip(PlaceShipRequest request, out Ship newShip)
        {
            newShip = null;
            if (_currentShipIndex > 7)
            {
                throw new Exception("You can not add another ship, 7 is the limit!");
            }

            if (!IsValidCoordinate(request.Coordinate))
            {
                return(ShipPlacement.NotEnoughSpace);
            }

            Ship newTempShip = ShipCreator.CreateShip(request.ShipType, this);

            ShipPlacement Placement = newTempShip.SetShipPositions(request.Coordinate);

            if (Placement == ShipPlacement.Ok)
            {
                AddShipToBoard(newTempShip);
                newShip = newTempShip;
            }
            return(Placement);
        }
Example #18
0
        public static void PlaceShips(Board board)
        {
            foreach (var item in Enum.GetValues(typeof(ShipType)))
            {
                while (true)
                {
                    Console.WriteLine($"\nPlace your {item}");

                    PlaceShipRequest request = new PlaceShipRequest
                    {
                        Coordinate = UserIO.EnterCoordinates(),
                        Direction  = UserIO.Direction(),
                        ShipType   = (ShipType)item, //set up loop to rotate current ship
                    };
                    ShipPlacement response = new ShipPlacement();
                    response = board.PlaceShip(request);
                    switch (response)
                    {
                    case ShipPlacement.NotEnoughSpace:
                        Console.Clear();
                        Console.WriteLine($"Could not place {item}: Not enough space.\nPlease try again.");
                        continue;

                    case ShipPlacement.Overlap:
                        Console.Clear();
                        Console.WriteLine($"Could not place {item}: Ship overlap.\nPlease try again");
                        continue;

                    case ShipPlacement.Ok:
                        break;
                    }
                    break;
                }
                Console.Clear();
            }
        }
        public bool AddBattleship(string playerName, Ship ship, Coordinates startPosition, ShipPlacement shipPlacement)
        {
            ValidatePlayer(playerName);

            IsShipProvided(ship);

            var player = _inMemoryDataStore.GetPlayer(playerName);

            DoesPlayerExist(player);

            var board = player.Board;

            DoesBoardExist(playerName, board);


            if (board.AttackHasStarted)
            {
                throw new
                      BattleshipGameException("Attack has already started, you cannot add battleships now.");
            }


            var boardSize = board.Blocks.GetLength(0);

            ValidateCoordinates(startPosition, boardSize);

            ValidateShipLength(ship, boardSize);

            if (shipPlacement == ShipPlacement.Row)
            {
                //row is fixed
                int row = startPosition.Row;

                if ((startPosition.Column + ship.Length) > boardSize)
                {
                    throw new BattleshipGameException($"Cannot add battleship at this position " +
                                                      $"as the ship will go out of the board ");
                }

                for (int col = startPosition.Column; col < startPosition.Column + ship.Length; col++)
                {
                    var block = board.Blocks[row, col];
                    ValidateIsBlockOccupied(block);
                }


                for (int col = startPosition.Column; col < startPosition.Column + ship.Length; col++)
                {
                    var block = board.Blocks[row, col];
                    block.Occupant = ship;
                }
            }
            else
            {
                //col is fixed
                int col = startPosition.Column;


                if ((startPosition.Row + ship.Length) > boardSize)
                {
                    throw new BattleshipGameException($"Cannot add battleship at this position " +
                                                      $"as the ship will go out of the board ");
                }


                for (int row = startPosition.Row; row < startPosition.Row + ship.Length; row++)
                {
                    var block = board.Blocks[row, col];
                    ValidateIsBlockOccupied(block);
                }


                for (int row = startPosition.Row; row < startPosition.Row + ship.Length; row++)
                {
                    var block = board.Blocks[row, col];
                    block.Occupant = ship;
                }
            }

            return(_inMemoryDataStore.UpdateBoard(playerName, board));
        }
Example #20
0
        private void SetUp()
        {
            for (var i = 0; i < 5; i++)
            {
                do
                {
                    Coordinate       coord     = AskCoordinate();
                    ShipDirection    direction = AskDirection();
                    ShipType         type      = AskShipType();
                    PlaceShipRequest req       = new PlaceShipRequest();
                    req.Coordinate = coord;
                    req.Direction  = direction;
                    req.ShipType   = type;
                    ShipPlacement sp = p1board.PlaceShip(req);
                    if (sp == ShipPlacement.NotEnoughSpace)
                    {
                        Console.WriteLine("Not enough space to put a ship there! Try again!\n");
                        nextShip = false;
                    }
                    else if (sp == ShipPlacement.Overlap)
                    {
                        Console.WriteLine("That ship would overlap one you already placed! Try again!\n");
                        nextShip = false;
                    }
                    else // shipplacement.ok
                    {
                        nextShip = true;
                    }
                } while (!nextShip);
            }

            Console.Clear();
            Console.WriteLine("{0}'s turn!!", player2name);

            for (int i = 0; i < 5; i++)
            {
                do
                {
                    Coordinate       coord     = AskCoordinate();
                    ShipDirection    direction = AskDirection();
                    ShipType         type      = AskShipType();
                    PlaceShipRequest req       = new PlaceShipRequest();
                    req.Coordinate = coord;
                    req.Direction  = direction;
                    req.ShipType   = type;
                    ShipPlacement sp = p2board.PlaceShip(req);
                    if (sp == ShipPlacement.NotEnoughSpace)
                    {
                        Console.WriteLine("Not enough space to put a ship there! Try again!");
                        nextShip = false;
                    }
                    if (sp == ShipPlacement.Overlap)
                    {
                        Console.WriteLine("That ship would overlap one you already placed! Try again!");
                        nextShip = false;
                    }
                    else // shipplacement.ok
                    {
                        nextShip = true;
                    }
                } while (!nextShip);
            }

            Console.Clear();
        }
Example #21
0
        private void ShipPlacementRequest()
        {
            var request = new PlaceShipRequest
            {
                Coordinate = new Coordinate(_xCoordinate,_yCoordinate),
                Direction = _shipDirection,
                ShipType = _shipType
            };

            if (_player1Turn)
            {
                _response = player1Board.PlaceShip(request);
            }
            else
            {
                _response = player2Board.PlaceShip(request);
            }

            switch (_response)
            {
                case ShipPlacement.Overlap:
                    Console.WriteLine("\n*Coordinates result in overlapping ship locations*\n");
                    break;
                case ShipPlacement.NotEnoughSpace:
                    Console.WriteLine("\n*Coordinates exceed board parameters*\n");
                    break;
                case ShipPlacement.Ok:
                    Console.WriteLine("\nShip placed successfully! Press any key to continue.");
                    Console.ReadKey();
                    break;
            }
        }
Example #22
0
        public MapGenerator(int mapWidth, int mapHeight, int maxShots)
        {
            Height = mapHeight;
            Width  = mapWidth;

            // 1. Randomly Place ships
            var shipsToPlace = new List <Ship>
            {
                Ship.Battleship,
                Ship.Carrier,
                Ship.Cruiser,
                Ship.Destroyer,
                Ship.Submarine
            };

            List <ShipPlacement> MyShips = new List <ShipPlacement>();

            // for now randomly place ships
            foreach (Ship s in shipsToPlace)
            {
                bool   gotPosB = false;
                Random rnd     = new Random();

                while (gotPosB == false)
                {
                    int x = rnd.Next(0, mapWidth);
                    int y = rnd.Next(0, mapHeight);

                    var       v      = Enum.GetValues(typeof(Direction));
                    Direction newDir = (Direction)v.GetValue(rnd.Next(v.Length));

                    ShipPlacement newShip = new ShipPlacement(new Point(x, y), s, newDir);
                    if ((newShip.IsCollidedB(MyShips) == false) && (newShip.IsOffMapB(mapWidth, mapHeight) == false))
                    {
                        MyShips.Add(newShip);
                        gotPosB = true;
                    }
                }
            }
            // assign list of ships
            ShipList = MyShips;


            // 2. Randomly choose number of shots
            Random rand     = new Random();
            int    numShots = 0;

            if (maxShots != 0)
            {
                numShots = rand.Next(1, maxShots + 1);
                Shots    = numShots;
            }

            // 3. Choose random co-ords to shoot at
            // create list
            CurrentMap.Cells = new List <MapSpace>();
            for (int i = 0; i < mapWidth * mapHeight; i++)
            {
                MapSpace nextSpace = new MapSpace(i % mapWidth, (int)(i / mapHeight));
                nextSpace.State = SpaceState.Open;
                CurrentMap.Cells.Add(nextSpace);
            }
            while (numShots > 0)
            {
                bool foundOpenB = false;

                while (foundOpenB == false)
                {
                    int shotX = rand.Next(0, mapWidth);
                    int shotY = rand.Next(0, mapHeight);

                    if (CurrentMap.GetSpace(shotX, shotY).State == SpaceState.Open)
                    {
                        foundOpenB = true;

                        bool isHitB = false;
                        foreach (ShipPlacement s in ShipList)
                        {
                            if (s.IsCollidedB(CurrentMap.GetSpace(shotX, shotY).Coords))
                            {
                                isHitB = true;
                                break;
                            }
                        }

                        if (isHitB == true)
                        {
                            Hits++;
                            CurrentMap.GetSpace(shotX, shotY).State = SpaceState.Hit;
                        }
                        else
                        {
                            Misses++;
                            CurrentMap.GetSpace(shotX, shotY).State = SpaceState.Miss;
                        }
                    }
                }
                numShots--;
            }
        }
 public void SpecifyAShip(string shipName, string gridReference, string orientation)
 {
     _shipPlacement = new ShipPlacement(shipName, gridReference, orientation);
 }
Example #24
0
        //Places ships onto the selected player's board.
        private void PlaceShips(Player player)
        {
            ShipDirection orientation   = ShipDirection.Down;
            ShipPlacement shipPlacement = ShipPlacement.NotEnoughSpace;

            //Requires the player to place each ship, in order, one at a time.
            do
            {
                string prompt  = "Place your destroyer. (Size: 2)";
                var    request = new PlaceShipRequest
                {
                    Coordinate = RequestCoordinate(player, prompt, 2, out orientation),
                    Direction  = orientation,
                    ShipType   = ShipType.Destroyer
                };
                shipPlacement = player.Board.PlaceShip(request);

                if (shipPlacement != ShipPlacement.Ok)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Warning: You cannot move there.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            } while (shipPlacement != ShipPlacement.Ok);
            playerPlacedShips++;

            //Requires the player to place each ship, in order, one at a time.
            do
            {
                string prompt  = "Place your cruiser. (Size: 3)";
                var    request = new PlaceShipRequest
                {
                    Coordinate = RequestCoordinate(player, prompt, 3, out orientation),
                    Direction  = orientation,
                    ShipType   = ShipType.Cruiser
                };
                shipPlacement = player.Board.PlaceShip(request);

                if (shipPlacement != ShipPlacement.Ok)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Warning: You cannot move there.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            } while (shipPlacement != ShipPlacement.Ok);
            playerPlacedShips++;

            //Requires the player to place each ship, in order, one at a time.
            do
            {
                string prompt  = "Place your submarine. (Size: 3)";
                var    request = new PlaceShipRequest
                {
                    Coordinate = RequestCoordinate(player, prompt, 3, out orientation),
                    Direction  = orientation,
                    ShipType   = ShipType.Submarine
                };
                shipPlacement = player.Board.PlaceShip(request);

                if (shipPlacement != ShipPlacement.Ok)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Warning: You cannot move there.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            } while (shipPlacement != ShipPlacement.Ok);
            playerPlacedShips++;

            //Requires the player to place each ship, in order, one at a time.
            do
            {
                string prompt  = "Place your battleship. (Size: 4)";
                var    request = new PlaceShipRequest
                {
                    Coordinate = RequestCoordinate(player, prompt, 4, out orientation),
                    Direction  = orientation,
                    ShipType   = ShipType.Battleship
                };
                shipPlacement = player.Board.PlaceShip(request);

                if (shipPlacement != ShipPlacement.Ok)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Warning: You cannot move there.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            } while (shipPlacement != ShipPlacement.Ok);
            playerPlacedShips++;

            //Requires the player to place each ship, in order, one at a time.
            do
            {
                string prompt  = "Place your carrier. (Size: 5)";
                var    request = new PlaceShipRequest
                {
                    Coordinate = RequestCoordinate(player, prompt, 5, out orientation),
                    Direction  = orientation,
                    ShipType   = ShipType.Carrier
                };
                shipPlacement = player.Board.PlaceShip(request);

                if (shipPlacement != ShipPlacement.Ok)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Warning: You cannot move there.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            } while (shipPlacement != ShipPlacement.Ok);
            playerPlacedShips++;

            PlayerShipDisplay(player, "All ships placed.\nPress any key to continue...");
            Console.ReadKey();

            //Clears number of ships placed.
            playerPlacedShips = 0;

            //Hides the board
            Console.Clear();
        }
Example #25
0
        public void PlaceShip(Board board, string currentPlayerName)
        {
            int shipType = 0;


            do
            {
                int moveOn = 0;

                _gameView.DisplayShipPlacement(board);

                Coordinate coord = _gameInput.PromptForCoordinate(string.Format("\n\n{0}, select a coordinate to place your {1} (e.g. A2): ", currentPlayerName, (ShipType)shipType));

                do
                {
                    Console.WriteLine("\nUsing a numeric value, which direction would you like to point your {1}, {0}?", currentPlayerName, (ShipType)shipType);
                    Console.Write("1 = Up, 2 = Down, 3 = Left, 4 = Right: ");
                    string shipDirectionString = Console.ReadLine();
                    if (shipDirectionString == "1" || shipDirectionString == "2" || shipDirectionString == "3" || shipDirectionString == "4")
                    {
                        int shipDirection = Convert.ToInt32(shipDirectionString);
                        moveOn++;

                        if (coord.XCoordinate >= 1 && coord.XCoordinate <= 10 && coord.YCoordinate >= 1 && coord.YCoordinate <= 10)
                        {
                            PlaceShipRequest placementRequest = new PlaceShipRequest();
                            placementRequest.ShipType   = (ShipType)shipType;
                            placementRequest.Coordinate = coord;
                            placementRequest.Direction  = (ShipDirection)shipDirection - 1;

                            ShipPlacement shipPlacement = board.PlaceShip(placementRequest);

                            switch (shipPlacement)
                            {
                            case ShipPlacement.NotEnoughSpace:
                                Console.Write("There is not enough space on the board for you {0}.  Press any key to give a new coordinate.", (ShipType)shipType);
                                Console.ReadKey();
                                break;

                            case ShipPlacement.Overlap:
                                Console.Write("Your {0} overlaps with an already placed ship.  Press any key to give a new coordinate.", (ShipType)shipType);
                                Console.ReadKey();
                                break;

                            case ShipPlacement.Ok:
                                shipType++;
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            Console.Write("\nThe coordinate you gave was invalid.  Press any key to give a new coordinate.", (ShipType)shipType);
                            Console.ReadKey();
                        }

                        Console.Clear();
                    }
                    else
                    {
                        Console.Write("\nThat was not a valid ship direction. Please give a new ship direction.\n");
                    }
                } while (moveOn == 0);
            } while (shipType < 5);
        }
Example #26
0
        private void PlaceAllActivePlayerShips()
        {
            if (activePlayer == player2)
            {
                Console.WriteLine();
                Console.WriteLine();
            }


            AvertYourEyes(activePlayer.name + ", press enter when it is safe to deploy your ships... ");

            Dictionary <ShipType, int> unplacedShips = new Dictionary <ShipType, int>();

            unplacedShips.Add(ShipType.Carrier, 5);
            unplacedShips.Add(ShipType.Battleship, 4);
            unplacedShips.Add(ShipType.Submarine, 3);
            unplacedShips.Add(ShipType.Cruiser, 3);
            unplacedShips.Add(ShipType.Destroyer, 2);

            while (unplacedShips.Count > 0)
            {
                PlaceShipRequest shipRequest     = GetShipPlacementRequestFromUser(activePlayer, unplacedShips);
                ShipPlacement    placementStatus = activePlayer.board.PlaceShip(shipRequest);

                switch (placementStatus)
                {
                case ShipPlacement.Ok:
                    unplacedShips.Remove(shipRequest.ShipType);

                    DisplayScreenTitle(activePlayer.name + " Ship Deployment");
                    activePlayer.board.DisplayAll();
                    Console.ForegroundColor = TextEffects.HighlightColor;
                    if (shipRequest.ShipType == ShipType.Carrier)
                    {
                        TextEffects.CenterAlignWriteLine("Aircraft Carrier deployment sucessful!");
                    }
                    else
                    {
                        TextEffects.CenterAlignWriteLine(shipRequest.ShipType + " deployment sucessful!");
                    }
                    Console.WriteLine();
                    Console.ResetColor();
                    TextEffects.CenterAlignWrite("Press enter to continue...");
                    Console.ReadLine();
                    Console.Clear();
                    continue;

                case ShipPlacement.NotEnoughSpace:
                    DisplayScreenTitle(activePlayer.name + " Ship Deployment");
                    activePlayer.board.DisplayAll();
                    Console.ForegroundColor = TextEffects.HighlightColor;
                    TextEffects.CenterAlignWriteLine("But captain, that would place the ship outside of the battle zone!");
                    Console.WriteLine();
                    Console.ResetColor();
                    TextEffects.CenterAlignWrite("Let me ask again. (Press enter)...");
                    Console.ReadLine();
                    Console.Clear();
                    continue;

                case ShipPlacement.Overlap:
                    DisplayScreenTitle(activePlayer.name + " Ship Deployment");
                    activePlayer.board.DisplayAll();
                    Console.ForegroundColor = TextEffects.HighlightColor;
                    TextEffects.CenterAlignWriteLine("But captain, that would overlap one of our ships!");
                    Console.WriteLine();
                    Console.ResetColor();
                    TextEffects.CenterAlignWrite("Let me ask again. (Press enter)...");
                    Console.ReadLine();
                    Console.Clear();
                    continue;
                }
            }
        }
Example #27
0
        public static Player SetupBoards(Player player)
        {
            ShipType      shipType;
            Coordinate    coordinate;
            ShipDirection shipDirection;

            // Gets and preps ship locations from user.  The for loop ensures no more than 5 ships
            // get placed onto board.
            PrintBoard(player.displayBoard);

            for (int i = 0; i < 5; i++)
            {
                bool valid = false;
                while (!valid)
                {
                    //PrintBoard(playerBoard);
                    Console.WriteLine("{0}, place ship {1}. ", player.playerName, i + 1);

                    // This method retrieves the type of ship from the player
                    shipType = GetShipType(player);

                    // This method retrieves coordinates from the player
                    coordinate = GetCoordinate(player);

                    // This method retrieves the direction the ship should be placed from the player
                    shipDirection = GetShipDirection(player);

                    // Next we input the 3 parameters specified by the player into the PlaceShipRequest method
                    PlaceShipRequest PlaceShipRequest = new PlaceShipRequest()
                    {
                        Coordinate = coordinate,
                        Direction  = shipDirection,
                        ShipType   = shipType
                    };

                    // The ShipPlacement method then attempts to place ship onto board
                    ShipPlacement value = player.internalBoard.PlaceShip(PlaceShipRequest);
                    if (value == ShipPlacement.NotEnoughSpace)
                    {
                        Console.Clear();
                        PrintBoard(player.displayBoard);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Not enough space to place ship. Press enter and try again.");
                        Console.ResetColor();
                        Console.ReadLine();
                        Console.Clear();
                        valid = false;
                    }
                    else if (value == ShipPlacement.Overlap)
                    {
                        Console.Clear();
                        PrintBoard(player.displayBoard);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("This ship overlaps another. Press enter and try again.");
                        Console.ResetColor();
                        Console.ReadLine();
                        valid = false;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Ship was succesfully placed! Press Enter to continue.");
                        Console.ResetColor();
                        player = PlaceShipOnBoard(player, i);
                        Console.ReadLine();
                        valid = true;
                    }
                }
            }
            Console.Clear();
            return(player);
        }
Example #28
0
        //New SetBoard Method
        public static void SetBoard(Player[] players)
        {
            Console.Clear();

            for (int p = 0; p < players.Length; p++)
            {
                Console.Clear();
                Console.WriteLine(
                    "{0}, you will now place your 5 battleships: Destroyer (2 coordinates), Submarine (3), Cruiser (3), Battleship (4), Carrier (5)." +
                    "\nPress Enter to continue."
                    ,
                    players[p].Name);
                Console.ReadLine();
                for (int s = 0; s < 5; s++)
                {
                    ShipPlacement placementIsValid = new ShipPlacement();
                    ShipType shipType = (ShipType) s;

                    int shipLength = 0;
                    switch (s)
                    {
                        case 0:
                            shipLength = 2;
                            break;
                        case 1:
                        case 2:
                            shipLength = 3;
                            break;
                        case 3:
                            shipLength = 4;
                            break;
                        case 4:
                            shipLength = 5;
                            break;
                    }

                    do
                    {
                        Console.Clear();
                        DrawShipPlacement(players[p]);
                        Console.WriteLine("\n\n\n{0}, get ready to place your {1} ({2} coordinates)", players[p].Name,
                            shipType.ToString(), shipLength);
                        Console.WriteLine(
                            "\nFirst, choose an initial coordinate (alphanumeric) within the 10x10 grid for your ship.\n\nWe will ask for the direction/orientation of the ship afterward.");

                        string coordString = Console.ReadLine();
                        Coordinate baseCoord = Convert(coordString);

                        PlaceShipRequest requestShip = new PlaceShipRequest();
                        requestShip.Coordinate = baseCoord;
                        requestShip.ShipType = (ShipType) s;

                        Console.WriteLine("{0}, now choose a direction to place your {1} ({2} coordinates):\n" +

                                          "(U)p, (D)own, (L)eft, or (R)ight.", players[p].Name, shipType.ToString(),
                            shipLength);

                        bool validShipDirection = false;

                        string shipDirection = Console.ReadLine().ToUpper();
                        while (!validShipDirection)
                        {
                            switch (shipDirection)
                            {
                                case "R":
                                    requestShip.Direction = ShipDirection.Right;
                                    validShipDirection = true;
                                    break;
                                case "L":
                                    requestShip.Direction = ShipDirection.Left;
                                    validShipDirection = true;
                                    break;
                                case "U":
                                    requestShip.Direction = ShipDirection.Up;
                                    validShipDirection = true;
                                    break;
                                case "D":
                                    requestShip.Direction = ShipDirection.Down;
                                    validShipDirection = true;
                                    break;
                                default:
                                    Console.WriteLine(
                                        "That is not a valid direction. Please choose (U)p, (D)own, (L)eft or (R)ight.");
                                    shipDirection = Console.ReadLine().ToUpper();
                                    break;
                            }
                        }
                        placementIsValid = players[p].PlayerBoard.PlaceShip(requestShip);

                        switch (placementIsValid)
                        {
                            case ShipPlacement.NotEnoughSpace:
                                Console.WriteLine("There is not enough space to place the ship there. Try again.");
                                break;
                            case ShipPlacement.Overlap:
                                Console.WriteLine("The ship is overlapping with a previously placed ship. Try again.");
                                break;
                            default:
                                Console.WriteLine("That ship placement is OK!!");
                                break;
                        }

                        //Console.WriteLine(placementIsValid);
                        Console.ReadLine();

                    } while (placementIsValid != ShipPlacement.Ok);

                    //Adding ship to ShipBoard Dictionary
                    Ship shipToDraw = players[p].PlayerBoard._ships[s];

                    foreach (Coordinate shipCoord in shipToDraw.BoardPositions)
                    {
                        players[p].PlayerBoard.ShipBoard.Add(shipCoord, shipToDraw.ShipType);
                    }

                    Console.Clear();
                    DrawShipPlacement(players[p]);

                    Console.WriteLine("\n\nCongratulations, {0}! You have placed your {1}. Press enter to continue...",
                        players[p].Name, shipType.ToString());
                    Console.ReadLine();
                }
            }
        }