Python 實現 Game of life
阿新 • • 發佈:2018-12-29
團隊內部組織現場程式設計活動,實現這個Game of life。現場沒寫出來,思路是有的。
結尾討論時領導提到了陣列,一下想到了用Numpy.
網址:https://bitstorm.org/gameoflife/
程式碼: Python2.7
# -*- coding: utf-8 -*-
import numpy as np
import os
class AAA(object):
def __init__(self, size):
self.size = size
self.panel = np.zeros(shape=(size, size))
def add(self, x, y):
self.panel[y][x] = 1
def next(self):
alives = np.where(self.panel != 0)
new_panel = np.zeros(shape=(self.size, self.size))
for y, x in zip(*alives):
for i in xrange(x - 1, x + 2):
for j in xrange(y - 1, y + 2):
neighbor = self.countNeighbor(j, i)
if neighbor >= 2 and neighbor <= 3 and self.panel[j, i]:
new_panel[j, i] = 1
elif neighbor == 3 and not self.panel[j, i]:
new_panel[j, i] = 1
self.panel = new_panel
def countNeighbor(self, x, y):
return np.sum(self.panel[x-1 :x+2, y-1:y+2]) - self.panel[x, y]
if __name__ == "__main__":
a = AAA(24)
for point in [(10, 7), (10, 8), (10, 9), (11, 8), (11, 9), (12, 7), (12, 8), (12, 9)]:
a.add(*point)
while True:
os.system('cls')
for row in a.panel:
for col in row:
if col:
print u'■',
else:
print u'□',
print '\n'
s = raw_input()
if s == 'c':
a.next()