Python——Pygame实现生命游戏(game of life)

模块:pygame

1import pygame,sys,time,random 2from pygame.locals import * 3 4 5"""Color""" 6WHITE = (255,255,255) 7RED = (255,0,0) 8GREEN = (0,255,0) 9"""Color""" 10 11def Neighbor(x,y):#返回周围存活细胞数 12 alive = 0 13 around = ((x+1,y+1),(x+1,y),(x+1,y-1),(x-1,y),(x-1,y+1),(x-1,y-1),(x,y-1),(x,y+1),) 14 for a in around: 15 color = WIN.get_at(a) 16 if color == RED: 17 alive += 1 18 return alive 19 20def Init(): 21 so = 200000 22 for number in range(0,so): 23 pygame.draw.rect(WIN,RED,(random.randint(0,SIZE[0]),random.randint(0,SIZE[1]),1,1)) 24 print('so = ',so) 25 26def rule(i,j): 27 if Neighbor(i,j) < 2: 28 return False 29 elif WIN.get_at((i,j)) == RED: 30 if Neighbor(i,j) == 2 : 31 return True 32 elif Neighbor(i,j) == 3: 33 return True 34 elif Neighbor(i,j) > 3: 35 return False 36 elif Neighbor(i,j) == 3: 37 return True 38 39 40pygame.init() 41 42SIZE = (800,800) 43WIN = pygame.display.set_mode(SIZE) 44pygame.display.set_caption("game of life") 45 46WIN.fill(WHITE) 47Init() 48gen = 0 49while True: 50 Next_alive = [] 51 Next_dead = [] 52 for event in pygame.event.get(): 53 if event.type == QUIT: 54 pygame.quit() 55 sys.exit(0) 56 x = SIZE[0] 57 y = SIZE[1] 58 for i in range(10,x-10): 59 for j in range(10,y-10): 60 if rule(i,j): 61 Next_alive.append((i,j)) 62 WIN.fill(WHITE) 63 print('Alive =',len(list(set(Next_alive)))) 64 65 66 67 68 for x,y in list(set(Next_alive)): 69 pygame.draw.rect(WIN,RED,(x,y,1,1)) 70 # for x,y in Next_dead: 71 # pygame.draw.rect(WIN,GREEN,(x,y,1,1)) 72 gen += 1 73 print(gen) 74 75 pygame.display.update()

该代码的实现策略是遍历所有像素点,判断每个像素点下一代的状态,然后每个像素点状态写入数组,根据数组更新画面

这个方法有点暴力,像素过多的话会大量消耗资源,很慢

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Python之time模块的时间戳、时间字符串格式化与转换

Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y