|
// 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);
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.