康威生命游戏(Conway's Game of Life)Pygame实现异常:仅增殖不消亡求助
康威生命游戏细胞只增殖不消亡的问题修复
问题根源分析
- 存活规则逻辑完全错误:原代码中判断细胞死亡的条件是
if temp and (count > 3 and count < 2),temp是整个细胞数组永远为真,而count>3且count<2是逻辑矛盾,永远不会触发,导致没有细胞会死亡,只会不断繁殖新细胞。正确规则是:存活细胞周围活细胞数<2或>3时死亡。 - 边界越界访问:遍历到边缘细胞(如y=0、y=height-1、x=0、x=width-1)时,访问
y-1、y+1等索引会超出数组范围,Python会自动取数组首尾元素,导致活细胞计数完全错误,加剧异常增殖。 - 数组初始化冗余:初始化
randomBool时用了range(height+1)和range(width+1),但后续逻辑只用到height和width长度的数组,多余行列会引发索引混乱。
修正后的完整代码
import pygame, random, copy w, h = 500, 500 cellsize = 5 pygame.init() clock = pygame.time.Clock() width, height = w // cellsize, h // cellsize dis = pygame.display.set_mode((w, h)) dis.fill((0, 0, 0)) # 初始化细胞数组,移除多余行列 randomBool = [] cellPc = 0.1 for y in range(height): randomBool.append([]) for x in range(width): randomBool[y].append(random.random() < cellPc) def update_cells(): global randomBool, height, width temp = copy.deepcopy(randomBool) for y in range(height): for x in range(width): count = 0 # 遍历周围8个邻居,处理边界情况 for dy in (-1, 0, 1): for dx in (-1, 0, 1): if dy == 0 and dx == 0: continue # 跳过自身 ny, nx = y + dy, x + dx # 检查坐标是否在有效范围内 if 0 <= ny < height and 0 <= nx < width: if temp[ny][nx]: count += 1 # 应用康威生命游戏规则 current_cell = temp[y][x] if not current_cell and count == 3: randomBool[y][x] = True elif current_cell and (count < 2 or count > 3): randomBool[y][x] = False running = True while running: dis.fill((0, 0, 0)) clock.tick(10) # 降低帧率,方便观察演化过程 update_cells() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 绘制细胞(缩小1像素避免和网格线重叠) for y in range(height): for x in range(width): if randomBool[y][x]: pygame.draw.rect(dis, (255, 0, 0), (x * cellsize, y * cellsize, cellsize - 1, cellsize - 1)) # 绘制灰色网格线 for x in range(0, w, cellsize): pygame.draw.line(dis, (30, 30, 30), (x, 0), (x, h)) for y in range(0, h, cellsize): pygame.draw.line(dis, (30, 30, 30), (0, y), (w, y)) pygame.display.update() pygame.quit()
关键修正说明
- 修复规则判断:替换错误的死亡条件,严格遵循康威生命游戏的存活/死亡规则。
- 边界安全处理:通过坐标范围检查,避免边缘细胞越界访问邻居,确保计数准确。
- 简化数组初始化:移除多余行列,保证数组尺寸和遍历范围一致。
- 优化交互体验:降低帧率方便观察,调整细胞绘制大小避免和网格重叠,修复退出逻辑确保程序正常关闭。
内容的提问来源于stack exchange,提问作者SilphCoding
相关产品推荐
相关产品推荐

