团队内部组织现场编程活动,实现这个Game of life。现场没写出来,思路是有的。
结尾讨论时领导提到了数组,一下想到了用Numpy.
网址:https://bitstorm.org/gameoflife/
代码: Python3.8
# -*- coding: utf-8 -*-
import numpy as np
import os, sys
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 range(x - 1, x + 2):
for j in range(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__":
N = 50
N2 = N // 2
p1 = N2 - 1
p2 = p1 + 1
p3 = p2 + 1
a = AAA(N)
for point in [(p1, p1), (p1, p2), (p1, p3), (p2, p2), (p2, p3), (p3, p1), (p3, p2), (p3, p3)]:
a.add(*point)
count = 0
while True:
os.system('cls')
for row in a.panel:
for col in row:
if col:
print('■', end="")
else:
print('□', end="")
print()
count += 1
print(count)
os.system("pause")
a.next()