康威生命游戏(Conway’s Game of Life)是英国数学家约翰·康威(John Conway)于 1970 年发明的一个经典元胞自动机(Cellular Automaton)。这个零玩家游戏仅由简单的规则驱动,却能产生极其复杂的涌现行为,被广泛用于研究复杂系统、人工生命和混沌理论。本项目使用 EGE 图形库实现了完整的生命游戏可视化,支持交互式绘制、多种经典图案、视图缩放和轨迹效果。
源码在末尾, 可滑到底部获取 ↓
生命游戏规则
生命游戏在一个无限的二维网格上进行,每个格子(细胞)有两种状态:存活或死亡。每一代的演化遵循以下四条规则:
- 孤独:任何活细胞周围少于 2 个活邻居则死亡
- 存活:任何活细胞周围有 2 或 3 个活邻居则继续存活
- 拥挤:任何活细胞周围超过 3 个活邻居则死亡
- 繁殖:任何死细胞周围恰好有 3 个活邻居则复活
这四条简单规则产生了丰富多彩的图案,包括静止图案、振荡器、飞船、滑翔机枪等。
项目特性
- 交互式绘制:鼠标左键绘制/擦除细胞,支持拖动连续绘制
- 9 种预设图案:滑翔机、轻型飞船、脉冲星、高斯帕枪等经典图案
- 视图控制:鼠标右键平移视图,滚轮缩放(2x-30x)
- 轨迹效果:显示细胞的历史轨迹,形成渐变尾迹
- 速度控制:1-60 代/秒可调,支持暂停和单步执行
- 网格开关:可切换网格线显示
- 实时统计:显示代数、存活细胞数、速度等信息
- 视觉反馈:不同颜色表示新生、存活、死亡细胞
核心算法实现
邻居计数
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int countNeighbors(int x, int y) const { int count = 0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { if (dx == 0 && dy == 0) { continue; // 跳过自己 } if (getCell(x + dx, y + dy)) { count++; } } } return count; } |
这个函数检查细胞周围 8 个方向的邻居(摩尔邻域),返回存活邻居的数量。
状态更新
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
void update() { m_prevGrid = m_grid; // 保存上一代状态用于视觉效果 m_population = 0; for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { int neighbors = countNeighbors(x, y); bool alive = getCell(x, y); bool nextState = false; if (alive) { // 规则 1, 2, 3 nextState = (neighbors == 2 || neighbors == 3); } else { // 规则 4 nextState = (neighbors == 3); } m_nextGrid[y * GRID_WIDTH + x] = nextState; if (nextState) { m_population++; } } } std::swap(m_grid, m_nextGrid); m_generation++; } |
算法要点:
- 同时计算所有细胞的下一代状态,避免影响其他细胞的计算
- 使用双缓冲(
m_grid和m_nextGrid)避免读写冲突 - 保存上一代状态用于视觉过渡效果
规则简化表达
生命游戏的规则可以用一行代码表达:
|
1 |
nextState = (neighbors == 3) || (alive && neighbors == 2); |
这个表达式等价于四条规则:
neighbors == 3:死细胞复活,活细胞存活alive && neighbors == 2:活细胞存活
经典图案
1. 滑翔机(Glider)
|
1 |
pattern = {{0, 0}, {1, 0}, {2, 0}, {2, -1}, {1, -2}}; |
最小的飞船,每 4 代向右下移动一格,是生命游戏的标志性图案。
|
1 2 3 4 |
█ █ █ ███ |
2. 轻型飞船(LWSS)
|
1 2 |
pattern = {{0, 0}, {3, 0}, {4, 1}, {0, 2}, {4, 2}, {1, 3}, {2, 3}, {3, 3}, {4, 3}}; |
每 4 代水平移动 2 格的飞船。
3. 脉冲星(Pulsar)
周期为 3 的振荡器,具有完美的对称性。通过镜像生成完整图案:
|
1 2 3 4 5 6 7 8 9 10 |
// 生成一个象限 pattern = {{2, 0}, {3, 0}, {4, 0}, {0, 2}, {5, 2}, ...}; // 镜像到四个象限 for (auto& p : pattern) { fullPattern.push_back({p.first, p.second}); fullPattern.push_back({-p.first - 1, p.second}); fullPattern.push_back({p.first, -p.second - 1}); fullPattern.push_back({-p.first - 1, -p.second - 1}); } |
4. 高斯帕滑翔机枪(Gosper Glider Gun)
|
1 2 |
pattern = {{0, 4}, {0, 5}, {1, 4}, {1, 5}, {10, 4}, {10, 5}, {10, 6}, {11, 3}, ...}; |
第一个被发现的能产生无限滑翔机的图案,证明了生命游戏可以产生无限增长的结构。每 30 代发射一个滑翔机。
5. R-五格体(R-pentomino)
|
1 |
pattern = {{0, 0}, {1, 0}, {0, 1}, {-1, 1}, {0, 2}}; |
仅由 5 个细胞组成,却要经过 1103 代才稳定下来,最终产生 116 个细胞。展示了简单初始状态可以产生极其复杂的演化。
6. 橡子(Acorn)
|
1 2 |
pattern = {{0, 0}, {1, -2}, {1, 0}, {3, -1}, {4, 0}, {5, 0}, {6, 0}}; |
仅 7 个细胞,经过 5206 代才稳定,最终产生 633 个细胞。
视觉效果实现
轨迹效果
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
void updateTrail() { if (m_showTrail) { for (int i = 0; i < GRID_WIDTH * GRID_HEIGHT; i++) { if (m_grid[i]) { m_trailGrid[i] = 255; // 活细胞轨迹最亮 } else if (m_trailGrid[i] > 0) { m_trailGrid[i] = std::max(0, m_trailGrid[i] - 15); // 渐变淡化 } } } } void renderTrail() { for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { int trail = m_trailGrid[y * GRID_WIDTH + x]; if (trail > 0 && !m_grid[y * GRID_WIDTH + x]) { int r = 30 * trail / 255; int g = 60 * trail / 255; int b = 40 * trail / 255; setfillcolor(EGERGB(r, g, b)); bar(screenX, screenY, screenX + cellSize - 1, screenY + cellSize - 1); } } } } |
轨迹效果为每个细胞维护一个强度值(0-255),活细胞设为最亮,死亡后逐渐淡化,形成渐变的历史轨迹。
细胞状态颜色
|
1 2 3 4 5 6 7 8 |
color_t cellColor; if (alive && !wasAlive) { cellColor = LIFE_COLOR_CELL_BORN; // 新生 - 浅绿色 } else if (!alive && wasAlive) { cellColor = LIFE_COLOR_CELL_DYING; // 死亡 - 橙色 } else { cellColor = LIFE_COLOR_CELL_ALIVE; // 存活 - 绿色 } |
通过对比当前状态和上一代状态,用不同颜色表示细胞的生命周期。
交互功能实现
鼠标绘制
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
void handleMouseDrawing(mouse_msg msg) { if (msg.is_left()) { if (msg.is_down()) { m_isDrawing = true; int gridX = (int)((msg.x - m_offsetX) / m_cellSize); int gridY = (int)((msg.y - m_offsetY) / m_cellSize); // 记录绘制值(toggle 当前细胞状态) m_drawValue = !getCell(gridX, gridY); setCell(gridX, gridY, m_drawValue); } else if (msg.is_move() && m_isDrawing) { // 拖动连续绘制 int gridX = (int)((msg.x - m_offsetX) / m_cellSize); int gridY = (int)((msg.y - m_offsetY) / m_cellSize); setCell(gridX, gridY, m_drawValue); } else if (msg.is_up()) { m_isDrawing = false; } } } |
支持点击切换细胞状态,以及拖动连续绘制。
视图平移
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
void handlePan(mouse_msg msg) { if (msg.is_right()) { if (msg.is_down()) { m_isDragging = true; m_lastMouseX = msg.x; m_lastMouseY = msg.y; } else if (msg.is_move() && m_isDragging) { m_offsetX += msg.x - m_lastMouseX; m_offsetY += msg.y - m_lastMouseY; m_lastMouseX = msg.x; m_lastMouseY = msg.y; } else if (msg.is_up()) { m_isDragging = false; } } } |
右键拖动实现视图平移,类似地图导航。
缩放功能
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void handleZoom(mouse_msg msg) { if (msg.is_wheel()) { float oldCellSize = m_cellSize; float zoomFactor = msg.wheel > 0 ? 1.2f : 0.8f; m_cellSize *= zoomFactor; m_cellSize = std::max(2.0f, std::min(30.0f, m_cellSize)); // 以鼠标位置为中心缩放 float mouseGridX = (msg.x - m_offsetX) / oldCellSize; float mouseGridY = (msg.y - m_offsetY) / oldCellSize; m_offsetX = msg.x - mouseGridX * m_cellSize; m_offsetY = msg.y - mouseGridY * m_cellSize; } } |
缩放算法要点:
- 保持鼠标指向的网格坐标不变
- 计算鼠标在网格中的相对位置
- 根据新的
cellSize重新计算偏移量
数学公式:
$$\text{mouseGridX} = \frac{\text{mouseX} – \text{offsetX}_{\text{old}}}{\text{cellSize}_{\text{old}}}$$
$$\text{offsetX}_{\text{new}} = \text{mouseX} – \text{mouseGridX} \times \text{cellSize}_{\text{new}}$$
性能优化
1. 视锥剔除(Frustum Culling)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
void renderCells() { for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { float screenX = m_offsetX + x * m_cellSize; float screenY = m_offsetY + y * m_cellSize; // 剔除屏幕外的细胞 if (screenX + m_cellSize < 0 || screenX > GRID_AREA_WIDTH || screenY + m_cellSize < 0 || screenY > WINDOW_HEIGHT) { continue; } // 只渲染可见区域 drawCell(x, y, screenX, screenY); } } } |
只渲染屏幕可见区域的细胞,大幅提升性能。
2. 帧率控制
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
void run() { while (is_run()) { if (!m_paused) { m_frameCount++; int updateInterval = 60 / m_speed; // 控制更新频率 if (m_frameCount >= updateInterval) { update(); m_frameCount = 0; } } render(); delay_fps(60); // 保持 60 FPS 渲染 } } |
渲染和逻辑更新分离,确保流畅的视觉体验。
3. 一维数组存储
|
1 2 3 4 5 |
std::vector<bool> m_grid; // 大小为 GRID_WIDTH * GRID_HEIGHT // 访问 (x, y) 位置 int index = y * GRID_WIDTH + x; bool alive = m_grid[index]; |
使用一维数组替代二维数组,提升缓存友好性和访问效率。
EGE 图形库应用
网格绘制
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
void drawGrid() { if (m_showGrid && m_cellSize >= 4) { setcolor(LIFE_COLOR_GRID); // 垂直线 for (int x = 0; x <= GRID_WIDTH; x++) { float screenX = m_offsetX + x * m_cellSize; if (screenX >= 0 && screenX < GRID_AREA_WIDTH) { line((int)screenX, 0, (int)screenX, WINDOW_HEIGHT); } } // 水平线 for (int y = 0; y <= GRID_HEIGHT; y++) { float screenY = m_offsetY + y * m_cellSize; if (screenY >= 0 && screenY < WINDOW_HEIGHT) { line(0, (int)screenY, GRID_AREA_WIDTH, (int)screenY); } } } } |
当 cellSize 足够大时绘制网格线,提升视觉效果。
信息面板
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void drawPanel() { // 面板背景 setfillcolor(LIFE_COLOR_PANEL); bar(GRID_AREA_WIDTH, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // 统计信息 sprintf(buf, "代数: %d", m_generation); outtextxy(x, y, buf); sprintf(buf, "存活: %d", m_population); outtextxy(x, y + 22, buf); sprintf(buf, "速度: %d 代/秒", m_speed); outtextxy(x, y + 44, buf); } |
右侧面板显示实时统计和操作说明。
操作指南
- 空格:暂停/继续
- R:随机生成细胞
- C:清空网格
- G:切换网格线
- T:切换轨迹效果
- + / –:调整速度
- 1-9:加载预设图案
- 鼠标左键:绘制/擦除细胞
- 鼠标右键:平移视图
- 滚轮:缩放
- ESC:退出
数学与哲学意义
生命游戏不仅是一个有趣的可视化项目,还蕴含深刻的数学和哲学意义:
- 涌现性:简单规则产生复杂行为,展示了复杂系统的涌现特性
- 图灵完备:生命游戏被证明是图灵完备的,可以模拟任何计算机程序
- 自组织:无需外部干预,系统自发形成有序结构
- 混沌边缘:介于完全随机和完全有序之间的临界状态
- 人工生命:探索生命的本质特征——自我复制、演化、适应
通过这个项目,你不仅能学习元胞自动机和可视化技术,还能深入思考生命、计算和复杂性的本质。
完整代码
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
/** * @file graph_game_of_life.cpp * @brief Conway's Game of Life Visualization Demo * * 康威生命游戏可视化演示 * - 经典的元胞自动机模拟 * - 简单规则产生复杂涌现行为 * - 支持鼠标绘制初始状态 * - 内置多种经典图案 * * Controls / 控制: * Space - Pause/Resume 暂停/继续 * R - Random reset 随机重置 * C - Clear grid 清空网格 * G - Toggle grid lines 开关网格线 * T - Toggle trail effect 开关轨迹效果 * +/- - Speed up/down 加速/减速 * 1-9 - Load preset patterns 加载预设图案 * Mouse Left - Draw/Erase cells 绘制/擦除细胞 * Mouse Right - Pan view 平移视图 * Mouse Wheel - Zoom in/out 缩放 * ESC - Exit 退出 * * Rules / 规则: * 1. 任何活细胞周围少于2个活邻居则死亡(孤独) * 2. 任何活细胞周围有2-3个活邻居则存活 * 3. 任何活细胞周围超过3个活邻居则死亡(拥挤) * 4. 任何死细胞周围恰好3个活邻居则复活(繁殖) */ // 禁用 Windows.h 中的 min/max 宏,避免与 std::min/std::max 冲突 #ifndef NOMINMAX #define NOMINMAX #endif #include <graphics.h> #include <cmath> #include <cstdlib> #include <ctime> #include <vector> #include <string> #include <algorithm> #ifdef _MSC_VER #define DEMO_TITLE "康威生命游戏" #define STR_PAUSED "已暂停" #define STR_RUNNING "运行中" #define STR_GENERATION "代数: %d" #define STR_POPULATION "存活: %d" #define STR_SPEED "速度: %d 代/秒" #define STR_ZOOM "缩放: %.1fx" #define STR_GRID "网格: %s" #define STR_TRAIL "轨迹: %s" #define STR_ON "开" #define STR_OFF "关" #define STR_CONTROLS "控制说明" #define STR_SPACE "空格 - 暂停/继续" #define STR_KEY_R "R - 随机重置" #define STR_KEY_C "C - 清空网格" #define STR_KEY_G "G - 开关网格" #define STR_KEY_T "T - 开关轨迹" #define STR_PLUS_MINUS "+/- - 调整速度" #define STR_MOUSE_L "左键 - 绘制细胞" #define STR_MOUSE_R "右键 - 平移视图" #define STR_WHEEL "滚轮 - 缩放" #define STR_NUM_KEYS "1-9 - 预设图案" #define STR_ESC "ESC - 退出" #define STR_PATTERNS "预设图案" #define STR_PAT_GLIDER "1 - 滑翔机" #define STR_PAT_LWSS "2 - 轻型飞船" #define STR_PAT_PULSAR "3 - 脉冲星" #define STR_PAT_GOSPER "4 - 高斯帕枪" #define STR_PAT_PENTA "5 - 五联体" #define STR_PAT_DIEHARD "6 - 顽固" #define STR_PAT_ACORN "7 - 橡子" #define STR_PAT_INF "8 - 无限增长" #define STR_PAT_RANDOM "9 - 随机" #else #define DEMO_TITLE "Conway's Game of Life" #define STR_PAUSED "Paused" #define STR_RUNNING "Running" #define STR_GENERATION "Gen: %d" #define STR_POPULATION "Pop: %d" #define STR_SPEED "Speed: %d gen/s" #define STR_ZOOM "Zoom: %.1fx" #define STR_GRID "Grid: %s" #define STR_TRAIL "Trail: %s" #define STR_ON "On" #define STR_OFF "Off" #define STR_CONTROLS "Controls" #define STR_SPACE "Space - Pause/Resume" #define STR_KEY_R "R - Random Reset" #define STR_KEY_C "C - Clear Grid" #define STR_KEY_G "G - Toggle Grid" #define STR_KEY_T "T - Toggle Trail" #define STR_PLUS_MINUS "+/- - Adjust Speed" #define STR_MOUSE_L "LMB - Draw Cells" #define STR_MOUSE_R "RMB - Pan View" #define STR_WHEEL "Wheel - Zoom" #define STR_NUM_KEYS "1-9 - Preset Patterns" #define STR_ESC "ESC - Exit" #define STR_PATTERNS "Patterns" #define STR_PAT_GLIDER "1 - Glider" #define STR_PAT_LWSS "2 - LWSS" #define STR_PAT_PULSAR "3 - Pulsar" #define STR_PAT_GOSPER "4 - Gosper Gun" #define STR_PAT_PENTA "5 - Pentadecathlon" #define STR_PAT_DIEHARD "6 - Diehard" #define STR_PAT_ACORN "7 - Acorn" #define STR_PAT_INF "8 - Infinite Growth" #define STR_PAT_RANDOM "9 - Random" #endif using namespace ege; // Window dimensions const int WINDOW_WIDTH = 1280; const int WINDOW_HEIGHT = 800; const int PANEL_WIDTH = 200; const int GRID_AREA_WIDTH = WINDOW_WIDTH - PANEL_WIDTH; // Colors const color_t LIFE_COLOR_BG = EGERGB(20, 20, 30); const color_t LIFE_COLOR_PANEL = EGERGB(40, 40, 50); const color_t LIFE_COLOR_TEXT = EGERGB(220, 220, 220); const color_t LIFE_COLOR_TITLE = EGERGB(100, 200, 255); const color_t LIFE_COLOR_GRID = EGERGB(50, 50, 60); const color_t LIFE_COLOR_CELL_ALIVE = EGERGB(50, 255, 100); const color_t LIFE_COLOR_CELL_BORN = EGERGB(100, 255, 150); const color_t LIFE_COLOR_CELL_DYING = EGERGB(150, 100, 50); const color_t LIFE_COLOR_TRAIL = EGERGB(30, 60, 40); // Grid settings const int GRID_WIDTH = 200; const int GRID_HEIGHT = 150; class GameOfLife { public: GameOfLife() : m_paused(true), m_showGrid(true), m_showTrail(false), m_generation(0), m_population(0), m_speed(10), m_cellSize(6.0f), m_offsetX(0.0f), m_offsetY(0.0f), m_isDragging(false), m_isDrawing(false), m_drawValue(true), m_lastMouseX(0), m_lastMouseY(0), m_frameCount(0) { m_grid.resize(GRID_WIDTH * GRID_HEIGHT, false); m_nextGrid.resize(GRID_WIDTH * GRID_HEIGHT, false); m_trailGrid.resize(GRID_WIDTH * GRID_HEIGHT, 0); m_prevGrid.resize(GRID_WIDTH * GRID_HEIGHT, false); // Center the view m_offsetX = (GRID_AREA_WIDTH - GRID_WIDTH * m_cellSize) / 2; m_offsetY = (WINDOW_HEIGHT - GRID_HEIGHT * m_cellSize) / 2; // Load default pattern (Gosper Glider Gun) loadPattern(4); } void run() { initgraph(WINDOW_WIDTH, WINDOW_HEIGHT); setbkmode(TRANSPARENT); setcaption(DEMO_TITLE); setbkcolor(LIFE_COLOR_BG); while (is_run()) { handleInput(); if (!m_paused) { m_frameCount++; int updateInterval = 60 / m_speed; if (updateInterval < 1) { updateInterval = 1; } if (m_frameCount >= updateInterval) { update(); m_frameCount = 0; } } render(); delay_fps(60); } closegraph(); } private: // Grid access helpers bool getCell(int x, int y) const { if (x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT) { return false; } return m_grid[y * GRID_WIDTH + x]; } void setCell(int x, int y, bool alive) { if (x >= 0 && x < GRID_WIDTH && y >= 0 && y < GRID_HEIGHT) { m_grid[y * GRID_WIDTH + x] = alive; } } int countNeighbors(int x, int y) const { int count = 0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { if (dx == 0 && dy == 0) { continue; } if (getCell(x + dx, y + dy)) { count++; } } } return count; } void update() { // Save previous state for visual effects m_prevGrid = m_grid; m_population = 0; for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { int neighbors = countNeighbors(x, y); bool alive = getCell(x, y); bool nextState = false; if (alive) { // Rule 1 & 3: Die if < 2 or > 3 neighbors // Rule 2: Survive if 2 or 3 neighbors nextState = (neighbors == 2 || neighbors == 3); } else { // Rule 4: Birth if exactly 3 neighbors nextState = (neighbors == 3); } m_nextGrid[y * GRID_WIDTH + x] = nextState; if (nextState) { m_population++; } // Update trail if (m_showTrail) { if (alive) { m_trailGrid[y * GRID_WIDTH + x] = 255; } else if (m_trailGrid[y * GRID_WIDTH + x] > 0) { m_trailGrid[y * GRID_WIDTH + x] = std::max(0, m_trailGrid[y * GRID_WIDTH + x] - 15); } } } } std::swap(m_grid, m_nextGrid); m_generation++; } void render() { cleardevice(); // Draw trail effect if (m_showTrail) { for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { int trail = m_trailGrid[y * GRID_WIDTH + x]; if (trail > 0 && !m_grid[y * GRID_WIDTH + x]) { float screenX = m_offsetX + x * m_cellSize; float screenY = m_offsetY + y * m_cellSize; if (screenX + m_cellSize >= 0 && screenX < GRID_AREA_WIDTH && screenY + m_cellSize >= 0 && screenY < WINDOW_HEIGHT) { int r = 30 * trail / 255; int g = 60 * trail / 255; int b = 40 * trail / 255; setfillcolor(EGERGB(r, g, b)); bar((int)screenX, (int)screenY, (int)(screenX + m_cellSize - 1), (int)(screenY + m_cellSize - 1)); } } } } } // Draw grid lines if (m_showGrid && m_cellSize >= 4) { setcolor(LIFE_COLOR_GRID); for (int x = 0; x <= GRID_WIDTH; x++) { float screenX = m_offsetX + x * m_cellSize; if (screenX >= 0 && screenX < GRID_AREA_WIDTH) { line((int)screenX, 0, (int)screenX, WINDOW_HEIGHT); } } for (int y = 0; y <= GRID_HEIGHT; y++) { float screenY = m_offsetY + y * m_cellSize; if (screenY >= 0 && screenY < WINDOW_HEIGHT) { line(0, (int)screenY, GRID_AREA_WIDTH, (int)screenY); } } } // Draw cells for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { bool alive = m_grid[y * GRID_WIDTH + x]; bool wasAlive = m_prevGrid[y * GRID_WIDTH + x]; if (alive || (wasAlive && !alive && !m_paused)) { float screenX = m_offsetX + x * m_cellSize; float screenY = m_offsetY + y * m_cellSize; // Culling if (screenX + m_cellSize < 0 || screenX > GRID_AREA_WIDTH || screenY + m_cellSize < 0 || screenY > WINDOW_HEIGHT) { continue; } color_t cellColor; if (alive && !wasAlive) { // Just born cellColor = LIFE_COLOR_CELL_BORN; } else if (!alive && wasAlive) { // Just died cellColor = LIFE_COLOR_CELL_DYING; } else { // Alive cellColor = LIFE_COLOR_CELL_ALIVE; } setfillcolor(cellColor); float margin = m_cellSize >= 6 ? 1.0f : 0.0f; bar((int)(screenX + margin), (int)(screenY + margin), (int)(screenX + m_cellSize - margin - 1), (int)(screenY + m_cellSize - margin - 1)); } } } // Draw panel drawPanel(); } void drawPanel() { // Panel background setfillcolor(LIFE_COLOR_PANEL); bar(GRID_AREA_WIDTH, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Border setcolor(EGERGB(80, 80, 90)); line(GRID_AREA_WIDTH, 0, GRID_AREA_WIDTH, WINDOW_HEIGHT); int x = GRID_AREA_WIDTH + 15; int y = 20; char buf[64]; // Title setfont(24, 0, "Consolas"); setcolor(LIFE_COLOR_TITLE); outtextxy(x, y, DEMO_TITLE); y += 40; // Status setfont(16, 0, "Consolas"); setcolor(m_paused ? EGERGB(255, 150, 100) : EGERGB(100, 255, 150)); outtextxy(x, y, m_paused ? STR_PAUSED : STR_RUNNING); y += 30; // Stats setcolor(LIFE_COLOR_TEXT); sprintf(buf, STR_GENERATION, m_generation); outtextxy(x, y, buf); y += 22; sprintf(buf, STR_POPULATION, m_population); outtextxy(x, y, buf); y += 22; sprintf(buf, STR_SPEED, m_speed); outtextxy(x, y, buf); y += 22; sprintf(buf, STR_ZOOM, m_cellSize / 6.0f); outtextxy(x, y, buf); y += 22; sprintf(buf, STR_GRID, m_showGrid ? STR_ON : STR_OFF); outtextxy(x, y, buf); y += 22; sprintf(buf, STR_TRAIL, m_showTrail ? STR_ON : STR_OFF); outtextxy(x, y, buf); y += 40; // Controls setcolor(LIFE_COLOR_TITLE); outtextxy(x, y, STR_CONTROLS); y += 25; setfont(14, 0, "Consolas"); setcolor(EGERGB(180, 180, 180)); outtextxy(x, y, STR_SPACE); y += 18; outtextxy(x, y, STR_KEY_R); y += 18; outtextxy(x, y, STR_KEY_C); y += 18; outtextxy(x, y, STR_KEY_G); y += 18; outtextxy(x, y, STR_KEY_T); y += 18; outtextxy(x, y, STR_PLUS_MINUS); y += 18; outtextxy(x, y, STR_MOUSE_L); y += 18; outtextxy(x, y, STR_MOUSE_R); y += 18; outtextxy(x, y, STR_WHEEL); y += 18; outtextxy(x, y, STR_NUM_KEYS); y += 18; outtextxy(x, y, STR_ESC); y += 35; // Patterns setfont(16, 0, "Consolas"); setcolor(LIFE_COLOR_TITLE); outtextxy(x, y, STR_PATTERNS); y += 25; setfont(14, 0, "Consolas"); setcolor(EGERGB(180, 180, 180)); outtextxy(x, y, STR_PAT_GLIDER); y += 18; outtextxy(x, y, STR_PAT_LWSS); y += 18; outtextxy(x, y, STR_PAT_PULSAR); y += 18; outtextxy(x, y, STR_PAT_GOSPER); y += 18; outtextxy(x, y, STR_PAT_PENTA); y += 18; outtextxy(x, y, STR_PAT_DIEHARD); y += 18; outtextxy(x, y, STR_PAT_ACORN); y += 18; outtextxy(x, y, STR_PAT_INF); y += 18; outtextxy(x, y, STR_PAT_RANDOM); } void handleInput() { // Keyboard input while (kbhit()) { int key = getch(); switch (key) { case ' ': m_paused = !m_paused; break; case 'r': case 'R': randomize(); break; case 'c': case 'C': clear(); break; case 'g': case 'G': m_showGrid = !m_showGrid; break; case 't': case 'T': m_showTrail = !m_showTrail; if (!m_showTrail) { std::fill(m_trailGrid.begin(), m_trailGrid.end(), 0); } break; case '+': case '=': m_speed = std::min(60, m_speed + 5); break; case '-': case '_': m_speed = std::max(1, m_speed - 5); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': loadPattern(key - '0'); break; case key_esc: closegraph(); exit(0); break; } } // Mouse input while (mousemsg()) { mouse_msg msg = getmouse(); if (msg.x < GRID_AREA_WIDTH) { if (msg.is_left()) { if (msg.is_down()) { m_isDrawing = true; int gridX = (int)((msg.x - m_offsetX) / m_cellSize); int gridY = (int)((msg.y - m_offsetY) / m_cellSize); if (gridX >= 0 && gridX < GRID_WIDTH && gridY >= 0 && gridY < GRID_HEIGHT) { m_drawValue = !getCell(gridX, gridY); setCell(gridX, gridY, m_drawValue); updatePopulation(); } } else if (msg.is_up()) { m_isDrawing = false; } else if (msg.is_move() && m_isDrawing) { int gridX = (int)((msg.x - m_offsetX) / m_cellSize); int gridY = (int)((msg.y - m_offsetY) / m_cellSize); if (gridX >= 0 && gridX < GRID_WIDTH && gridY >= 0 && gridY < GRID_HEIGHT) { setCell(gridX, gridY, m_drawValue); updatePopulation(); } } } if (msg.is_right()) { if (msg.is_down()) { m_isDragging = true; m_lastMouseX = msg.x; m_lastMouseY = msg.y; } else if (msg.is_up()) { m_isDragging = false; } else if (msg.is_move() && m_isDragging) { m_offsetX += msg.x - m_lastMouseX; m_offsetY += msg.y - m_lastMouseY; m_lastMouseX = msg.x; m_lastMouseY = msg.y; } } if (msg.is_wheel()) { float oldCellSize = m_cellSize; float zoomFactor = msg.wheel > 0 ? 1.2f : 0.8f; m_cellSize *= zoomFactor; m_cellSize = std::max(2.0f, std::min(30.0f, m_cellSize)); // Zoom towards mouse position float mouseGridX = (msg.x - m_offsetX) / oldCellSize; float mouseGridY = (msg.y - m_offsetY) / oldCellSize; m_offsetX = msg.x - mouseGridX * m_cellSize; m_offsetY = msg.y - mouseGridY * m_cellSize; } } } } void updatePopulation() { m_population = 0; for (int i = 0; i < GRID_WIDTH * GRID_HEIGHT; i++) { if (m_grid[i]) { m_population++; } } } void clear() { std::fill(m_grid.begin(), m_grid.end(), false); std::fill(m_trailGrid.begin(), m_trailGrid.end(), 0); std::fill(m_prevGrid.begin(), m_prevGrid.end(), false); m_generation = 0; m_population = 0; } void randomize() { clear(); for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { if (rand() % 100 < 25) { setCell(x, y, true); m_population++; } } } } void loadPattern(int patternIndex) { clear(); int centerX = GRID_WIDTH / 2; int centerY = GRID_HEIGHT / 2; // Pattern definitions (relative coordinates) std::vector<std::pair<int, int>> pattern; switch (patternIndex) { case 1: // Glider pattern = {{0, 0}, {1, 0}, {2, 0}, {2, -1}, {1, -2}}; break; case 2: // Lightweight Spaceship (LWSS) pattern = {{0, 0}, {3, 0}, {4, 1}, {0, 2}, {4, 2}, {1, 3}, {2, 3}, {3, 3}, {4, 3}}; break; case 3: // Pulsar pattern = { // Top left quadrant pattern (will be mirrored) {2, 0}, {3, 0}, {4, 0}, {0, 2}, {5, 2}, {0, 3}, {5, 3}, {0, 4}, {5, 4}, {2, 5}, {3, 5}, {4, 5}, }; // Mirror the pattern { std::vector<std::pair<int, int>> fullPattern; for (auto& p : pattern) { fullPattern.push_back({p.first, p.second}); fullPattern.push_back({-p.first - 1, p.second}); fullPattern.push_back({p.first, -p.second - 1}); fullPattern.push_back({-p.first - 1, -p.second - 1}); } pattern = fullPattern; } break; case 4: // Gosper Glider Gun pattern = {{0, 4}, {0, 5}, {1, 4}, {1, 5}, {10, 4}, {10, 5}, {10, 6}, {11, 3}, {11, 7}, {12, 2}, {12, 8}, {13, 2}, {13, 8}, {14, 5}, {15, 3}, {15, 7}, {16, 4}, {16, 5}, {16, 6}, {17, 5}, {20, 2}, {20, 3}, {20, 4}, {21, 2}, {21, 3}, {21, 4}, {22, 1}, {22, 5}, {24, 0}, {24, 1}, {24, 5}, {24, 6}, {34, 2}, {34, 3}, {35, 2}, {35, 3}}; centerX = GRID_WIDTH / 4; centerY = GRID_HEIGHT / 2; break; case 5: // Pentadecathlon pattern = { {-4, 0}, {-3, 0}, {-2, -1}, {-2, 1}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, -1}, {3, 1}, {4, 0}, {5, 0}}; break; case 6: // Diehard pattern = {{0, 0}, {1, 0}, {1, 1}, {5, 1}, {6, -1}, {6, 1}, {7, 1}}; break; case 7: // Acorn pattern = {{0, 0}, {1, -2}, {1, 0}, {3, -1}, {4, 0}, {5, 0}, {6, 0}}; break; case 8: // Infinite growth (R-pentomino) pattern = {{0, 0}, {1, 0}, {0, 1}, {-1, 1}, {0, 2}}; break; case 9: // Random randomize(); return; } // Place pattern for (auto& p : pattern) { setCell(centerX + p.first, centerY + p.second, true); } updatePopulation(); // Center view on pattern m_offsetX = (GRID_AREA_WIDTH - GRID_WIDTH * m_cellSize) / 2; m_offsetY = (WINDOW_HEIGHT - GRID_HEIGHT * m_cellSize) / 2; } std::vector<bool> m_grid; std::vector<bool> m_nextGrid; std::vector<bool> m_prevGrid; std::vector<int> m_trailGrid; bool m_paused; bool m_showGrid; bool m_showTrail; int m_generation; int m_population; int m_speed; float m_cellSize; float m_offsetX; float m_offsetY; bool m_isDragging; bool m_isDrawing; bool m_drawValue; int m_lastMouseX; int m_lastMouseY; int m_frameCount; }; int main() { srand((unsigned)time(NULL)); setinitmode(INIT_ANIMATION); GameOfLife game; game.run(); return 0; } |

近期评论