Random number array with sequence

I'm thinking of making a small game like Battleship that is set to a grid using two arrays, but when thinking about the setup I got stuck. For a ship, say about 5 positions long, how do you create a matrix of random numbers, but you still want to have some of those numbers represent the randomly placed ships? The ships are placed randomly, but the points of the ships need to be placed horizontally or vertically. Would a random number be generated then add 1 to it? If so, how would directions, collision or end of the matrix be prevented and still have proper ship length? What I'm thinking for the game is just the user vs. the comp.
The algorithm is to generate random x, y coordinates, choose the length you need, randomize direction (0 for horizontal, 1 for vertical or vice versa) and if you can, place the ship at the chosen location. If you can't keep randomizing x,y and dir until you succeed.

If you try to place many ships on a small board, you would need a smarter algorithm though. Make sure that the board is large enough so that the ships can be placed anywhere.

Lets say your grid is 10*10 int grid[100];

Now you need the following functions:
1
2
bool is_valid_location(int x, int y, int length, int direction, int grid[]);
void place_ship(int x, int y, int length, int direction, int grid[]);


The first one doesn't modify grid, only tells you whether you can place a ship at that location. This function should have a for loop that checks the tiles form [x][y] to either [x+length][y] or [x][y+length] depending on direction.

The second one has the same loop, but this time actually sets the grid values to something.

You'll have some problems with preventing adjacent ships (I think there is a rule about that..?). To solve it, make place_ship mark all the tiles around a ship with a special value that would be recognized by is_valid_location as unavailable.

Note that these two functions will be needed by both human and computer players.
Thanks a lot for the help. I'll be starting soon, and it's good to have an idea of where things will go now.
Topic archived. No new replies allowed.