Cellオブジェクトをセットに格納して(クラスを使用する必要があります)単純なライフゲームを作成しようとしていますが、セルオブジェクトはハッシュできないためセットに追加できないという問題に到達しました...何かありますかこれを回避する方法は?ありがとう!
class Cell():
def __init__(self, row, col):
self.row = row
self.col = col
def getRow(self):
return self.row
def getCol(self):
return self.col
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
class SparseLifeGrid(set):
# Creates a new infinite-sized game grid with all cells set to dead.
def __init__(self):
self.rowList = []
self.colList = []
self.cellSet = set()
def __add__(self, cell):
self.cellSet.add(cell)
self.rowList.append(cell.getRow())
self.colList.append(cell.getCol())
def minRange(self):
#Returns a 2-tuple (minrow, mincol) that contains the minimum
#row index and the minimum
#column index that is currently occupied by a live cell.
#None is returned if there are no alive cells.
return (sorted(self.rowList)[0], sorted(self.rowList)[0])
def maxRange(self):
#Returns a 2-tuple (maxrow, maxcol) that contains the
#maximum row index and the maximum
#column index that is currently occupied by a live cell.
#None is returned if there are no live cells.
return (sorted(self.rowList,reverse = True)[0],\
sorted(self.colList,reverse = True)[0])
def clearCell(self, row, col):
#Clears the individual cell (row, col) and sets it to dead.
#If the cell is already dead, no action is taken.
for item in self:
if item == Cell(row,col):
self.remove(item)
def setCell(self, row, col):
#Sets the indicated cell (row, col) to be alive.
#If the cell is already alive, no action is taken.
self.__add__(Cell(row,col))
def isLiveCell(self, row, col):
#Returns a boolean value indicating if the given
#cell (row, col) contains a live organism.
return Cell(row,col) in self
def numLiveNeighbors(self, row, col):
#checks how many live adjacents (not diagonals I think) a cell has
surround = 0
if self.isLiveCell(row+1,col):
surround += 1
if self.isLiveCell(row-1,col):
surround += 1
if self.isLiveCell(row, col+1):
surround += 1
if self.isLiveCell(row, col-1):
surround += 1
return surround
G = SparseLifeGrid()
G.setCell(2,3)