放个代码版的
- #_*_coding:UTF-8_*_
- #!/usr/bin/python
- #Author :CPF
- #Datatime :2017-06-03
- #copyright
- from itertools import groupby
- from itertools import count
- import random
- import Rhino.Geometry as rg
- from Grasshopper.Kernel.Data import GH_Path
- from Grasshopper import DataTree
- class Graph:
- """
- 一个二维向量用来存储细胞的的状态值,死为0,生为1.
- """
- DEATH = 0
- LIVE = 1
- def __init__(self,row,col):
- """
- row行,col列,默认状态值为死
- """
- self.vec2 = [[Graph.DEATH for i in range(col)] for k in range(row)]
- self._row = row
- self._col = col
-
- @property
- def row (self):
- return self._row
-
- @property
- def col(self):
- return self._col
-
- def reset(self,live_rate):
- """
- 重设细胞的的状态,live_rate为细胞的存活几率。
- """
- for i in range(self._row):
- for k in range(self._col):
- rand_value = random.uniform(0,1)
- if live_rate > rand_value:
- self.vec2[i][k] = Graph.LIVE
- else:
- self.vec2[i][k] = Graph.DEATH
-
- def neighbor_live_count(self,row,col):
- """
- 获取第row行,第col列的相邻的8个细胞的存活细胞数目
- """
- count = 0
- neighbor = {'right_top':(-1,-1),'top':(-1,0),'left_top':(-1,1),
- 'right':(0,-1),'lift':(0,1),
- 'right_buttom':(1,-1),'buttom':(1,0),'left_buttom':(1,1)}
- for value in neighbor.values():
- if row == 0:
- neig_row = row + value[0]
- else:
- neig_row = (row + value[0])%self.row
- if col == 0:
- neig_col = col + value[1]
- else:
- neig_col = (col + value[1])%self.col
- if self.vec2[neig_row][neig_col] == Graph.LIVE:
- count = count + 1
- return count
-
- def updates(self):
- """
- 更新细胞的状态值
- """
- lists = []
- for i in range(self._row):
- row_list = []
- for k in range(self.col):
- count = self.neighbor_live_count(i,k)
- row_list.append(count)
- lists.append(row_list)
- for i in range(self.row):
- for k in range(self.col):
- count = lists[i][k]
- print count
- if count == 3 :
- self.vec2[i][k] = Graph.LIVE
- elif count != 2:
- self.vec2[i][k] = Graph.DEATH
- def display(self):
- """
- 显示细胞状态
- """
- state =[]
- for row in self.vec2:
- state.extend(row)
- return state
- if bool:
- graph = Graph(x,y)
- graph.reset(0.4)
- a = graph.display()
- else:
- graph.updates()
- a = graph.display()
复制代码 |