Game Development Reference
In-Depth Information
Private NearNeighborOffsets() As Point = { _
New Point(-1, -1), New Point(-1, 0), New Point(-1, 1), _
New Point(0, -1), New Point(0, 1), _
New Point(1, -1), New Point(1, 0), New Point(1, 1)}
If you add the X,Y values stored in the Point objects to the row and column
numbers of a square, you will get the row and column numbers of the eight
surrounding squares. Squares on the border will have fewer than eight neighbors,
so our code will have to catch proposed neighbors that are off the board.
'We have the idea of near neighbors and far neighbors
Public Function NearNeighbors(ByVal Row As Integer, ByVal Col As Integer) _
As Collection
Return GeneralNeighbors(Row, Col, NearNeighborOffsets)
End Function
'Both neighbors' functions use same method on different offsets
Private Function GeneralNeighbors(ByVal Row As Integer, ByVal Col As Integer, _
ByVal Offsets() As Point) As Collection
'Put the neighboring Square objects into a collection
Dim Neighbors As New Collection
'No neighbors if no field
If Field IsNot Nothing Then
Dim Pt As Point
Dim NeighborRow, NeighborCol As Integer
For Each Pt In Offsets
'Add the values in the point to get neighbor
NeighborCol = Col + Pt.X
NeighborRow = Row + Pt.Y
'It has to be on the board
If (NeighborRow >= 0) And _
(NeighborRow < NumRows) And _
(NeighborCol >= 0) And _
(NeighborCol < NumCols) Then
'It is on the board, add it in with key
Neighbors.Add(Field(NeighborRow, NeighborCol), _
KeyFromRC(NeighborRow, NeighborCol))
End If
End If
'We always return a collection, even if it is empty
Return Neighbors
End Function
Search Nedrilad ::

Custom Search