Click here to Skip to main content
15,888,803 members
Articles / Programming Languages / C++

A Fast Version of Conway's Game of Life with Thread and DirectX Draw

Rate me:
Please Sign up or sign in to vote.
4.42/5 (14 votes)
14 Apr 2009CPOL4 min read 57.1K   904   30  
A fast version of Conway's Game of Life with thread and DirectX draw
// 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder SmartTick Software Inc.
Canada Canada
Jerry Jiang(BOLIANG JIANG)

A passionate software developer since 1992

Education:Master of Computer Science.

jerry@smarttick.com

Comments and Discussions