-
Battleship help!
Okay guys! Maybe you can help me out, I'm making a battleship game. I already did the main assignment so now I'm trying to do the extra credit portion. The extra credit part requires for us to randomly place "different" size ships on the board. I have some constant variables set up but I'm not sure exactly how to go about it. Any suggestions would be nice, I'll link the function below! Thanks for the help! :D
Code:
int randomizeShips(int board[SIZE][SIZE], int num_ships)
{
int placed_ships=1;
int loop=0;
int horiz=0;
int row, col;
srand( (unsigned int) time(0) );
//loop to place three ships. This loop ends when all three ships are placed or the loop has run to many times
while ((placed_ships < num_ships+1)&&(loop<100))
{
//randomly select horizontal or vertical
horiz=rand()%2;
//if ship is horizontal:
if(horiz==1)
{//randomly select row between 0 and size of board
row=rand()%SIZE;
//randomly select column between 0 and size of board minus size of the ship
col=rand()%SIZE-BATTLESHIP;
//check all three spaces to make sure nothing is there
if((board[row][col]==0)&&(board[row][col+1]==0)&&(board[row][col+2]==0))
{
//if nothing is there place the ship and increment loop variable
board[row][col]=placed_ships;
board[row][col+1]=placed_ships;
board[row][col+2]=placed_ships;
placed_ships++;
}
else
{
loop++;
}
//if something is there repeat from the beginning
}
//else
else
{
//randomly select col between 0 and size of board
col=rand()%SIZE-BATTLESHIP;
//randomly select row between 0 and size of board minus size of the ship
row=rand()%SIZE;
//check all three spaces to make sure nothing is there
if((board[row][col]==0)&&(board[row+1][col]==0)&&(board[row+2][col]==0))
{
//if nothing is there place the ship and increment loop variable
board[row][col]=placed_ships;
board[row+1][col]=placed_ships;
board[row+2][col]=placed_ships;
placed_ships++;
}
//if something is there repeat from the beginning
else
{
loop++;
}
}
}
//check to see why the loop ended
if(loop==100)
{
printf("\nLoop error, fix it\n");
return -1;
}
//report to main the results (return -1 if something went wrong)
else
{
return 1;
}
//if debugging print out hidden board
}
-
Perhaps you could rand() % 7+2 and make your ships between 2 and 8 "pegs" long?
Just because you have some values already in your program, that doesn't mean you can't be flexible with new one's.