赞
踩
首先,什么是生命游戏?
生命游戏是一种再空间上,时间上都离散的运动理论模型,简单点来说,就是模拟生命体的最小单元-细胞 的前后时间的状态,而且游戏规则是自订的,所以我就随便写了个游戏规则(一个周边的细胞小于2中间有细胞则死亡,为4时中间没有细胞则多生成细胞,大于四如果有细胞则死亡),如果想换成使用者想要的规则,请自己适当修改代码
实现:
要使用库:numpy(需要自行下载),tkinter
导入:
- import numpy as np
- from tkinter import *
接下来需要考虑是选择细胞离散的生成还是自己放制,因为我主打娱乐向,就选择了自己放制了
好,模拟生命游戏总得有个场地吧,那我就选择用numpy生成一个50x50全是0的矩阵,0代表没有细胞
ground=np.zeros(shape=(50,50))
好,场地设置完成,接下来就要写一个放置细胞的函数细胞
- def cell_place(x,y):
- global ground
- ground[x,y]=1
接下来,细胞总得演化吧,那么我们就写一个演化的逻辑判断,再封装到一个函数中
- def calculus():
- global ground
- for high in range(50):
- for widh in range(50):
- if high - 1 >= 0 and widh - 1 >= 0:
- area=ground[high-1:high+2,widh-1:widh+2]
- number = np.sum(area)
- if number < 2 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif number > 3 and ground[high,widh] == 0:
- ground[high,widh]=1
- elif number > 4 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif widh >= 0:
- area=ground[high:high+2,widh-1:widh+2]
- number = np.sum(area)
- if number < 2 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif number > 3 and ground[high,widh] == 0:
- ground[high,widh]=1
- elif number > 4 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif high >= 0:
- area=ground[high-1:high+2,widh:widh+2]
- number = np.sum(area)
- if number < 2 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif number > 3 and ground[high,widh] == 0:
- ground[high,widh]=1
- elif number >4 and ground[high,widh] == 1:
- ground[high,widh]=0
- else:
- are=ground[high:high+2,widh:widh+2]
- number = np.sum(area)
- if number < 2 and ground[high,widh] == 1:
- ground[high,widh]=0
- elif number > 3 and ground[high,widh] == 0:
- ground[high,widh]=1
- elif number >4 and ground[high,widh] == 1:
- ground[high,widh]=0
最后,有细胞的位置为一,那么如何找到它们的位置并且做成可视化呢?
我们就写个找出所有细胞坐标的位置(返回的为元组)
- def find_place():
- point_list=[]
- for high in range(50):
- for widh in range(50):
- if ground[high,widh] == 1:
- point_list.append([high,widh])
- return point_list
接下来就要用tkinter做游戏ui了,我们写入主函数来完成!
- if __name__ == '__main__':
- import tkinter
- from cell import *
- from tkinter import *
- root=Tk()
- root.geometry('500x530+500+50')
- start=False
- def draw_rect(point_list):
- window=tkinter.Canvas(root,width=500,height=500)#导入tkinter绘图组件
- for point in point_list:
- window.create_rectangle(point[0]*10,point[1]*10,point[0]*10+10,
- point[1]*10+10,fill='black',outline='black'
- )#绘制方形代表细胞
- window.pack()
- window.update()#更新画布
- window.destroy()#删除老画布
- def set_point(event):#通过鼠标事件细胞绘制在window上
- x=int(event.x/10)
- y=int(event.y/10)
- cell_place(x,y)
- def startcal(event):#开始演化的命令
- global start
- start = True
- def stopcal(event):#停止演化的命令
- global start
- start = False
- root.bind('<Button-3>',startcal)#开始事件
- root.bind('<Button-1>',set_point)#停止事件
- root.bind('<Key-0>',stopcal)
- print('左键布置细胞,右键开始演化,0可以暂停演化')
- while True:
- draw_rect(find_place())一直绘制细胞
- if start == True:
- calculus()#演化函数
结果:
好了,本程序就算大功告成了!
交流技术:
995981125
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。