Exemple #1
0
        BattleshipsPlayerStartGame_WhenInvoked_ShouldThrowExceptionsIfTooMany()
        {
            //arrange
            var mockSetting = SetupSettings(10);
            var mockInput   = new Mock <IInput>();

            mockInput.Setup(x => x.AskUserForShipPlacementCoordinates())
            .Returns(() => GenerateMockSetUpShipPlacementCoordinates());
            var          battleships    = new Battleships(mockSetting, mockInput.Object);
            const string mockPlayerName = "Chris";

            battleships.CreatePlayer(mockPlayerName);

            const string mockPlayerNameTwo = "John";

            battleships.CreatePlayer(mockPlayerNameTwo);

            const string mockPlayerNameThree = "Bill";

            battleships.CreatePlayer(mockPlayerNameThree);

            //act
            Action act = () => battleships.StartGame();

            //assert
            act.Should().Throw <Exception>().WithMessage("Too many players add");
        }
Exemple #2
0
        public void BattleshipsGameStart_WhenStartingGame_AWinnerIsFoundAndSet()
        {
            //arrange
            var mockSetting = SetupSettings(10);
            var mockInput   = new Mock <IInput>();

            mockInput.Setup(x => x.AskUserForShipPlacementCoordinates())
            .Returns(() => GenerateMockSetUpShipPlacementCoordinates());
            mockInput.Setup(x => x.AskUserForAttackingCoordinates())
            .Returns(() => GenerateMockSetUpAttackingCoordinates());

            var battleships = new Battleships(mockSetting, mockInput.Object);

            const string mockPlayerName   = "Chris";
            const string mockOpponentName = "John";

            battleships.CreatePlayer(mockPlayerName);
            battleships.CreatePlayer(mockOpponentName);

            //act
            var player   = battleships.GetPlayer(mockPlayerName);
            var opponent = battleships.GetPlayer(mockOpponentName);

            player.SetShips();
            opponent.SetShips();
            battleships.StartGame();

            //assert
            battleships.GetWinner().Should().NotBe(null);
            battleships.GetWinner().Should().BeOneOf("Chris", "John", "Draw");
        }
Exemple #3
0
        /// <summary>
        /// Creates a new battleship either manually or authomatically finding ther largest empty slot
        /// </summary>
        /// <param name="random"></param>
        /// <param name="alingment"></param>
        /// <param name="size"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public Battleship CreateBattleship(bool random, Alingment alingment = Alingment.Horizontal, int size = -1, int x = -1, int y = -1)
        {
            Battleship bs;

            if (random)      //if random find the largest Battleship that we can allocate to the board
            {
                if (alingment == Alingment.Horizontal)
                {
                    bs = FindLargestHorizontalShip();
                }
                else
                {
                    bs = FindLargestVerticalShip();
                }
            }
            else
            {
                bs = BuildBattleship(alingment, size, x, y);
            }
            if (bs != null)
            {
                Battleships.Add(bs);
            }
            return(bs);
        }
Exemple #4
0
        private static void BattleshipsSetup(out Battleships battleship)
        {
            var mockSetting = SetupSettings(10);
            var mockInput   = SetupInput("12V");

            battleship = new Battleships(mockSetting, mockInput);
        }
Exemple #5
0
        static void Main()
        {
            string s = Console.ReadLine();

            if (s == "INIT")
            {
                foreach (var ship in Battleships.Generate().OrderBy(i => i.Length))
                {
                    var points = new HashSet<string>
                    {
                        ship.Location.ToString(),
                        new Point
                        {
                            X = ship.Location.X + (ship.Orientation == Orientation.Vertical ? ship.Length - 1 : 0),
                            Y = ship.Location.Y + (ship.Orientation == Orientation.Vertical ? 0 : ship.Length - 1),
                        }.ToString()
                    };

                    Console.WriteLine(points.Aggregate((a, b) => a + ":" + b));
                }
            }
            else
            {
                int n = int.Parse(s);

                var board = Enumerable.Range(0, n).Select(i => Console.ReadLine()).ToList();
                var b = new Battleships(new Board(board), new Random());
                b.NextMove();
                Console.WriteLine(b.LastMove);
            }
        }
