康威生命游戏

devtools/2025/2/28 5:52:37/

通过二维卷积快速计算每个细胞的Moore型邻居存活数(8邻域)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy.signal import convolve2d
import time
import logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')class CellularAutomaton:def __init__(self, size=100):self.size = sizeself.grid = np.zeros((size, size), dtype=int)self.kernel = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]])# 初始化结构self._init_glider_gun(10, 10)self._init_pulsar(50, 50)self._init_glider(5, 5)self._init_block(80, 80)# 可视化设置self.fig, self.ax = plt.subplots(figsize=(10, 10))self.img = self.ax.imshow(self.grid, cmap='viridis', interpolation='nearest')self.last_update = time.time() + 1e-6  # 初始化时间戳def _init_glider_gun(self, x, y):"""标准高氏滑翔机枪"""gun = [(5, 1), (5, 2), (6, 1), (6, 2),(3, 13), (4, 13), (5, 13), (6, 13), (7, 13), (8, 13),(3, 14), (4, 14), (5, 14), (6, 14), (7, 14), (8, 14),(5, 17), (6, 17), (7, 17)]for dx, dy in gun:self.grid[(x + dx) % self.size, (y + dy) % self.size] = 1def _init_pulsar(self, x, y):"""标准脉冲星"""arms = [(2, 4), (2, 5), (2, 6), (7, 4), (7, 5), (7, 6), (9, 4), (9, 5), (9, 6),(4, 2), (5, 2), (6, 2), (4, 7), (5, 7), (6, 7), (4, 9), (5, 9), (6, 9)]for dx, dy in arms:self.grid[(x + dx) % self.size, (y + dy) % self.size] = 1def _init_glider(self, x, y):self.grid[x % self.size, (y + 1) % self.size] = 1self.grid[(x + 1) % self.size, (y + 2) % self.size] = 1self.grid[(x + 2) % self.size, y % self.size:(y + 3) % self.size] = 1def _init_block(self, x, y):self.grid[x % self.size:(x + 2) % self.size, y % self.size:(y + 2) % self.size] = 1def _update_grid(self):padded = np.pad(self.grid, 1, mode='wrap')neighbor_count = convolve2d(padded, self.kernel, mode='valid')birth = (self.grid == 0) & (neighbor_count == 3)survive = (self.grid == 1) & ((neighbor_count == 2) | (neighbor_count == 3))return np.where(birth | survive, 1, 0)def update(self, frame):try:self.grid = self._update_grid()self.img.set_data(self.grid)# 安全计算FPSnow = time.time()time_diff = max(now - self.last_update, 1e-6)fps = 1 / time_diffself.last_update = nowif frame % 10 == 0:logging.info(f"Frame {frame}: Cells {np.sum(self.grid)} | FPS {fps:.1f}")return self.img,except Exception as e:logging.error(f"Update error: {str(e)}")raisedef run(self):try:ani = FuncAnimation(self.fig, self.update,frames=1000,interval=50,blit=True,cache_frame_data=False)plt.show()except Exception as e:logging.error(f"Runtime error: {str(e)}")finally:logging.info("程序正常退出")if __name__ == "__main__":sim = CellularAutomaton(size=100)sim.run()


http://www.ppmy.cn/devtools/163275.html

相关文章

Spring 核心技术解析【纯干货版】- XIV:Spring 消息模块 Spring-Jms 模块精讲

在现代分布式系统中,消息队列(Message Queue,MQ)扮演着至关重要的角色,它不仅能够解耦系统各个模块,还能提升系统的可扩展性和可靠性。JMS(Java Message Service)作为 Java EE 规范中…

Spring MVC视图解析器的定制与应用

Spring MVC视图解析器的定制与应用 在Spring MVC框架中,视图解析器(ViewResolver)是一个非常重要的组件,它负责将控制器返回的逻辑视图名称解析为实际的视图资源。通过自定义视图解析器,我们可以灵活地控制视图的渲染…

阿里巴巴DIN模型原理与Python实现

阿里巴巴的 Deep Interest Network (DIN) 是一种用于点击率预测(CTR)的深度学习模型,特别针对电商场景中用户兴趣多样化和动态变化的特性设计。其核心思想是通过 注意力机制 动态捕捉用户历史行为中与当前候选商品相关的兴趣。 1.DIN 模型原理…

如何下载MinGW-w64到MATLAB

MinGW 的全称是:Minimalist GNU on Windows 。它是将经典的开源 C语言 编译器 GCC 移植到了 Windows 平台下,并且包含了 Win32API ,因此可以将源代码编译为可在 Windows 中运行的可执行程序。而且还可以使用一些 Windows 不具备的&#xff0c…

如何在 WPS 中集成 DeepSeek

如何在 WPS 中集成 DeepSeek:从零基础到高阶开发的完整指南 DeepSeek 作为国内领先的 AI 办公助手,与 WPS 的深度整合可显著提升文档处理效率。本文提供 ​4 种集成方案,覆盖从「小白用户」到「企业开发者」的全场景需求,并包含 …

不同Embedding模型与大语言模型(LLM)的交互主要通过语义向量传递实现

不同Embedding模型与大语言模型(LLM)的交互主要通过语义向量传递实现,其核心机制和示例如下: 一、交互机制 语义对齐 Embedding模型将文本编码为向量后,LLM通过解码器将向量还原为语义空间。若两者语义空间不一致&…

软件测试之压力测试

🍅 点击文末小卡片,免费获取软件测试全套资料,资料在手,涨薪更快 压力测试 压力测试是一种软件测试,用于验证软件应用程序的稳定性和可靠性。压力测试的目标是在极其沉重的负载条件下测量软件的健壮性和错误处理能力&…

机器学习数学基础:35.效度

效度全攻略:从理论到实践的深度剖析 一、效度(Validity)入门:揭开精准测量的面纱 效度,简单来说,就是测量工具能否准确命中目标的“命中率”。想象你手中有一把枪(测量工具)&#…