python 实现⽣命游戏的⽰例代码(GameofLife )
这篇⽂章主要介绍了python实现⽣命游戏的⽰例代码(Game of Life),⼩编觉得挺不错的,现在分享给⼤家,也给⼤家做个参考。⼀起跟随⼩编过来看看吧
⽣命游戏的算法就不多解释了,百度⼀下介绍随处可见。
因为⽹上⼤多数版本都是基于pygame,matlab等外部库实现的,⼆维数组⼤多是⽤numpy,使⽤起来学习成本⽐较⾼,所以闲暇之余写⼀个不⽤外部依赖库,console输出的版本。# -*- coding: utf-8 -*-from time import sleep from copy import deepcopy WORLD_HIGH = 20 #世界长度WORLD_WIDE = 40 #世界宽度ALIVE_CON = 3 #复活条件KEEP_CON = 2 #保有条件 class Cell (object ): '''''细胞对象''' def __init__(self , pos ): '''''⾃⾝坐标x,y, 已经是否还存活''' self .point , self .is_alive = pos , False self .x , self .y = self .point def setAlive (self ): self .is_alive = True def setDied (self ): self .is_alive = False def display (self ): if self .is_alive : return '*' return ' ' def displayLinux (self ): '''''在linux 环境下可以打印⿊⽩块''' if self .is_alive : return '\033[0;37;47m \033[0m' return '\033[0;30;40m \033[0m' class GameManager (object ): def __init__(self ): self .world = self .initWorld () self .initAliveCell () def initWorld (self ): world = [] for pos_x in xrange (WORLD_WIDE ): column = [] for pos_y in xrange (WORLD_HIGH ): column .append (Cell
((pos_x , pos_y ))) world .append (column ) return world def initAliveCell (self ): from random import choice for high in self .world : for cell in high : if choice ((0, 1)) == 0: continue cell .setAlive () def getNeighbours (self , cell_obj ):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
python新手代码示例23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。 def getNeighbours (self , cell_obj ): alive_count = 0 for x_of in xrange (-1, 2): for y_of in xrange (-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 < 0 or c_x >= WORLD_WIDE ) or \ (c_y < 0 or c_y >= WORLD_HIGH ): '''''排除⾃⾝和越界的点''' continue if self .world [c_x ][c_y ].is_alive : alive_count += 1 return alive_count def display (self ): print '='*WORLD_WIDE #等号分割线 for index in xrange (WORLD_HIGH ): print ''.join ([high [index ].displayLinux () for high in self .world ]) print '='*WORLD_WIDE def gameStart (self ): while True : self .display () new_world = deepcopy (self .world ) for p_x , wide_list in enumerate (self .world ): for p_y , _ in enumerate (wide_list ): current_cell = new_world [p_x ][p_y ] nei_num = self .getNeighbours (current_cell ) if nei_num == ALIVE_CON : current_cell .setAlive () elif nei_num != KEEP_CON : current_cell .setDied () self .world = new_world slee
p (0.2) if __name__ == '__main__': world = GameManager () try : world .gameStart () except KeyboardInterrupt : '''''防⽌ctrl+c 退出报错''' pass
565758596061626364656667686970717273747576777879808182838485868788899091929394959697
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论