Latest 100 public snipts »
lijamez's
snipts » game
showing 1-1 of 1 snipts for game
-
∞ Conway's Game of Life in C++
#include <iostream> using namespace std; //The Grid class of the game of life. The grid is a 2D array. class Grid { int width, height; bool grid [1000][1000]; public: Grid(int, int); void nextFrame(); void printFrame(); }; Grid::Grid(int a, int b) { height = a; width = b; //Presets of alive cells. Change these to whatever you wish. grid[0][1] = true; grid[1][2] = true; grid[2][0] = true; grid[2][1] = true; grid[2][2] = true; } /** Checks how many surrounding cells are alive for a cell and changes it depending on the game of life rules. The changes are stored in a temporary 2D array. Then, it is copied to the main grid array. **/ void Grid::nextFrame() { int numSurrounding = 0; bool tempGrid [height][width]; for (int i = 0; i < height ; i++) { for (int j = 0; j < width ; j++) { if ( (i+1) < height && grid[i + 1][j] == true ) { numSurrounding++; } if ( (i-1) >= 0 && grid[i - 1][j] == true ) { numSurrounding++; } if ( (j+1) < width && grid[i][j+1] == true ) { numSurrounding++; } if ( (j-1) >= 0 && grid[i][j-1] == true ) { numSurrounding++; } if ( (i+1) < height && (j+1) < width && grid[i+1][j+1] == true ) { numSurrounding++; } if ( (i+1) < height && (j-1) >= 0 && grid[i+1][j-1] == true ) { numSurrounding++; } if ( (i-1) >= 0 && (j+1) < width && grid[i-1][j+1] == true ) { numSurrounding++; } if ( (i-1) >= 0 && (j-1) >= 0 && grid[i-1][j-1] == true ) { numSurrounding++; } if (numSurrounding < 2 || numSurrounding > 3) { tempGrid[i][j] = false; } else if (numSurrounding == 2) { tempGrid[i][j] = grid[i][j]; } else if (numSurrounding == 3) { tempGrid[i][j] = true; } numSurrounding = 0; } } for (int i = 0 ; i < height ; i++ ) { for (int j = 0 ; j < width ; j++ ) { grid[i][j] = tempGrid[i][j]; } } } //Prints the grid into the console. void Grid::printFrame() { for (int i = 0; i < height ; i++ ) { for (int j = 0 ; j < width ; j++ ) { if ( grid[i][j] == true ) { cout << "x"; } else { cout << " "; } if ( (j + 1) >= width ) { cout << endl; } } } } int main () { int inputHeight, inputWidth; string kbd; cout << "The Game of Life in C++ by James Li\n\n" ; cout << "How many rows? (up to 1000)" << endl; cin >> inputHeight; cout << "How many columns? (up to 1000)" << endl; cin >> inputWidth; Grid life(inputHeight, inputWidth); life.printFrame(); cout << endl; do { kbd = ""; cout << "Enter \"y\" for next cycle, anything else to quit... "; cin >> kbd; cout << endl; life.nextFrame(); life.printFrame(); cout << endl; } while (kbd == "y"); cout << "Goodbye." << endl; return 0; }


