Python邻居都指向相同的值

时间:2014-04-27 01:28:56

标签: python pygame

我正在用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

在Board制作功能中,我打印xcoord和邻居5的xcoord来检查问题,问题来自设置邻居。在创建邻居期间,他们都指向正确的邻居,但是在它完成后它们都指向同一个邻居,但我知道盒子的数组都是不同的盒子,因为它们有不同的xcoord。如果有人能告诉我为什么邻居都指向同一个盒子,我会很感激。

1 个答案:

答案 0 :(得分: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)]