生命游戏python代码
时间: 2023-08-23 20:08:11 浏览: 203
python实现生命游戏的示例代码(Game of Life)
以下是一个简单的生命游戏Python代码:
```
import random
import copy
# 游戏界面大小
WIDTH = 20
HEIGHT = 20
# 初始化游戏界面
board = []
for y in range(HEIGHT):
row = []
for x in range(WIDTH):
if random.random() > 0.5:
row.append('*')
else:
row.append('.')
board.append(row)
# 打印游戏界面
def print_board(board):
for row in board:
print(' '.join(row))
# 计算周围细胞数量
def count_neighbors(board, x, y):
neighbors = 0
for dx in range(-1, 2):
for dy in range(-1, 2):
if dx == 0 and dy == 0:
continue
if x+dx < 0 or x+dx >= WIDTH or y+dy < 0 or y+dy >= HEIGHT:
continue
if board[y+dy][x+dx] == '*':
neighbors += 1
return neighbors
# 进行一轮游戏
def step(board):
new_board = copy.deepcopy(board)
for y in range(HEIGHT):
for x in range(WIDTH):
neighbors = count_neighbors(board, x, y)
if board[y][x] == '*' and (neighbors < 2 or neighbors > 3):
new_board[y][x] = '.'
elif board[y][x] == '.' and neighbors == 3:
new_board[y][x] = '*'
return new_board
# 主循环
while True:
print_board(board)
input('Press Enter to continue...')
board = step(board)
```
这个代码实现了基本的生命游戏,首先随机生成一个游戏界面,然后每轮根据每个细胞周围的细胞数量来判断该细胞的状态,最后更新游戏界面。每次更新后,界面会打印出来,并等待用户按下回车键继续下一轮。
阅读全文