初学Python和OpenGL,练手的第一个小程序life.py,这个小程序在日后会不断调整,增加类、优化判断及操作
执行效果:
按正规生命游戏的规则:
1、周围生命等于3时产生生命
2、周围生命等于2时保持不变
3、红绿两种互相侵蚀(新增)
4、其他情况死亡
新增了边界循环(2017/2/13)
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import random
'''全局参数开始'''
life_down_p = #竞争参数下限
life_up_p = #竞争参数上限
life_die_time = #死亡时间
life_begin = #开局生成时间
map_size =
'''全局参数结束'''
num = #golbal
life_map = []*map_size*map_size #golbal
life_new = []*map_size*map_size #golbal
all_c = []*map_size*map_size
green_c = []*map_size*map_size
red_c = []*map_size*map_size
w = /map_size #width pre
h = /map_size #height pre
RED =
GREEN =
def draw_point(color,p) : #画点
x = int(p%map_size)
y = int(p/map_size)
glColor3f(color[],color[],color[])
glBegin(GL_QUADS)
glVertex2f(x*w-,y*h-)
glVertex2f((x+)*w-,y*h-)
glVertex2f((x+)*w-,(y+)*h-)
glVertex2f(x*w-,(y+)*h-)
glEnd()
def god() :
global life_map,num,font_map,all_c,green_c,red_c
if num < life_begin : #初始生成开始
num +=
x = random.randint(,map_size-)*map_size+random.randint(,map_size-)
if random.randint(,) : #绿色生物
life_map[x] = GREEN
draw_point([,,],x)
else : #红色生物
life_map[x] = RED
draw_point([,,],x)
else : #初始生成结束,开始繁殖
'''情况判断开始'''
for x in range(,map_size) :
for y in range(,map_size) :
i = y*map_size+x
'''获取周边信息'''
c = [(y-)%map_size*map_size+(x-)%map_size,
(y-)%map_size*map_size+ x ,
(y-)%map_size*map_size+(x+)%map_size,
y *map_size+(x-)%map_size,
y *map_size+(x+)%map_size,
(y+)%map_size*map_size+(x-)%map_size,
(y+)%map_size*map_size+ x ,
(y+)%map_size*map_size+(x+)%map_size,]
red_c[i],green_c[i],all_c[i] = ,,
for cc in c :
if life_map[cc] == GREEN :
green_c[i] +=
elif life_map[cc] == RED :
red_c[i] +=
all_c[i] = green_c[i] + red_c[i]
'''判断'''
for i in range(,map_size*map_size) :
if all_c[i] == life_up_p : #生存
if green_c[i] > red_c[i] :
life_map[i] = GREEN
draw_point([,,],i)
elif green_c[i] < red_c[i] :
life_map[i] = RED
draw_point([,,],i)
else :
if random.randint(,) :
life_map[i] = GREEN
draw_point([,,],i)
else :
life_map[i] = RED
draw_point([,,],i)
elif all_c[i] > life_up_p or all_c[i] < life_down_p : #死亡
life_map[i] =
draw_point([,,],i)
#else : 保持
def drawFunc() :
god()
glFlush()
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(,)
glutCreateWindow(b"life-forver")
glutDisplayFunc(drawFunc)
glutIdleFunc(drawFunc)
glutMainLoop()
执行截图: