import sys标签:box,游戏,python,Cells,window,pygame,screen,255 From: https://www.cnblogs.com/lld76/p/16750389.html
import pygame
import random
# 参数设置
box_w, box_h = 10, 10 # 盒子宽高
window_w, window_h = 400, 400
x, y = 0,0
#使用pygame之前必须初始化
pygame.init()
#设置主屏窗口
screen = pygame.display.set_mode((400,400))
#设置窗口标题
pygame.display.set_caption('')
# 如果没有下列主循环代码,运行结果会一闪而过
def checks(x, y):
n = 0 # 周围细胞个数
L = x+box_w,y
R = x-box_w,y
U = x,y-box_h
D = x,y+box_h
ul = x+box_w,y-box_h
ur = x-box_w,y-box_h
dl = x+box_w,y+box_h
dr = x+box_w,y+box_h
d = [L, R, U, D, ul, ur, dl, dr]
for i in d:
if i in Cells:
n += 1
# 过于拥挤 n >= 4
if n >= 4:
Cells.remove([x,y])
# 过于孤独 n <= 1
elif n <= 1:
Cells.remove([x,y])
# 保持存活 2 <= n < 3
elif 2 <= n < 3:
pass
# 细胞繁衍 n = 3
elif n == 3:
while 1:
x,y = random.choice(d)
if [x,y] not in Cells:
print(x,y)
Cells.append([x,y])
break
# 细胞群
Cells = []
for t in range(100):
i = random.randint(0,int(window_w/box_w))
j = random.randint(0,int(window_h/box_h))
x, y = i*box_w,j*box_h
Cells.append([x, y])
# 更新屏幕内容
pygame.display.flip()
while True:
# #填充主窗口的背景颜色,参数值RGB(颜色元组)
screen.fill((255, 255, 255))
# 循环获取事件,监听事件
for event in pygame.event.get():
# 判断用户是否点了关闭按钮
if event.type == pygame.QUIT:
#卸载所有模块
pygame.quit()
#终止程序
sys.exit()
# 矩形
for x,y in Cells:
pygame.draw.rect(screen, (255, 0, 255), (x, y, box_w, box_h),width=0)
checks(x,y)
# 竖向
for i in range(int(window_h/box_w)):
pygame.draw.line(screen, (1, 1, 1), (box_w * i, 0), (box_w * i, window_h), 2)
# 横向
for j in range(int(window_w/box_h)):
pygame.draw.line(screen, (1, 1, 1), (0, box_h * j), (window_w, box_h * j), 2)
screen.blit(screen, (0, 0))
# 定义频率
clock = pygame.time.Clock()
# 设定刷新帧率
clock.tick(1) # 越大刷新的越快
pygame.display.update()