2013-03-08 74 views
0

我被分到這個項目下面的說明:無限局:康威生命遊戲 - Python的

生活的遊戲是爲無限大小的網格定義。在第2章中,我們將Life Grid ADT定義爲使用固定大小的網格,其中用戶指定網格的寬度和高度。這足以說明使用二維數組來實現生命遊戲。但是一個完整的實現應該允許一個無限大小的網格。使用類似於用於實現稀疏矩陣的方法實現稀疏生命網格ADT。

我真的不太瞭解這個概念。你能否給我一個外行人能夠理解的簡要描述(如果不是簡要的代碼)?我會很感激。

Sparselifegrid.py

""" My initial GameOfLife code 
    Feb 27, 2013 
    Sparse Matrix code specially designed for Game of Life 
""" 
class SparseLifeGrid: 

    def __init__(self): 
     """ 
     "pass" just allows this to run w/o crashing. 
     Replace it with your own code in each method. 
     """ 
     pass 

    def minRange(self): 
     """ 
     Return the minimum row & column as a list. 
     """ 
     pass 

    def maxRange(self): 
     """ 
     Returns the maximum row & column as a list. 
     """ 
     pass 

    def configure(self,coordList): 
     pass 

    def clearCell(self,row, col): 
     pass 

    def setCell(self,row, col): 
     pass 

    def isValidRowCol(val1,val2): 
     pass 

    def isLiveCell(self,row, col): 
     pass 

    def numLiveNeighbors(self, row,col): 
     pass 


    def __getitem__(self,ndxTuple): 
     pass 

    def __setitem__(self,ndxTuple, life): 
     """ 
     The possible values are only true or false: 
     True says alive, False for dead. 
     """ 
     pass 

    def _findPosition(self,row,col): 
     pass 

    def __repr__(self): 
     pass 

    def __str__(self): 
     """ 
     This method will only print the non-empty values, 
     and a row and column outside the non-empty values. 
     """ 
     pass 

    def evolve(self): 
     """ 
     Return the next generation state. 
     """ 
     pass 

    def hasOccurred(self): 
     """ 
     Check whether this current state has already occured. 
     If not, return False. If true, return which generation number (1-10). 
     """ 
     pass 

    def __eq__(self,other): 
     """ 
     This is good method if we want to compare two sparse matrices. 
     You can just use sparseMatrixA == sparseMatrixB because of this method. 
     """ 
     pass 

    def printLifeGrid(lifeGrid): 
     """ 
     Print a column before and after the live cells 
     """ 
     s="" 
     maxRange=lifeGrid.maxRange() 
     minRange=lifeGrid.minRange() 
     for i in range(minRange[0]-1,maxRange[0]+2): 
      for j in range(minRange[1]-1,maxRange[1]+2): 
       s+=" "+str(lifeGrid[i,j]) 
      s+="\n" 
     print(s) 


class _GoLMatrixElement: 
    """ 
    Storage class for one cell 
    """ 
    def __init__(self,row,col): 
     pass 

    def __str__self(self): 
     pass 

    def __eq__(self,other): 
     pass 

這是我的主文件

""" Marcus Brown's initial GameOfLife code 
    Feb 27, 2013 
""" 
from SparseLifeGrid_Key import SparseLifeGrid 
import sys 


# You'll probably need to add some other stuff like global variables 


""" #################################################### 
     Don't change anything below this line: readPoints or main 
""" #################################################### 

def readPoints(lifeGrid): 
    """ 
    Reads the locations of life and set to the SparseMatrix 
    """ 
    print("1. Enter positions of life with row,col format (e.g., 2,3).") 
    print("2. Enter empty line to stop.") 

    life=input() 
    coordList=[] 
    while life: 
     points=life.split(",") 
     try:  
      coord=[int(points[0]),int(points[1])] 
      coordList.append(coord) 
     except ValueError: 
      print("Ignored input:" + life+ ", row, col not valid numbers") 
     except: 
       print("Unexpected error:", sys.exc_info()[0]) 
     print("added, keep entering or enter empty line to stop.") 
     life=input() 
    print("Thanks, finished entering live cells") 
    lifeGrid.configure(coordList) 




def main(): 
    """ 
    Runs for ten generations if a stable (repeating) state is not found. 
    """ 
    lifeGrid= SparseLifeGrid() 
    readPoints(lifeGrid) 
    lifeGrid.printLifeGrid() 
    patterns=0 
    i=0 
    while i <10 and patterns == 0: 
     """ 
     Evolve to the next generation 
     """ 
     lifeGrid.evolve() 
     """ 
     Check whether this generation is a repetition of any of the 
     previous states. 
     If yes return the previous matching generation (1-10). 
     """ 
     patterns=lifeGrid.hasOccurred() 
     if patterns != -1: 
      break 
     i+=1 
     lifeGrid.printLifeGrid() 

    if i==10: 
     print("No pattern found") 
    else: 

     print("Pattern found at: " + str(i)+ " of type: " + str(patterns)) 