Exemple #6
0
        public async Task <IActionResult> Edit(string id, [Bind("Abbrev,Nation,Tier,ShipName,Survivability,Artillery,Torpedoes,AaDefense,Maneuverability,Concealment")] Battleships battleships)
        {
            if (id != battleships.Abbrev)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(battleships);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BattleshipsExists(battleships.Abbrev))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Abbrev"] = new SelectList(_context.ShipClasses, "Abbreviation", "Abbreviation", battleships.Abbrev);
            ViewData["Nation"] = new SelectList(_context.ShipNations, "NationAbbrev", "NationAbbrev", battleships.Nation);
            return(View(battleships));
        }
Exemple #7
0
        private static void Init()
        {
            if (game == null)
            {
                game = new Battleships();
            }
            if (!resized && restart)
            {
                game.Init();
                System.Threading.Thread.Sleep(100);
                hasOutcome = false;
                lastAction = null;
                restart    = false;
            }
            Console.Clear();

            CLEAR_LINE = "".PadRight(Console.BufferWidth);

            #region Header
            Console.WriteLine($"\n Save game: Ctrl+{SAVE};    Exit Game: Ctrl+{EXIT};    New Game: Ctrl+{NEW}\n" +
                              $"\nSelect cell: {ENTER}/{ENTER_ALT};    Move Down: {DOWN}/{DOWN_ALT};    Move Up: {UP}/{UP_ALT};    Move Left: {LEFT}/{LEFT_ALT};    Move Right: {RIGHT}/{RIGHT_ALT};\n\n");
            playerRow = Console.CursorTop;
            WriteLine($" {(!game.Turn ? PLAYER1 : PLAYER2)}'s turn\n", ConsoleColor.Cyan);
            #endregion Header

            #region Board
            BoardRow = Console.CursorTop;
            DrawBoard();
            #endregion Board

            #region Last action
            WriteLine("\n Last action:", ConsoleColor.Yellow);
            lastActionRow = Console.CursorTop;
            if (lastAction != null)
            {
                PostLastAction(lastAction ?? "\n");
            }
            #endregion Last action

            #region Game Log
            WriteLine("\n\n Game Log:", ConsoleColor.Green);
            List <GameMove> log = game.GetLog();
            foreach (var move in log)
            {
                WriteLine($"{(!move.turn ? PLAYER1 : PLAYER2)} {move}");
            }
            lastLogRow = Console.CursorTop;
            #endregion Game Log

            ConsoleWidth  = Console.WindowWidth;
            ConsoleHeight = Console.WindowHeight;
            resized       = false;
            restart       = false;

            Console.SetCursorPosition(firstCellCol, firstCellRow);
        }
Exemple #8
0
        public bool TakeHit(Position position)
        {
            // ensure only one ship takes the hit
            if (position.X > Xaxis || position.Y > Yaxis)
            {
                throw new ArgumentOutOfRangeException(nameof(position), "Target attack point is out of range");
            }

            return(Battleships.SingleOrDefault(b => b.TakeHit(position)) != null);
        }
Exemple #9
0
        public void AddBattleship(Battleship battleShip)
        {
            // check if battleship can be added in this plain
            if (!(battleShip.Positions.First().X == 0 && battleShip.Positions.Last().X == Xaxis - 1) &&
                !(battleShip.Positions.First().Y == 0 && battleShip.Positions.Last().Y == Yaxis - 1))
            {
                throw new ArgumentOutOfRangeException(nameof(battleShip), "Battleship is out of the bounds of plain");
            }

            Battleships.Add(battleShip);
        }
