Home > Software engineering >  Battleship game C#
Battleship game C#

Time:11-03

I am stuck upon a problem about namimng the colums and the lines, differently than 0 to 10. something like this picture, the lines starting from the bottom 1 to 10 and colums from A to J.enter image description here

I've created a program that tells me if the ship is destroyed or not, after using 14 moves( in this image using move 5 c, in my program 5 2, counts as a hit, if all the blue squares are hit the program returns destroyed). My problem is that i don't know why i can't user input a move like "4 a" (Input string was not in a correct format.' - after debugging). I wrote the following code:

char[,] board = new char[10, 10];
int table = 10;
int hits = 2;
int totalHits = 14;
int neededHits = 8;

for (int i = 9; i >= 0; i--)
{
    string line = Console.ReadLine();
    string[] boardCharacters = line.Split(' ');
    for (int j = 0; j < table; j  )
    {
        board[i, j] = Convert.ToChar(boardCharacters[j]);
    }
}

int countHits = 0;

for (int z = 0; z < totalHits; z  )
{
    var ac = Console.ReadLine().Split(' ');
    var c1 = int.Parse(ac[0]) - 1;
    var c2 = (ac[1].ToLower()[0] - 'a');
    int[] attack = new int[2];
    for (int i = 0; i < hits; i  )
    {
        attack[i] = int.Parse(ac[i]);
    }

    if (board[attack[0], attack[1]] == 'x')
    {
        countHits  ;
    }
}

Console.WriteLine(countHits == neededHits ? "destroyed" : "not destroyed");

Console.ReadLine();

CodePudding user response:

Your problem is in this section:

var ac = Console.ReadLine().Split(' ');
var c1 = int.Parse(ac[0]) - 1;
var c2 = (ac[1].ToLower()[0] - 'a');
int[] attack = new int[2];

// You've already parsed the two parts of the input into 'c1' and 'c2'.
// This loop is redundant, and is the cause of the problem.
for (int i = 0; i < hits; i  )
{
    // When 'i' = 1, this is looking at the second part of the input ("a")
    // and trying to parse it as a number. This is what causes the exception.
    attack[i] = int.Parse(ac[i]);
}

I would suggest removing that loop, and populate the 'attack' array when you create it:

int[] attack = new int[] { c1, c2 };
  • Related