I've created a program where I can randomly position two ships, with random orientation (horizontal or vertical), within a 2D array's borders.
The only problem that I'm facing is trying to prevent the ships from overlapping.
Here's a snippet from my code:
for ( row = 0; row < SIZE; row++ )
{
printf( "%c | ", a++ );
for ( column = 0; column < SIZE; column++ )
{
board[row][column] = ' ';
for ( i = 0; i < 4; i++ )
{
if ( battleship[i].column == column )
{
if ( battleship[i].row == row )
{
board[row][column] = 'B';
}
}
}
for ( i = 0; i < 5; i++ )
{
if ( carrier[i].column == column )
{
if ( carrier[i].row == row )
{
board[row][column] = 'A';
}
}
}
printf( "%c ", board[row][column] );
}
printf( "|\n" );
}
How can I check to see if a ship is already there, and if there is, restart the loop from the beginning, clearing the existing values?
You are decreasing the efficiency of your code by going through each point on the board and then checking if that point on the board corresponds to the 4 or 5 points of the battle ship or carrier.
Why not just fill the board with empty space characters
' '
. Then loop through your battle ship and carrier objects and check to see if the points on the board that the battle ship or carrier are to occupy are all empty spaces' '
or not. If what they are to occupy are all empty spaces' '
, then it collides with nothing and you can change the board points to either'A'
or'B'
accordingly. If it does collide you can randomly generate that ships position and check again.