Loading...
exquisite avatar exquisite 3 Точки

C# Advanced Warship

Здравейте, 90/100 . Първия тест не минава.

https://pastebin.com/Qdvj2Xha

 

2. Warships

You have been tasked with the development of an online version of the famous Warships game. You start by developing a console version.

We get as input the size of the field in which our Warships are situated. The field is always a square. After that we will receive the coordinates for the attacks for each player in pairs of integers (row, column). If there is an attack on invalid coordinates - ignore the attack. The possible characters that may appear on the screen are:

  • * – a regular position on the field
  • < – ship of the first player.
  • > – ship of the second player
  • # – a sea mine that explodes when attacked

Each time when an attack hits a ship or a mine replace it with 'X'. Keep track of the count of ships remaining for each player. If a player hits a mine it explodes destroying all ships in adjacent fields (friend or foe). If a player destroys all enemy ships, the program stops and you have to print the following message: "Player {One/Two} has won the game! {totalCountShipsDestroyed} ships have been sunk in the battle."

If the list of attack commands ends before any of the player has won, you have to print the following message:     

"It's a draw! Player One has {countOfShips} left. Player Two has {countOfShips} left."

Input

  • Field size – an integer number.
  • Attack commands – All attack coordinates will be received on a single line. There will be a coma (,) between each set of coordinates and a whitespace (" ") between every two integers representing the row and column to attack.
  • The field: some of the following characters (*, <, >, #), separated by whitespace (" ");

Output

  • There are three types of output:
    • If player One wins, print the following output: "Player One has won the game! {totalCountShipsDestroyed} ships have been sunk in the battle."
    • If player Two wins, print the following output: "Player Two has won the game! {totalCountShipsDestroyed} ships have been sunk in the battle."
    • If there are no more commands and none of the above cases had happened, you have to print the following message: "It's a draw! Player One has {countOfShips} ships left. Player Two has {countOfShips} ships left."

Constraints

  • The field size will be a 32-bit integer in the range [4 … 2 147 483 647].
  • Player One always starts first.
  • A player will never attack the coordinates of one of his own ships.
  • There will be no incomplete sets of attack coordinates – e.g. – "0 1,2 3,2".
  • There will never be 2 mines in adjacent fields.
  • There will not be a test where both players lose their last ships in the same turn.

Examples

Input

Output

Comment

5

0 0,-1 -1,2 2,4 4,4 2,3 3,3 6

# < * < *

> > * < *

* * > * *

< * * * *

* * > * *

Player One has won the game! 5 ships have been sunk in the battle.

 

Player One attacks first at coordinates 0,0 and hits a mine. All adjacent fields (including diagonally) are blasted. The enemy ships at 1,0 and 1,1 are destroyed as well as the friendly ship at 0,1. The field now looks like this:

# X * < *

X X * < *

* * > * *

< * * * *

* * > * *

Player Two attacks on invalid coordinates so we ignore it.

Player One attacks 2,2 and destroys an enemy ship.

Player Two attacks 4,4 and misses.

Player One attacks 4,2 and destroys the last enemy ship. The game is over so we ignore any remaining attack coordinates and print message. The final state of the map is the following:

X X * < *

X X * < *

* * X * *

< * * * *

* * X * *

6

0 0,1 0,5 5

* * * * * *

< * * * < *

* * > > * *

* * * * * *

* * * * * *

* * * * * *

It’s a draw! Player One has 1 ships left. Player Two has 2 ships left.

 

5

1 1,0 3,2 1,1 3,4 1,3 0

# * * < *

* * * < *

* * > * *

< * * > *

* * > * *

Player Two has won the game! 3 ships have been sunk in the battle.

 

 

Тагове:
0
C# Advanced 08/02/2022 12:42:09
Axiomatik avatar Axiomatik 2422 Точки
Best Answer
  • < – ship of the first player.
  • > – ship of the second player

No need for counter-validation (since each player has an individual ship symbol) which should be:

counter % 2 == 0 => playerOneDestroyedShips++;

counter % 2 != 0 => playerTwoDestroyedShips++;

Try to refactor to obtain more compact code, which is easier to handle.

With the corrected first two validations (line 40 - 60) code gives 100%.

using System;
using System.Linq;

namespace Warship
{
    class Program
    {
        static void Main(string[] args)
        {
            var size = int.Parse(Console.ReadLine());
            var matrix = new char[size, size];

            var input = Console.ReadLine().Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                var line = Console.ReadLine()
                    .Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(char.Parse).ToArray();

                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    matrix[row, col] = line[col];
                }
            }

            var playerOneDestroyedShips = 0;
            var playerTwoDestroyedShips = 0;
            var playerOne = 0;
            var playerTwo = 0;
            //player one or player two turn
            var counter = 0;

            for (int i = 0; i < input.Length; i += 2)
            {
                var currRow = int.Parse(input[i]);
                var currCol = int.Parse(input[i + 1]);

                counter++;

                if (isInRange(matrix, currRow, currCol) && matrix[currRow, currCol] == '<')
                {
                    //if (counter % 2 == 0)
                    //{
                    //    matrix[currRow, currCol] = 'X';
                    //    playerTwoDestroyedShips++;
                    //}
                    // < – ship of the first player.
                    matrix[currRow, currCol] = 'X';
                    playerOneDestroyedShips++;
                }
                else if (isInRange(matrix, currRow, currCol) && matrix[currRow, currCol] == '>')
                {
                    //if (counter % 2 != 0)
                    //{
                    //    matrix[currRow, currCol] = 'X';
                    //    playerOneDestroyedShips++;
                    //}
                    // > – ship of the second player.
                    matrix[currRow, currCol] = 'X';
                    playerTwoDestroyedShips++;
                }
                else if (isInRange(matrix, currRow, currCol) && matrix[currRow, currCol] == '#')
                {
                    //current
                    matrix[currRow, currCol] = 'X';
                    //up
                    if (isInRange(matrix, currRow - 1, currCol))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow - 1, currCol);
                    }
                    //upleft
                    if (isInRange(matrix, currRow - 1, currCol - 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow - 1, currCol - 1);
                    }
                    //upright
                    if (isInRange(matrix, currRow - 1, currCol + 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow - 1, currCol + 1);
                    }
                    //left
                    if (isInRange(matrix, currRow, currCol - 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow, currCol - 1);
                    }
                    //right
                    if (isInRange(matrix, currRow, currCol + 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow, currCol + 1);
                    }
                    //down
                    if (isInRange(matrix, currRow + 1, currCol))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow + 1, currCol);
                    }
                    //downleft
                    if (isInRange(matrix, currRow + 1, currCol - 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow + 1, currCol - 1);
                    }
                    //downright
                    if (isInRange(matrix, currRow + 1, currCol + 1))
                    {
                        AttackShips(matrix, ref playerOneDestroyedShips, ref playerTwoDestroyedShips, currRow + 1, currCol + 1);
                    }
                }

                playerOne = 0;
                playerTwo = 0;

                for (int row = 0; row < matrix.GetLength(0); row++)
                {
                    for (int col = 0; col < matrix.GetLength(1); col++)
                    {
                        if (matrix[row, col] == '<')
                        {
                            playerOne++;
                        }
                        if (matrix[row, col] == '>')
                        {
                            playerTwo++;
                        }
                    }
                }

                if (playerTwo == 0)
                {
                    Console.WriteLine($"Player One has won the game! {playerOneDestroyedShips + playerTwoDestroyedShips} ships have been sunk in the battle.");
                    break;
                }

                if (playerOne == 0)
                {
                    Console.WriteLine($"Player Two has won the game! {playerOneDestroyedShips + playerTwoDestroyedShips} ships have been sunk in the battle.");
                    break;
                }
            }

            if (playerOne > 0 && playerTwo > 0)
            {
                Console.WriteLine($"It's a draw! Player One has {playerOne} ships left. Player Two has {playerTwo} ships left.");
            }
        }

        private static void AttackShips(char[,] matrix, ref int playerOneDestroyedShips, ref int playerTwoDestroyedShips, int currRow, int currCol)
        {
            if (matrix[currRow, currCol] == '<')
            {
                //playerTwoDestroyedShips++; !!!
                playerOneDestroyedShips++;
            }
            else if (matrix[currRow, currCol] == '>')
            {
                //playerOneDestroyedShips++; !!!
                playerTwoDestroyedShips++;
            }

            matrix[currRow, currCol] = 'X';
        }

        private static bool isInRange(char[,] matrix, int row, int col)
        {
            return row >= 0 && row < matrix.GetLength(0) &&
                   col >= 0 && col < matrix.GetLength(1);
        }
    }
}

 

0
exquisite avatar exquisite 3 Точки

Thank you sir!

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.