【Python】次の世代のセルの生死を判定する

ライフゲームのルールに従って、周辺のセル(ムーア近傍)の生きているセルの合計から
次の世代のセルの生死を判定するためにcheck_rulesメソッドを作成する。

class LifeGame:
  def __init__(self):
    self.cells = [[0, 1, 0, 0, 0],
                  [0, 0, 1, 0, 0],
                  [1, 1, 1, 0, 0],
                  [0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0]]

  def print_cells(self):
    for x in self.cells:
      print(*x)

  def get_around_cells(self,_x,_y):
    return [[self.cells[y][x] for x in range(max(_x-1,0),min(_x+2,len(self.cells[0]))) if x != _x or y != _y] for y in range(max(_y-1,0),min(_y+2,len(self.cells)))]

  def flatten(self,_arr):
    return sum(_arr,[])

  def check_rules(self,_x,_y,_num):
    if self.cells[_y][_x] == 0:
      if _num == 3:
        return 1
      else:
        return 0
    else:
      if _num <= 1 or _num >= 4:
        return 0
      else:
        return 1

lg = LifeGame()
tmp = [[0]*5 for _ in range(5)]
for y in range(5):
  for x in range(5):
    tmp[y][x] = lg.check_rules(x,y,sum(lg.flatten(lg.get_around_cells(x,y)))) 
for x in tmp:
  print(*x)

今回は、以下のように出力される。

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

参考

ライフゲーム - Wikipedia
タイトルとURLをコピーしました