tiles()方法列表不会在类中变异

时间:2016-03-17 04:47:44

标签: python list class

下面是宽度和高度的矩形房间的类。地板的瓷砖数量宽度乘以高度。我最初制作一个列表设置为False的列表,因为它们没有被清理但是在“cleanTileAtPosition(pos)”中我们将tile列表元素tiles [x_tile] [y_tile]设置为True但是在另一个方法中调用时当立即打印出来时,元素不会更改为True。你能告诉我我做错了什么,或者这与我失踪的课程有什么关系?

class RectangularRoom(object):
"""
A RectangularRoom represents a rectangular region containing clean or dirty
tiles.

A room has a width and a height and contains (width * height) tiles. At any
particular time, each of these tiles is either clean or dirty.
"""
def __init__(self, width, height):
    """
    Initializes a rectangular room with the specified width and height.

    Initially, no tiles in the room have been cleaned.

    width: an integer > 0
    height: an integer > 0
    """

    self.width = width
    self.height = height

def tiles(self):
    """
    Initialise a list of rows and columns of tiles that are False if not cleaned and true if cleaned
    """

    return [[False] * self.height for i in range(self.width)]


def cleanTileAtPosition(self, pos):
    """
    Mark the tile under the position POS as cleaned.

    Assumes that POS represents a valid position inside this room.

    pos: a Position - pos is a tuple (x, y)
    """


    (x_tile, y_tile) = (int(math.floor(pos.getX())), int(math.floor(pos.getY())))

    #print (x_tile, y_tile)

    self.tiles()[x_tile][y_tile] = True



def isTileCleaned(self, m, n):
    """
    Return True if the tile (m, n) has been cleaned.

    Assumes that (m, n) represents a valid tile inside the room.

    m: an integer
    n: an integer
    returns: True if (m, n) is cleaned, False otherwise
    """
    self.m = m
    self.n = n

    if self.tiles()[self.m][self.n] == True:
        return True
    else:
        return False

def getNumTiles(self):
    """
    Return the total number of tiles in the room.

    returns: an integer
    """

    return self.width*self.height

def getNumCleanedTiles(self):
    """
    Return the total number of clean tiles in the room.

    returns: an integer
    """
    numCleanTiles = 0

    for row in range(self.width):
        for column in range(self.height):
            if self.tiles()[row][column] == True:
                numCleanTiles +=1

    return numCleanTiles

def getRandomPosition(self):
    """
    Return a random position inside the room.

    returns: a Position object.
    """
    #
    return Position(random.randrange(0, self.width), random.randrange(0, self.height))

def isPositionInRoom(self, pos):
    """
    Return True if pos is inside the room.

    pos: a Position object.
    returns: True if pos is in the room, False otherwise.
    """
    if 0 <= pos.getX() < self.width and 0 <= pos.getY() < self.height:
        return True
    else:
        return False

1 个答案:

答案 0 :(得分:3)

问题是你正在调用始终创建新网格的tiles()函数。使用__init__函数初始化网格并将其分配给self.tiles,方法与初始化self.widthself.height的方式相同。然后只需在任何地方使用self.tiles,而不是调用可以移除的self.tiles()