python游戏代码示例_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):

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 实现元胞自动机中的生命游戏(Game of life)

时间: 2018-01-23

生命游戏Game of Life)是一种细胞自动机,是由英国数学家约翰·康威在 1970 年发明的。它通过简单的规则模拟生命的演化过程,被认为是一种复杂系统。在游戏中,每个细胞只有两种状态:存活或死亡。通过规则来判断每个细胞在下一轮中的状态,从而模拟生命的繁衍和死亡。 在 Python 中,我们可以用 NumPy 来创建一个二维数组来表示细胞的状态,然后通过循环遍历每个细胞,根据其周围细胞的状态来判断其下一轮的状态。具体实现方式可以参考以下示例代码: ```python import numpy as np def generate_board(size): board = np.zeros((size, size), dtype=int) # 在这里可以初始化细胞的初始状态 return board def get_neighbours(board, x, y): neighbours = [] for i in range(x-1, x+2): for j in range(y-1, y+2): if i >= 0 and j >= 0 and i < len(board) and j < len(board) and (i, j) != (x, y): neighbours.append((i, j)) return neighbours def get_next_state(board, x, y): state = board[x][y] neighbours = get_neighbours(board, x, y) live_neighbours = sum([board[i][j] for i, j in neighbours]) if state == 1: if live_neighbours < 2 or live_neighbours > 3: return 0 else: return 1 else: if live_neighbours == 3: return 1 else: return 0 def update_board(board): new_board = np.zeros((len(board), len(board)), dtype=int) for i in range(len(board)): for j in range(len(board)): new_board[i][j] = get_next_state(board, i, j) return new_board ``` 以上代码实现了一个基本的生命游戏,并可以自定义初始状态。你可以根据自己的需要对代码进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值