团队内部组织现场编程活动,实现这个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()