python实现生命游戏的示例代码(Game of Life)

yipeiwu_com6年前Python基础

生命游戏的算法就不多解释了,百度一下介绍随处可见。

因为网上大多数版本都是基于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): 
    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 
      sleep(0.2) 
 
if __name__ == '__main__': 
  world = GameManager() 
  try: 
    world.gameStart() 
  except KeyboardInterrupt: 
    '''''防止ctrl+c退出报错''' 
    pass 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python有序字典简单实现方法示例

Python有序字典简单实现方法示例

本文实例讲述了Python有序字典简单实现方法。分享给大家供大家参考,具体如下: 代码: # -*- coding: UTF-8 -*- import collections pri...

Python使用Supervisor来管理进程的方法

本文实例讲述了Python使用Supervisor来管理进程的方法。分享给大家供大家参考。具体分析如下: Supervisor可以启动、停止、重启*nix系统中的程序。也可以重启崩溃的程...

解决pycharm最左侧Tool Buttons显示不全的问题

解决pycharm最左侧Tool Buttons显示不全的问题

问题描述如下: 解决方案如下: 下图中字体调整为18及以上 效果如下: 以上这篇解决pycharm最左侧Tool Buttons显示不全的问题就是小编分享给大家的全部内容了,希望能...

Python实现简单拆分PDF文件的方法

本文实例讲述了Python实现简单拆分PDF文件的方法。分享给大家供大家参考。具体如下: 依赖pyPdf处理PDF文件 切分pdf文件 使用方法: 1)将要切分的文件放在input_di...

教大家玩转Python字符串处理的七种技巧

教大家玩转Python字符串处理的七种技巧

前言 日常使用python经常要对文本进行处理,无论是爬虫的数据解析,还是大数据的文本清洗,还是普通文件的处理,都是要用到字符串. Python对字符串的处理内置了很多高效的函数,非常方...