I am making a minesweeper clone in Python and I am running into issues setting the "Neighbors"
This is the class:
class Box:
hasBomb = False
numBombNeighbors = 0
clicked = False
xcoord = 0
ycoord = 0
neighbors = [None, None, None, None, None, None, None, None]
def __init__(self):
self.hasBomb = False
self.numBombNeighbors = 0
self.clicked = False
self.xcoord = 0
self.ycoord = 0
for i in xrange(8):
self.neighbors[i] = None
Then I make the board
def getRandomBoard():
# we will hide 50 random bombs
result = []
for i in xrange(BOARDWIDTH):
result.append([])
for j in xrange(BOARDHEIGHT):
new_box = Box()
new_box.xcoord = i
new_box.ycoord = j
result[i].append(new_box)
# set all the neighbors
result = setNeighbros(result)
for i in range(BOARDWIDTH):
for j in range(BOARDHEIGHT):
print result[i][j].xcoord
print result[0][0].neighbors[5].xcoord
And this is the function to set the Neighbors:
def setNeighbros(board):
for i in range(len(board)):
for j in range(len(board[i])-1):
if j > 0:
board[i][j].neighbors[0] = board[i][j-1]
if j > 0 and i < len(board) -1:
board[i][j].neighbors[1] = board[i+1][j-1]
if i < len(board) - 1:
board[i][j].neighbors[2] = board[i+1][j]
if i < len(board) - 1 and j < len(board[i]) - 1:
board[i][j].neighbors[3] = board[i+1][j+1]
if j < len(board[i]) - 1:
board[i][j].neighbors[4] = board[i][j+1]
if j < len(board[i]) - 1 and i > 0:
board[i][j].neighbors[5] = board[i-1][j+1]
if i > 0:
board[i][j].neighbors[6] = board[i-1][j]
if i > 0 and j > 0:
board[i][j].neighbors[7] = board[i-1][j-1]
return board
In the Board making function, I print the xcoord and the xcoord of neighbor 5 to check the problem, and the problem is coming from setting the neighbors. During the creation of the neighbors they are all pointing to the correct neighbor, but after it finishes they are all pointing to the same neighbor, but I know the array of boxes is all holding different boxes since they have different xcoord. If someone could tell me why the neighbors are all pointing at the same box, I would appreciate it.