I'm making a Battleship program for a school assignment (there, I said it). Everything is coming along rather good, except for the placing of the ships. They are supposed to be placed randomly, and they can't be placed directly next to each other.
I can't for the life of me figure out how to execute this in a smooth way. If anyone could point me in the right direction, it'd be much appreciated.
I hate to double post, but seeing that almost all posts except this one have been answered, it's starting to seem like people don't answer this because it's a school assignment.
It's not like I'm asking for the complete code, or even a complete answer, I just want a push in the right direction.
If you do read this topic and decide not to answer, at least please post why, so that I'' learn what I'm doing wrong.
bool BATTLEFIELD[BATTLEFIELD_MAX_SIZE_HORZ][BATTLEFIELD_MAX_SIZE_VERT]; // Initialze that to false, i.e. memset(...);
bool CanPlaceAt(int x, int y)
{
bool ok = (x > 0) && (x < BATTLEFIELD_MAX_SIZE_HORZ); // This is for horizontal
if(ok)
{
ok = !BATTLEFIELD[x][y];
if(ok && (x > 0)) // if x isn't at the left border
ok = !BATTLEFIELD[x - 1][y]; // Is there a ship left
if(ok && (x < (BATTLEFIELD_MAX_SIZE_HORZ - 1))) // if x isn't at the right border
ok = !BATTLEFIELD[x + 1][y]; // Is ther a ship right
// do this for y allike
...
}
void PlaceHorz()
{
int size = rand() % SHIP_MAX_SIZE; // We need the size of a ship
bool ok = false;
while(not ok) // Loop as long as no proper place is fount / you might end after a certain amount of tries
{
int pos_horz = rand() % BATTLEFIELD_MAX_SIZE_HORZ; // the horizontal position
int pos_vert = rand() % BATTLEFIELD_MAX_SIZE_VERT; // the vertical position
for(int i = 0; i < size; ++i) // We need to know if the entire ship can be placed there
{
ok = CanPlaceAt(pos_horz + i, pos_vert); // Check if the spot is free
if(not ok)
break;
}
}
}
void Place()
{
srand(time(NULL)); // Initialze random generator
bool horz = rand() % 1; // Do we place the ship vertically or horizontally
if(horz)
PlaceHorz();
else
PlaceVert();
}
It's just a hint so don't sue me if it's not exactly what you have and it's not tested (of course)