Exemple #1
0
        private void TakeGuesses()
        {
            var guesses = 0;

            while (guesses < _player.NumberOfTurns)
            {
                Console.Write("Enter the point of guess {0}, separated by a comma (ex: 3,4): ", guesses + 1);
                var input      = Console.ReadLine();
                var coords     = input.Split(',');
                var convertedX = int.TryParse(coords[0], out var xCoord);
                var convertedY = int.TryParse(coords[1], out var yCoord);
                try
                {
                    if (convertedX && convertedY)
                    {
                        if (_board._board[yCoord - 1, xCoord - 1].IsOccupied)
                        {
                            if (_board._board[yCoord - 1, xCoord - 1].Contents == "*")
                            {
                                _board._board[yCoord - 1, xCoord - 1].Contents = "X";
                                _shipsDamaged++;
                                Console.WriteLine("Hit at point {0},{1}!", xCoord, yCoord);
                                guesses++;
                            }
                            else
                            {
                                Console.WriteLine("Point {0},{1} already guessed. Try a different point.", xCoord, yCoord);
                            }
                        }
                        else
                        {
                            if (_board._board[yCoord - 1, xCoord - 1].Contents == "*")
                            {
                                _board._board[yCoord - 1, xCoord - 1].Contents = "o";
                                Console.WriteLine("Miss at point {0},{1}.", xCoord, yCoord);
                                guesses++;
                            }
                            else
                            {
                                Console.WriteLine("Point {0},{1} already guessed. Try a different point.", xCoord, yCoord);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid input. Please try again.");
                    }
                } catch (Exception ex)
                {
                    Console.WriteLine("Not a valid input. Please try again: {0}", ex.Message);
                }
                _board.UpdateDraw();
                if (_shipsDamaged >= _boardShipsHealth)
                {
                    _gameWon = true;
                    break;
                }
            }
            if (_gameWon)
            {
                Console.WriteLine("Congratulations, you won!");
            }
            else
            {
                Console.WriteLine("Sorry, you did not win. Better luck next time.");
            }
        }