Ship placement in Battleship

My problem is this: I can't seem to find a way to keep computer placed ships from occasionally overlapping each other. I have a 10 x 10 grid and a way to randomize ship placement, but I can't seem to find a way to keep them from overlapping eachother.
post your code please and then maybe we can help.
I realize that I should use functions to clean this up, but I still haven't really gotten down to learning them just yet. This is essentially one quarter of my placement code. the variable 'direction' is a random number 0-3, with corresponding cases coming after this one. I have added some debug text to try to help isolate what is going on.

What I am trying to get this code to do is locate an empty square for the ship placement to start, and from there determine if there is a) enough space and b) nothing already occupying the spaces in the random direction that was chosen. What I can't figure out is how to get the code to cycle back through a random direction if there is not enough space in the chosen one; find new coordinates for the initial square placement is already taken; and/or both if it finds too crowded of an area.

switch (direction)
{
case 0: //Checks spaces to the left.
cout<<"Ship Number "<<ship<<".\n";
if (x - shipSize >= 0)
{
for (int a = 0; a <= shipSize - 1; a++)
{
if (computerGrid[y][x-a] == 0)
{
computerGrid[y][x-a] = ship;
}
else
{
cout<<"Target coordinates: ("<<x-a<<","<<y<<")\n";
cout<<"Error: Space taken by "<<computerGrid[y][x-a]<<"!\n";
int direction = rand() % 4;
}
}
}
else
{
cout<<"Target coordinates: ("<<x<<","<<y<<")\n";
cout<<"Error: Not enough space for placement!\n";
int direction = rand() % 4;
}
break;
Now would be an excellent time to learn functions, because using them will make your problem
much simpler to solve.

Your above code, while it does check, still will place a partial ship. For example, if the first three
spaces are open to place the carrier but the fourth isn't, you still put the first 3/5 of the carrier there.
The problem is that your code is trying to do everything at once; you really need to functionize it.

Alright, so I've started to divide all of my code into functions (finally!). Now, correct me if I am wrong, but in order to make my program adaptive, I will need to utilize recursive functions, correct?
GMurtha wrote:
Now, correct me if I am wrong, but in order to make my program adaptive, I will need to utilize recursive functions, correct?

What do you mean by "adaptive"? But the answer's probably no, recursive functions are functions that are calling themselves directly or indirectly and are rarely needed.
Perhaps adaptive was the wrong word. Auto-correcting maybe? I thought recursive functions would call themselves until a certain value was returned. Am I to assume that is incorrect?
Topic archived. No new replies allowed.