生命的遊戲
約翰·何頓·康威,生於英國利物浦,數學家,活躍於有限群的研究、趣味數學、紐結理論、數論、組合博弈論和編碼學等範疇。康威年少時就對數學很有強烈的興趣:四歲時,其母發現他背誦二的次方;十一歲時,升讀中學的面試,被問及他成長後想幹什麼,他回答想在劍橋當數學家。後來康威果然於劍橋大學修讀數學,後為普林斯頓大學的教授。
新冠肺炎造成全球多人染疫後病逝,英國著名的數學家,約翰·霍頓·康威(John Horton Conway)在4月11日死於冠狀病毒,享壽82歲。由於約翰康威在很多領域都有卓越貢獻,此訊息也震驚學界。
本文以其創立的生命的遊戲來向其致敬 ! 以下是一段程式碼, 展示生命的遊戲, 如果你想知道規則, 可以上網查.
import numpy as np
import PySimpleGUI as sg
from PIL import Image, ImageFilter
from io import BytesIO
class Life():
"""
John Conway's "Game of Life" using a PySimpleGUI.
"""
def __init__(self):
self.width = 120
self.height = 90
self.low = 2
self.high = 3
self.death = 3
self.scale = 8
self.font = ('Courier New', 12)
self.background = '#000040'
self.percent = 0.3
self.color = np.array([[0, 0, 64, 255], [206, 206 ,0, 255]],
dtype=np.uint8)
self.life = self.counts = self.figure = None
self.image = None
self.new()
def new(self):
p = int(self.percent*10) if 0<self.percent<1 else 1
self.life = np.random.choice([0]*(10-p)+[1]*p,
size=(self.height, self.width)).astype(np.uint8)
def count(self):
array = np.zeros((self.height+2, self.width+2), dtype=np.uint8)
array[1:-1, 1:-1] = self.life
im = Image.fromarray(array, mode='L')
im = im.filter(ImageFilter.Kernel((3, 3), (1,1,1,1,0,1,1,1,1), 1, 0))
self.counts = np.array(im, dtype=np.uint8, copy=True)[1:-1, 1:-1]
self.life = np.logical_or(np.logical_and(np.logical_and(self.life==1,
self.counts>=self.low), self.counts<=self.high), np.logical_and(
self.life==0, self.counts==self.death)).astype(np.uint8)
def image_to_data(self):
im = Image.fromarray(self.image, mode='RGBA')
im = im.resize((self.width*self.scale, self.height*self.scale),
resample= Image.NEAREST)
with BytesIO() as output:
im.save(output, format="PNG")
self.data = output.getvalue()
def colors(self):
self.image = self.color[self.life]
def draw(self):
self.colors()
self.image_to_data()
window.find_element('Graph').Erase()
self.figure = window.find_element('Graph').DrawImage(
data=self.data, location=(0, self.height*self.scale))
def button(self):
return sg.Button('Quit', font=self.font, size=(6, 1), key='Quit')
def graph(self):
return sg.Graph((self.width*self.scale+3, self.height*self.scale+3),
(-1, -1), (self.width*self.scale+1, self.height*self.scale+1),
background_color=self.background, key='Graph')
L = Life()
layout = [[L.button()], [L.graph()]]
window = sg.Window('Game of Life', layout=layout, finalize=True)
while True:
event, values = window.read(timeout=10)
if event in [None, 'Quit']:
break
L.count()
L.draw()
window.close()
本作品採用《CC 協議》,轉載必須註明作者和本文連結