2014-04-27 46 views
1

我正在Python中的掃雷艇克隆和我遇到的問題設置「鄰居」Python的鄰居都指向同一個值

這是類:

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 

然後我做板

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 

這是設置鄰居功能:

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 

在董事會製作功能中,我打印xcoord和鄰居5的xcoord以檢查問題,並且問題來自設置鄰居。在創建鄰居時,他們都指向正確的鄰居,但是在完成後,他們都指向同一個鄰居,但是我知道,因爲他們有不同的xcoord,所以這些框的數組都是不同的。如果有人能告訴我爲什麼鄰居們都指着同一個盒子,我將不勝感激。

回答

1

問題在於類級變量在類的所有實例之間共享。

如果您來自Java這樣的語言,您可以想象在類中聲明的變量全部爲static變量。

修改您的類以刪除所有類級變量,並在__init__內部執行所有實例級變量的初始化。

class Box: 

    def __init__(self): 
     self.hasBomb = False 
     self.numBombNeighbors = 0 
     self.clicked = False 
     self.xcoord = 0 
     self.ycoord = 0 
     self.neighbors = [None for i in xrange(8)]