⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 life.cpp

📁 Conway s Game of life 算法程序
💻 CPP
字号:
// LIFE.CPP
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include "apmatrix.h"

enum STATUS {FAILED, OK};

const int ROWS = 20, COLS = 50;  // The size of the grid.

const char ALIVE = 'x';
const char DEAD = '.';

apmatrix<char> grid(ROWS,COLS);

void NextGeneration()

// Creates the next generation on the grid.

{
    apmatrix<char> newgrid(ROWS, COLS);
    int r, c, neighbors;

    // Count alive neighbors of each cell and
    //   calculate the new grid:

    for (r = 0;   r < ROWS;   r++) {
        for (c = 0;   c < COLS;   c++) {
            neighbors = 0;
            if (r > 0 && c > 0 && grid[r-1][c-1] == ALIVE)
                neighbors++;
            
        }
    }
        // Update the grid:
        grid = newgrid;
}
//****************************************************************
void DisplayGrid(int generation)
 // Displays the current generation on the grid.
{
    int r, c;

    cout << setw(4) << generation << ":" << endl;
    for (r = 0;   r < ROWS;   r++) {
        for (c = 0;   c < COLS;   c++)
            cout << grid[r][c];
        cout << endl;
    }
}
//****************************************************************
STATUS LoadGrid (char fileName[])

// Reads the initial grid configuration.

{
    int r, c;

    ifstream file(fileName);
    if (!file) return FAILED;

    for (r = 0;   r < ROWS;   r++)
        for (c = 0;   c < COLS;   c++)
            file >> grid[r][c];

    return OK;
}
 //****************************************************************
int main()
 {
    int generation = 0;
    char fileName[60];

    cout << "Filename: ";
    cin >> fileName;
    if (!LoadGrid(fileName)) {
        cout << "Cannot open " << fileName << ".\n";
        return 1;
    }

    DisplayGrid(generation);       // Display initial configuration.

    char next;
    for(;;) {
//        cout << "Next (y/n)? ";
  //      cin >> next;
    //    if (next != 'y')
      //      break;
        NextGeneration();
        generation++;
        DisplayGrid(generation);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -