Hi,
In my game of Battleships, I am trying right now to randomly generate ship placement for the computer.
I have made the program generate one particular spot in the grid using code like this:

                    While CPlacementX > 5
                        GenerateCoords()
                    End While
                    For Each label In Me.Controls
                        If label.Tag = "C" & "x" & CPlacementX & "y" & CPlacementY Then
                            For j = 0 To 4
                                ComputerGrid(CPlacementX + j, CPlacementY) = "AC"
                                label.Text = "AC"
                            Next j
                        End If
                    Next

This works fine to generate it in one spot, but I have multiple square ships like this code is for an Aircraft Carrier, so, my question is: How do I modify this code so it 'steps off' another 4 squares to the right of the original one and make all the labels text "AC" Also, how I would I later make this code show a picturebox instead of a label?

Help would be much appreciated :)

I generally try to work from the simple case to the complex one. In this case your first concern is developing an algorithm to place the ships and you are complicating it with grids, labels, etc.

I'd start with a simple 10x10 integer array. Ships (at least in the classic game) cover either 2, 3, 4 or 5 cells ann can be placed horizontally or vertically. In VB, the indices of the rows and columns will run from 0 to 9 so that is the maximum range for the random numbers. You'll have to generate three numbers for each selection. One will be the row, the next the column, and the third will indicate direction. Once you generate the direction it will determine the upper range for either the row or column as ten minus the ship width. For example, if placing an aircraft carrier (5 cells) horizontally, the first column can't exceed 5 because that would overlap the right edge of the board.

Dim board(9,9) As Integer   'the playing area
Dim row As Integer          'row number from 0 to 9
Dim col As Integer          'column number from 0 to 9
Dim dir As Integer          'direction 0=horizontal, 1=vertical

So you start with a list of ship types and continue placing ships at random until the list is exhausted. That's your outer loop. In the inner loop you generate dir, then row and col (restricting the range based on dir). All you need then is a Sub that checks in a given direction for a given number of spaces to see if the ship can be placed. If the spaces are free you can toggle the array values from 0 (unoccupied) to a number indicating the ship type.

Once you have the algorithm debugged you can then convert it to use grids, labels, etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.