Exemple #10
0
        public async Task <IActionResult> Create([Bind("Abbrev,Nation,Tier,ShipName,Survivability,Artillery,Torpedoes,AaDefense,Maneuverability,Concealment")] Battleships battleships)
        {
            if (ModelState.IsValid)
            {
                _context.Add(battleships);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Abbrev"] = new SelectList(_context.ShipClasses, "Abbreviation", "Abbreviation", battleships.Abbrev);
            ViewData["Nation"] = new SelectList(_context.ShipNations, "NationAbbrev", "NationAbbrev", battleships.Nation);
            return(View(battleships));
        }
Exemple #11
0
        public void BattleshipsPlayerBoards_WhenInitialised_ShouldEqualTheSquareOfTheSettingsBoardSizeValue(int boardSize)
        {
            //arrange
            var mockSetting = SetupSettings(boardSize);
            var mockInput   = SetupInput("12V");
            var battleship  = new Battleships(mockSetting, mockInput);

            battleship.CreatePlayer("Chris");

            //act
            var player = battleship.GetPlayer("Chris");

            //assert
            player.Board.Should().HaveCount(boardSize * boardSize);
            player.AttackingBoard.Should().HaveCount(boardSize * boardSize);
        }
Exemple #12
0
        BattleshipsPlayerStartGame_WhenInvoked_ShouldThrowExceptionsIfNoPlayersHaveBeenCreated()
        {
            //arrange
            var mockSetting = SetupSettings(10);
            var mockInput   = new Mock <IInput>();

            mockInput.Setup(x => x.AskUserForShipPlacementCoordinates())
            .Returns(() => GenerateMockSetUpShipPlacementCoordinates());
            var battleships = new Battleships(mockSetting, mockInput.Object);

            //act
            Action act = () => battleships.StartGame();

            //assert
            act.Should().Throw <Exception>().WithMessage("No players created");
        }
Exemple #13
0
    public BattleshipsService(Battleships game, string playerId)
    {
        _gameStarter = new GameStarter(game);

        _gameJoiner = new GameJoiner(game);

        _gameResigner = new GameResigner(game);

        _gameRestarter = new GameRestarter(game);

        _gamePlayerGetter = new GamePlayerGetter <BattleshipsPlayerModel>(game);

        _gameMover = new GameMover <BattleshipsPosition>(game);

        _playerId = playerId;

        _game = game;
    }
Exemple #14
0
        public HitResult TryHit(int x, int y)
        {
            Battleship destroyed = null;
            var        result    = HitResult.Missed;

            foreach (var bs in Battleships)
            {
                result = bs.TryToHit(x, y);
                if (result == HitResult.Destroyed)
                {
                    destroyed = bs;
                }
                if (result != HitResult.Missed)
                {
                    break;
                }
            }
            if (destroyed != null)
            {
                Battleships.Remove(destroyed);
            }
            return(result);
        }
Exemple #15
0
        BattleshipsPlayerShipSetUp_WhenSettingThePlayerShipsOnTheBoard_PlayerShouldHaveMarkersEqualToTheNumberOfShipsAndTheirLength()
        {
            //arrange
            var mockSetting = SetupSettings(10);
            var mockInput   = new Mock <IInput>();

            mockInput.Setup(x => x.AskUserForShipPlacementCoordinates())
            .Returns(() => GenerateMockSetUpShipPlacementCoordinates());
            var          battleships    = new Battleships(mockSetting, mockInput.Object);
            const string mockPlayerName = "Chris";

            battleships.CreatePlayer(mockPlayerName);

            //act
            var player = battleships.GetPlayer(mockPlayerName);

            player.SetShips();
            var result = player.Board.Cast <BoardBlock>().Count(boardBlock => boardBlock.MarkerType == "E");


            //assert
            result.Should().Be(player.Board.Length - CountShips(player));
        }
Exemple #16
0
        public void BattleshipsPlayerShipSetUp_WhenSettingThePlayerShipsOnTheBoard_MarkTypesCountShouldEqualShipLength
            (string battleshipMarker, int shipLength)
        {
            //arrange
            var mockSetting = SetupSettings(10);
            var mockInput   = new Mock <IInput>();

            mockInput.Setup(x => x.AskUserForShipPlacementCoordinates())
            .Returns(() => GenerateMockSetUpShipPlacementCoordinates());
            var          battleships    = new Battleships(mockSetting, mockInput.Object);
            const string mockPlayerName = "Chris";

            battleships.CreatePlayer(mockPlayerName);

            //act
            var player = battleships.GetPlayer(mockPlayerName);

            player.SetShips();

            //assert
            var result = player.Board.Cast <BoardBlock>().Count(boardBlock => boardBlock.MarkerType == battleshipMarker);

            result.Should().Be(shipLength);
        }
Exemple #17
0
        private static string PLAYER2 = "Player_2";             // Second Player Name

        public static void RunConsoleGame(Setting?setting, GameSave?save = null, GAME_TYPE gameType = GAME_TYPE.HU_VS_HU)
        {
            try
            {
                hasOutcome = false;
                lastAction = null;
                if (setting == null)
                {
                    setting = new Setting();
                }
                if (gameType == GAME_TYPE.HU_VS_HU)
                {
                    PLAYER1_CONTROLLER = Selector;
                    PLAYER2_CONTROLLER = Selector;
                }
                else if (gameType == GAME_TYPE.HU_VS_AI)
                {
                    PLAYER1_CONTROLLER = Selector;
                    PLAYER2_CONTROLLER = AISelector;
                }
                if (save == null)
                {
                    restart = true;
                    game    = new Battleships(setting);
                }
                else
                {
                    restart = false;
                    game    = new Battleships(save);
                }
                PLAYER1 = game.Player_1;
                PLAYER2 = game.Player_2;
                bool           loop = true;
                ConsoleKeyInfo pressedKey;
                Init();
                if (save == null)
                {
                    if (setting.PlaceType == PlaceShips.Select)
                    {
                        SetShips();
                    }
                    else
                    {
                        game.PlaceRandom();
                    }
                    Console.SetCursorPosition(0, BoardRow);
                    DrawBoard();
                    Console.SetCursorPosition(firstCellCol, firstCellRow);
                    System.Threading.Thread.Sleep(100);
                    if (setting.PlaceType == PlaceShips.Select && gameType == GAME_TYPE.HU_VS_HU)
                    {
                        SetShips();
                    }
                    else
                    {
                        game.PlaceRandom();
                    }
                    Console.SetCursorPosition(firstCellCol, firstCellRow);
                }
                Console.SetCursorPosition(0, BoardRow);
                DrawBoard();
                Console.SetCursorPosition(firstCellCol, firstCellRow);
                do
                {
                    if (hasOutcome)
                    {
                        pressedKey = Selector();
                    }
                    else
                    {
                        pressedKey = !game.Turn ? PLAYER1_CONTROLLER() : PLAYER2_CONTROLLER();
                    }
                    if (pressedKey.Modifiers == CTRL)
                    {
                        if (pressedKey.Key == EXIT)
                        {
                            loop = false;
                        }
                        if (pressedKey.Key == NEW)
                        {
                            restart = true;
                            Init();
                            if (setting.PlaceType == PlaceShips.Select)
                            {
                                SetShips();
                            }
                            else
                            {
                                game.PlaceRandom();
                            }
                            Console.SetCursorPosition(0, BoardRow);
                            DrawBoard();
                            Console.SetCursorPosition(firstCellCol, firstCellRow);
                            System.Threading.Thread.Sleep(100);
                            if (setting.PlaceType == PlaceShips.Select && gameType == GAME_TYPE.HU_VS_HU)
                            {
                                SetShips();
                            }
                            else
                            {
                                game.PlaceRandom();
                            }
                            Console.SetCursorPosition(firstCellCol, firstCellRow);
                            Console.SetCursorPosition(0, BoardRow);
                            DrawBoard();
                            Console.SetCursorPosition(firstCellCol, firstCellRow);
                        }
                        //if (pressedKey.Key == UNDO)
                        //    UpdateGameState(false);
                        if (pressedKey.Key == SAVE && gameType == GAME_TYPE.HU_VS_HU)
                        {
                            SaveGame();
                        }
                    }
                    else if (pressedKey.Key == ENTER || pressedKey.Key == ENTER_ALT)
                    {
                        UpdateGameState(true, (Console.CursorTop - firstCellRow) / 2, (Console.CursorLeft - firstCellCol) / (ROW_SEP.Length + CROSS_POINT.Length));
                    }
                } while (loop);

                Console.Clear();
            }
            catch (Exception)
            {
                return;
            }
        }
Exemple #18
0
 public bool IsDestroyed()
 {
     return(Battleships.All(ship => ship.IsDestroyed()));
 }