示例#1
0
        public void ShouldPlaceAShip_WhenCorrectPositionsProvided(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            ShipType shipType)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //act
            //now place the ship on the board
            var shipPlacer = new ShipPlacer();

            shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn);

            //assert

            /*check that the ship has been placed on the board and that the board's
             * status is occupied for the ship*/
            Assert.True(
                board.BoardCellStatuses[placementRow, placementColumn] == BoardCellStatus.Occupied &&
                board.BoardCellStatuses[placementRow, placementColumn + ship.Size - 1] == BoardCellStatus.Occupied
                );
        }
示例#2
0
        public void ShouldReturnCorrectAttackStatus_WhenAttackLaunched(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            int attackRow, int attackColumn,
            ShipType shipType, BoardCellStatus boardCellStatus)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //place the ship on the board
            var shipPlacer = new ShipPlacer();

            shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn);

            //act
            //now attack the ship at the given position
            var attacker = new Attacker();

            attacker.Attack(board, attackRow, attackColumn);

            //assert
            /*check that the status on the board is hit*/
            Assert.True(
                board.BoardCellStatuses[attackRow, attackColumn] == boardCellStatus
                );
        }
示例#3
0
            public when_placing_a_ship_of_length_four_diagonally_down_and_left()
            {
                _mockCoordsPlacer = new MockCoordGenerator(new[] { 'j' }, new[] { '1' });
                var shipPlacer = new ShipPlacer(_mockCoordsPlacer.GenerateCoords);

                board = shipPlacer.PlaceShipOfLength(new GameBoard(), 4, () => ShipDirection.DiagonallyDownAndLeft);
            }
示例#4
0
            public when_placing_a_ship_of_length_four_vertically()
            {
                var mockCoordsPlacer = new MockCoordGenerator(new[] { 'a' }, new[] { '1' });
                var shipPlacer       = new ShipPlacer(mockCoordsPlacer.GenerateCoords);

                board = shipPlacer.PlaceShipOfLength(new GameBoard(), 4, () => ShipDirection.Vertical);
            }
示例#5
0
                public when_placing_a_ship_horizontally()
                {
                    var mockCoordsPlacer = new MockCoordGenerator(new[] { 'g' }, new[] { '1' });
                    var shipPlacer       = new ShipPlacer(mockCoordsPlacer.GenerateCoords);

                    board = shipPlacer.PlaceShipOfLength(new GameBoard(), 4, () => ShipDirection.Horizontal);
                }
        public void PlaceRandomly_GridIsEmptyAndRandomChoosesFirstPossiblePlacement_PlacedShipOnGrid(Ship ship,
                                                                                                     List <List <Cell> > possiblePlacements)
        {
            var randomIndexGeneratorStub             = new Mock <IRandomGenerator>();
            var shipPossiblePlacementsCalculatorStub = new Mock <IShipPossiblePlacementsCalculator>();
            var modifiedGrid = EmptyGridGenerator.GenerateEmptyGridOfSize(Constants.GridSize);

            shipPossiblePlacementsCalculatorStub.Setup(s => s.CalculatePossiblePlacements(ship, modifiedGrid))
            .Returns(possiblePlacements);
            randomIndexGeneratorStub.Setup(r => r.GetRandomNumberFromRange(0, possiblePlacements.Count))
            .Returns((int minValue, int maxValue) => minValue);
            const int firstIndex      = 0;
            var       chosenPlacement = possiblePlacements[firstIndex];
            var       shipPlacer      = new ShipPlacer(randomIndexGeneratorStub.Object, shipPossiblePlacementsCalculatorStub.Object);
            var       actualResult    = EmptyGridGenerator.GenerateEmptyGridOfSize(Constants.GridSize);

            foreach (var cell in chosenPlacement)
            {
                actualResult[cell.Y][cell.X] = true;
            }

            shipPlacer.PlaceRandomly(ship, modifiedGrid);

            Assert.That(modifiedGrid, Is.EqualTo(actualResult));
        }
        private static string GetTileValue(Boards.BoardTile tile, bool enemy)
        {
            string s = "    ";

            if (tile.Ship != null && tile.Destroyed && (!enemy || tile.Ship.HP == 0))
            {
                s = $"{HIT[0]}{tile.Ship.Index.ToString(),BOX_WIDTH - 4}{HIT[1]}";                                                                       // known ship hits
            }
            else if (enemy && tile.Ship != null && tile.Destroyed)
            {
                s = $" {HIT,BOX_WIDTH - 4} ";                                                    // hits on unknown ships
            }
            else if (tile.Destroyed)
            {
                s = $" {MISS,BOX_WIDTH - 4} ";                      // missed shots
            }
            else if (!enemy && tile.Ship != null)
            {
                s = $" {tile.Ship.Index.ToString(),BOX_WIDTH - 4} ";                                   // show shop on friendly map
            }
            else if (ShipPlacerController.Start != null && ShipPlacer.IsValidEndPoint(tile.Coords))
            {
                s = $" {VALID_PLACE,BOX_WIDTH - 4} ";                                                                                     // valid end point for ship
            }
            int ws = (BOX_WIDTH - 2 - s.Length);

            return(s.PadLeft((int)Math.Floor((float)ws / 2) + s.Length).PadRight(ws + s.Length));
        }