main() 
+1

什麼是您的實際問題?請記住,我們可以在這裏幫助您處理代碼的實際問題,而不是CS理論或代碼評論。我們在SE網絡中有其他的網站。 – 2013-03-08 15:47:44

+0

你是否明白稀疏矩陣是什麼,或者如何去表示一個矩陣? – NPE 2013-03-08 15:47:53

回答

3

一個稀疏矩陣是一個矩陣的表示只是位置是該值不等於一些默認(通常爲0)存儲在內存中。在Python中表示這種矩陣的一種簡單方法是使用一個字典,其中的密鑰是座標爲(x, y)的元組,並且該值是矩陣值。

例如,這個矩陣:

0 0 0 0 
0 0 0 0 
0 1 0 0 
0 0 0 0 

可能有以下表現:

matrix = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]] 
sparse_matrix = {(1, 2): 1} 

,你會訪問值這樣的:

for x in xrange(4): 
    for y in xrange(4): 
     assert matrix[y][x] == sparse_matrix.get((x, y), 0) 

這應該是足夠的讓你開始。你的練習要求你將這樣一個稀疏矩陣包裝在一個類中,這個矩陣將給它提供與傳統矩陣相同的界面。

有存儲這些sparse matrix,每做一個不同的權衡複雜性,內存使用情況之間,更先進的方式...

+0

謝謝你的幫助。我想我以爲我知道什麼是稀疏矩陣,但我沒有。如果我卡住了,我可以請你幫忙嗎? – 2013-03-08 16:55:30

1

下面是一個簡單的稀疏矩陣基礎的生活解決方案在Python 2.x的遊戲您可以將大小設置爲與系統可以處理的一樣大。它環繞在X和Y方向上:

class Cell(): 
    def __init__(self, x, y, live=True): 
     self.x, self.y = x, y 
     self.live = live 
     self.around = 0 

    def __eq__(self, other): 
     return (self.x, self.y) == (other.x, other.y) 

    def spawn(self): 
     self.live = True 
     self.around = 0 
     return self 

class Grid(): 
    def __init__(self, width, height): 
     self.xMax = width 
     self.yMax = height 
     self.cells = [] 
     self.deltas = [(-1, -1), (0, -1), (1, -1), (1, 0), 
         (1, 1), (0, 1), (-1, 1), (-1, 0)] 

    def tick(self): 
     newCells = self.cells[:] 
     ''' create potential new cells ''' 
     for cell in self.cells: 
      for dx, dy in self.deltas: 
       newCell = Cell((cell.x+dx)%self.xMax, 
           (cell.y+dy)%self.yMax, live=False) 
       if newCell not in newCells: 
        newCells.append(newCell) 
       newCells[newCells.index(newCell)].around += 1 
     ''' spawn new cells for next grid ''' 
     self.cells = [] 
     for cell in newCells: 
      if (cell.live and cell.around in [2, 3] 
      or not cell.live and cell.around == 3): 
       self.cells.append(cell.spawn()) 

    def show(self): 
     for y in range(self.yMax): 
      print ''.join('X|' if Cell(x, y) in self.cells 
        else ' |' for x in range(self.xMax)) 
     print 

用法:

>>> glider = [Cell(2,0), Cell(2,1), Cell(2,2), Cell(1,2), Cell(0,1)] 
>>> g = Grid(7, 7) 
>>> glider = [Cell(2,0), Cell(2,1), Cell(2,2), Cell(1,2), Cell(0,1)] 
>>> g.cells = glider 
>>> g.show() 
| |X| | | | | 
X| |X| | | | | 
|X|X| | | | | 
| | | | | | | 
| | | | | | | 
| | | | | | | 
| | | | | | | 

>>> g.tick() 
>>> g.tick() 
>>> g.show() 
| |X| | | | | 
| | |X| | | | 
|X|X|X| | | | 
| | | | | | | 
| | | | | | | 
| | | | | | | 
| | | | | | | 

>>> g.tick() 
>>> g.tick() 
>>> g.show() 
| | | | | | | 
| | |X| | | | 
|X| |X| | | | 
| |X|X| | | | 
| | | | | | | 
| | | | | | | 
| | | | | | |