python实现生命游戏的示例代码(Game of Life)
生命游戏的算法就不多解释了,百度一下介绍随处可见。
因为网上大多数版本都是基于pygame,matlab等外部库实现的,二维数组大多是用numpy,使用起来学习成本比较高,所以闲暇之余写一个不用外部依赖库,console输出的版本。
#-*-coding:utf-8-*- fromtimeimportsleep fromcopyimportdeepcopy WORLD_HIGH=20#世界长度 WORLD_WIDE=40#世界宽度 ALIVE_CON=3#复活条件 KEEP_CON=2#保有条件 classCell(object): '''''细胞对象''' def__init__(self,pos): '''''自身坐标x,y,已经是否还存活''' self.point,self.is_alive=pos,False self.x,self.y=self.point defsetAlive(self): self.is_alive=True defsetDied(self): self.is_alive=False defdisplay(self): ifself.is_alive: return'*' return'' defdisplayLinux(self): '''''在linux环境下可以打印黑白块''' ifself.is_alive: return'\033[0;37;47m\033[0m' return'\033[0;30;40m\033[0m' classGameManager(object): def__init__(self): self.world=self.initWorld() self.initAliveCell() definitWorld(self): world=[] forpos_xinxrange(WORLD_WIDE): column=[] forpos_yinxrange(WORLD_HIGH): column.append(Cell((pos_x,pos_y))) world.append(column) returnworld definitAliveCell(self): fromrandomimportchoice forhighinself.world: forcellinhigh: ifchoice((0,1))==0: continue cell.setAlive() defgetNeighbours(self,cell_obj): alive_count=0 forx_ofinxrange(-1,2): fory_ofinxrange(-1,2): c_x,c_y=cell_obj.x+x_of,cell_obj.y+y_of if((c_x,c_y)==cell_obj.point)or\ (c_x<0orc_x>=WORLD_WIDE)or\ (c_y<0orc_y>=WORLD_HIGH): '''''排除自身和越界的点''' continue ifself.world[c_x][c_y].is_alive: alive_count+=1 returnalive_count defdisplay(self): print'='*WORLD_WIDE#等号分割线 forindexinxrange(WORLD_HIGH): print''.join([high[index].displayLinux()forhighinself.world]) print'='*WORLD_WIDE defgameStart(self): whileTrue: self.display() new_world=deepcopy(self.world) forp_x,wide_listinenumerate(self.world): forp_y,_inenumerate(wide_list): current_cell=new_world[p_x][p_y] nei_num=self.getNeighbours(current_cell) ifnei_num==ALIVE_CON: current_cell.setAlive() elifnei_num!=KEEP_CON: current_cell.setDied() self.world=new_world sleep(0.2) if__name__=='__main__': world=GameManager() try: world.gameStart() exceptKeyboardInterrupt: '''''防止ctrl+c退出报错''' pass
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。