示例#8
0
        public void ShouldReturnException_WhenIncorrectAttackCoordinatesProvided(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            int attackRow, int attackColumn,
            ShipType shipType)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //place the ship on the board
            var shipPlacer = new ShipPlacer();

            shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn);

            //act
            //now attack the ship at the given position
            var attacker = new Attacker();
            IndexOutOfRangeException ex = Assert.Throws <IndexOutOfRangeException>(() =>
                                                                                   attacker.Attack(board, attackRow, attackColumn));

            //assert
            Assert.Equal("Attack position is out of bounds", ex.Message);
        }
示例#9
0
        public void ShouldNotReturnLostGameStatusTrue_WhenShipsNotSunk()
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(10, 10);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(ShipType.Destroyer);

            //place the ship on the board
            var shipPlacer = new ShipPlacer();

            shipPlacer.AddShipToBoard(ship, board, 0, 0);

            //act
            //now attack the ship at all given positions for the ship
            var attacker = new Attacker();

            attacker.Attack(board, 0, 1);

            //assert that the status is not lost
            Assert.False(board.HasLost);
        }
示例#10
0
        public void PlaceShip_BoardContainsShip_CorrectlyPlacesShip()
        {
            // Arrange
            var shipToPlace = new Destroyer();

            var existingShipPlacement = new List <Point>
            {
                new Point {
                    X = 5, Y = 5
                },
                new Point {
                    X = 5, Y = 4
                },
                new Point {
                    X = 5, Y = 3
                },
                new Point {
                    X = 5, Y = 2
                }
            };

            var existingBoard = new Board.Board();

            existingBoard.Tiles.Where(t => existingShipPlacement.Contains(t.Coordinates)).ToList().ForEach(t => t.IsOccupied = true);

            // Act
            ShipPlacer.PlaceShip(existingBoard, shipToPlace);

            // Assert
            shipToPlace.Position.Should().NotContain(existingShipPlacement, "ship should be placed without colliding with ship on board");
        }
示例#11
0
        private static void Main()
        {
            (IEnumerable <string> message, MenuState state)state = (Enumerable.Empty <string>(), MenuState.Initialise);
            GameBoard playersGameBoard;
            GameBoard computersGameBoard;
            var       userInput = ' ';
            var       random    = new Random();
            var       placer    = new ShipPlacer((min, max) => (char)random.Next(min, max));

            while (state.state != MenuState.Quit)
            {
                switch (state.state)
                {
                case MenuState.NewGame:
                    playersGameBoard   = GameFactory.NewBoard(placer, random.Next);
                    computersGameBoard = GameFactory.NewBoard(placer, random.Next);
                    break;

                default:
                    state = Menu.GetMenuText(state.state, userInput);
                    break;
                }

                foreach (var line in state.message)
                {
                    Console.WriteLine(line);
                }
                userInput = Console.ReadKey().KeyChar;
                Console.WriteLine();
            }
        }
示例#12
0
        public void ShouldFailToPlaceAShip_WhenIncorrectCorrectPositionsProvided(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            ShipType shipType)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //act
            //now place the ship on the board
            var shipPlacer = new ShipPlacer();

            IndexOutOfRangeException ex = Assert.Throws <IndexOutOfRangeException>(() =>
                                                                                   shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn));

            //assert
            Assert.Equal("Ship's placement position is out of bounds", ex.Message);
        }
示例#13
0
            public when_attempting_to_place_a_ship_on_the_same_location()
            {
                mockCoordGenerator = new MockCoordGenerator(new[] { 'b', 'd', 'g' }, new[] { '2', '1', '0' });
                var shipPlacer = new ShipPlacer(mockCoordGenerator.GenerateCoords);

                board = shipPlacer.PlaceShipOfLength(new GameBoard(), 4, () => ShipDirection.Horizontal);
                board = shipPlacer.PlaceShipOfLength(board, 4, () => ShipDirection.Vertical);
            }
示例#14
0
        public void PlaceShip_BoardIsEmpty_CorrectlyPlacesShip()
        {
            // Arrange
            var shipToPlace   = new Destroyer();
            var existingBoard = new Board.Board();

            // Act
            ShipPlacer.PlaceShip(existingBoard, shipToPlace);

            // Assert
            shipToPlace.Position.Should().HaveCount(shipToPlace.Size, "ship was correctly placed on board");
        }
示例#15
0
        /// <summary>
        /// Starts new game.
        /// </summary>
        public static void StartGame()
        {
            var board = new Board.Board();

            var ships = new List <Ship>
            {
                new Battleship(),
                new Destroyer(),
                new Destroyer()
            };

            ships.ForEach(ship => ShipPlacer.PlaceShip(board, ship));

            PlayGame(board, ships);
        }
示例#16
0
        public void PlaceShip_BoardWithPlaceForOneShipHOrizontalOrVertical_CorrectlyPlacesShip()
        {
            // Arrange
            var shipToPlace = new Destroyer();

            var freeshipSlot = new List <Point>
            {
                new Point {
                    X = 5, Y = 5
                },
                new Point {
                    X = 5, Y = 4
                },
                new Point {
                    X = 5, Y = 3
                },
                new Point {
                    X = 5, Y = 2
                },
                new Point {
                    X = 5, Y = 5
                },
                new Point {
                    X = 4, Y = 5
                },
                new Point {
                    X = 3, Y = 5
                },
                new Point {
                    X = 2, Y = 5
                }
            };

            var existingBoard = new Board.Board();

            existingBoard.Tiles.Where(t => !freeshipSlot.Contains(t.Coordinates)).ToList().ForEach(t => t.IsOccupied = true);

            // Act
            ShipPlacer.PlaceShip(existingBoard, shipToPlace);

            // Assert
            freeshipSlot.Should().Contain(shipToPlace.Position, "ship should be placed without colliding with ships on board");
        }
示例#17
0
            public when_the_player_takes_a_turn_that_will_hit()
            {
                var placer = new ShipPlacer(
                    new MockCoordGenerator(
                        new [] { 'a', 'b', 'c', 'a', 'b', 'c' },
                        new [] { '0', '0', '0', '0', '0', '0' }
                        ).GenerateCoords
                    );

                gameHandler = new GameHandler(
                    GameFactory.NewBoard(placer, (min, max) => 1),
                    GameFactory.NewBoard(placer, (min, max) => 1),
                    new MockCoordGenerator(
                        new [] { 'd' },
                        new [] { '4' }
                        ).GenerateCoords
                    );

                gameTurnStatus = gameHandler.TakeTurn('a', '1');
            }
示例#18
0
    /// <summary>
    /// Initializes the battle.
    /// </summary>
    /// <param name="competitors">Players to compete in this battle.</param>
    public void Initialize(Player[] competitors)
    {
        players      = competitors;
        ships        = new List <Ship>();
        isMainBattle = GameController.mainBattle == this;
        for (int i = 0; i < players.Length; i++)
        {
            players[i].gameObject.transform.parent = transform;
            players[i].battle = this;
            if (isMainBattle)
            {
                players[i].board.Set(BoardState.OVERHEAD);
            }
            else
            {
                players[i].AI = true;
            }
        }

        playersAlive = players.Length;
        ShipPlacer.HandleShipsForBattle(this);
    }
示例#19
0
 public ShipPlacerTests()
 {
     _fixture     = new Fixture();
     _battlefield = Mock.Of <IBattlefield>();
     _shipPlacer  = new ShipPlacer();
 }