title: Conway's Game of Life - C++ and Qt
body: <p>I've done all of the layouts and have most of the code written even. But, I'm stuck in two places.</p>
  
  <p>1) I'm not quite sure how to set up the timer. Am I using it correctly in the gridwindow class? And, am I used the timer functions/signals/slots correctly with the other gridwindow functions.</p>
  
  <p>2) In GridWindow's timerFired() function, I'm having trouble checking/creating the vector-vectors. I wrote out in the comments in that function exactly what I am trying to do. </p>
  
  <p>Any help would be much appreciated. </p>
  
  <p>main.cpp</p>
  
  <pre><code>// Main file for running the grid window application.
  #include &lt;QApplication&gt;
  #include "gridwindow.h"
  //#include "timerwindow.h"
  #include &lt;stdexcept&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  #include &lt;sstream&gt;
  #include &lt;iostream&gt;
  
  void Welcome();             // Welcome Function - Prints upon running program; outputs program name, student name/id, class section.
  void Rules();               // Rules Function: Prints the rules for Conway's Game of Life.
  
  using namespace std;
  
  // A simple main method to create the window class  and then pop it up on the screen.
  int main(int argc, char *argv[])
  {
      Welcome();                                      // Calls Welcome function to print student/assignment info.
      Rules();                                        // Prints Conway's Game Rules.
      QApplication app(argc, argv);                   // Creates the overall windowed application.
      int rows = 25, cols = 35;                       //The number of rows &amp; columns in the game grid.
      GridWindow widget(NULL,rows,cols);              // Creates the actual window (for the grid).
      widget.show();                                  // Shows the window on the screen.
      return app.exec();                              // Goes into visual loop; starts executing GUI.
  }    
  
  // Welcome Function: Prints my name/id, my class number, the assignment, and the program name.
  void Welcome()                                                              
  {
      cout &lt;&lt; endl;
      cout &lt;&lt; "-------------------------------------------------------------------------------------------------" &lt;&lt; endl;
      cout &lt;&lt; "Name/ID - Gabe Audick #7681539807" &lt;&lt; endl;
      cout &lt;&lt; "Class/Assignment - CSCI-102 Disccusion 29915: Homework Assignment #4" &lt;&lt; endl;
      cout &lt;&lt; "-------------------------------------------------------------------------------------------------" &lt;&lt; endl &lt;&lt; endl;
  }
  
  // Rules Function: Prints the rules for Conway's Game of Life.
  void Rules()
  {
      cout &lt;&lt; "Welcome to Conway's Game of Life." &lt;&lt; endl;
      cout &lt;&lt; "Game Rules:" &lt;&lt; endl;
      cout &lt;&lt; "\t 1) Any living cell with fewer than two living neighbours dies, as if caused by underpopulation." &lt;&lt; endl;
      cout &lt;&lt; "\t 2) Any live cell with more than three live neighbours dies, as if by overcrowding." &lt;&lt; endl;
      cout &lt;&lt; "\t 3) Any live cell with two or three live neighbours lives on to the next generation." &lt;&lt; endl;
      cout &lt;&lt; "\t 4) Any dead cell with exactly three live neighbours becomes a live cell." &lt;&lt; endl &lt;&lt; endl;
      cout &lt;&lt; "Enjoy." &lt;&lt; endl &lt;&lt; endl;
  }
  </code></pre>
  
  <p>gridcell.h</p>
  
  <pre><code>// A header file for a class representing a single cell in a grid of cells.
  #ifndef GRIDCELL_H_
  #define GRIDCELL_H_
  
  #include &lt;QPalette&gt;
  #include &lt;QColor&gt;
  #include &lt;QPushButton&gt;
  #include &lt;Qt&gt;
  #include &lt;QWidget&gt;
  #include &lt;QFrame&gt;
  #include &lt;QHBoxLayout&gt;
  #include &lt;iostream&gt;
  
  // An enum representing the two different states a cell can have. 
  enum CellType
  {
      DEAD,                   // DEAD = Dead Cell. --&gt; Color = White.
      LIVE                    // LIVE = Living Cell. ---&gt; Color = White.
  };
  
  /*
  Class: GridCell.
      A class representing a single cell in a grid.  Each cell is implemented
      as a QT QFrame that contains a single QPushButton.  The button is sized
      so that it takes up the entire frame.  Each cell also keeps track of what
      type of cell it is based on the CellType enum.
  */
  class GridCell : public QFrame
  {
      Q_OBJECT                            // Macro allowing us to have signals &amp; slots on this object.
  
      private:    
          QPushButton* button;            // The button inside the cell that gives its clickability.
          CellType type;                  // The type of cell (DEAD or LIVE.)
  
      public slots:
          void handleClick();             // Callback for handling a click on the current cell.
          void setType(CellType type);    // Cell type mutator. Calls the "redrawCell" function.
  
      signals:
          void typeChanged(CellType type);        // Signal to notify listeners when the cell type has changed.
  
      public:
          GridCell(QWidget *parent = NULL);       // Constructor for creating a cell. Takes parent widget or default parent to NULL.
          virtual ~GridCell();                    // Destructor.
          void redrawCell();                      // Redraws cell: Sets new type/color.
          CellType getType() const;               //Simple getter for the cell type.
  
      private:
          Qt::GlobalColor getColorForCellType();  // Helper method. Returns color that cell should be based from its value.       
  };
  
  #endif
  </code></pre>
  
  <p>gridcell.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  #include "gridcell.h"
  #include "utility.h"
  
  using namespace std;
  
  // Constructor: Creates a grid cell.
  GridCell::GridCell(QWidget *parent)
  : QFrame(parent)
  { 
      this-&gt;type = DEAD;              // Default: Cell is DEAD (white).
      setFrameStyle(QFrame::Box);     // Set the frame style.  This is what gives each box its black border.
  
      this-&gt;button = new QPushButton(this);           //Creates button that fills entirety of each grid cell.
      this-&gt;button-&gt;setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);         // Expands button to fill space.
      this-&gt;button-&gt;setMinimumSize(19,19); //width,height                                 // Min height and width of button.
  
      QHBoxLayout *layout = new QHBoxLayout();                //Creates a simple layout to hold our button and add the button to it.
      layout-&gt;addWidget(this-&gt;button);
      setLayout(layout);
  
      layout-&gt;setStretchFactor(this-&gt;button,1);       // Lets the buttons expand all the way to the edges of the current frame with no space leftover
      layout-&gt;setContentsMargins(0,0,0,0);
      layout-&gt;setSpacing(0);
  
      connect(this-&gt;button,SIGNAL(clicked()),this,SLOT(handleClick()));   // Connects clicked signal with handleClick slot.
      redrawCell();           // Calls function to redraw (set new type for) the cell.
  }
  
  // Basic destructor. 
  GridCell::~GridCell()
  {
      delete this-&gt;button;
  }
  
  
  // Accessor for the cell type.
  CellType GridCell::getType() const
  {
      return(this-&gt;type);
  }
  
  // Mutator for the cell type.  Also has the side effect of causing the cell to be redrawn on the GUI.
  void GridCell::setType(CellType type)
  {
      this-&gt;type = type;
      redrawCell();
  }
  
  // Handler slot for button clicks.  This method is called whenever the user clicks on this cell in the grid.
  void GridCell::handleClick()
  {                                   // When clicked on...
    if(this-&gt;type == DEAD)            // If type is DEAD (white), change to LIVE (black).
      type = LIVE;
    else 
      type = DEAD;                    // If type is LIVE (black), change to DEAD (white).
  
    setType(type);                    // Sets new type (color). setType Calls redrawCell() to recolor.
  }
  
  // Method to check cell type and return the color of that type.  
  Qt::GlobalColor GridCell::getColorForCellType()
  {
      switch(this-&gt;type)
      {
          default:
          case DEAD:
              return Qt::white;
          case LIVE:
              return Qt::black;
      }
  }
  
  
  // Helper method. Forces current cell to be redrawn on the GUI.  Called whenever the setType method is invoked.
  void GridCell::redrawCell()
  {
      Qt::GlobalColor gc = getColorForCellType();         //Find out what color this cell should be.
      this-&gt;button-&gt;setPalette(QPalette(gc,gc));          //Force the button in the cell to be the proper color.
      this-&gt;button-&gt;setAutoFillBackground(true);
      this-&gt;button-&gt;setFlat(true);                        //Force QT to NOT draw the borders on the button
  }
  </code></pre>
  
  <p>gridwindow.h</p>
  
  <pre><code>// A header file for a QT window that holds a grid of cells.
  #ifndef GRIDWINDOW_H_
  #define GRIDWINDOW_H_
  
  #include &lt;vector&gt;
  #include &lt;QWidget&gt;
  #include &lt;QTimer&gt;
  #include &lt;QGridLayout&gt;
  #include &lt;QLabel&gt;
  #include &lt;QApplication&gt;
  #include "gridcell.h"
  
  /*
  class GridWindow:
      This is the class representing the whole window that comes up when this program runs.  
      It contains a header section with a title, a middle section of MxN cells and a bottom section with buttons.
  */
  class GridWindow : public QWidget
  {
      Q_OBJECT                            // Macro to allow this object to have signals &amp; slots.
  
      private:
          std::vector&lt;std::vector&lt;GridCell*&gt; &gt; cells;     // A 2D vector containing pointers to all the cells in the grid.
          QLabel *title;                                  // A pointer to the Title text on the window.
          QTimer *timer;                                  // Creates timer object.
  
      public slots:
          void handleClear();             // Handler function for clicking the Clear button.
          void handleStart();             // Handler function for clicking the Start button.
          void handlePause();             // Handler function for clicking the Pause button.
          void timerFired();              // Method called whenever timer fires.
  
      public:
          GridWindow(QWidget *parent = NULL,int rows=3,int cols=3);       // Constructor.
          virtual ~GridWindow();                                          // Destructor.
          std::vector&lt;std::vector&lt;GridCell*&gt; &gt;&amp; getCells();               // Accessor for the array of grid cells.
  
      private:
          QHBoxLayout* setupHeader();                     // Helper function to construct the GUI header.
          QGridLayout* setupGrid(int rows,int cols);      // Helper function to constructor the GUI's grid.
          QHBoxLayout* setupButtonRow();                  // Helper function to setup the row of buttons at the bottom.
  };
  
  #endif
  </code></pre>
  
  <p>gridwindow.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "gridwindow.h"
  
  using namespace std;
  
  // Constructor for window. It constructs the three portions of the GUI and lays them out vertically.
  GridWindow::GridWindow(QWidget *parent,int rows,int cols)
  : QWidget(parent)
  {
      QHBoxLayout *header = setupHeader();            // Setup the title at the top.
      QGridLayout *grid = setupGrid(rows,cols);       // Setup the grid of colored cells in the middle.
      QHBoxLayout *buttonRow = setupButtonRow();      // Setup the row of buttons across the bottom.
      QVBoxLayout *layout = new QVBoxLayout();        // Puts everything together.
      layout-&gt;addLayout(header);
      layout-&gt;addLayout(grid);
      layout-&gt;addLayout(buttonRow);
      setLayout(layout);
  }
  
  // Destructor.
  GridWindow::~GridWindow()
  {
      delete title;
  }
  
  // Builds header section of the GUI.  
  QHBoxLayout* GridWindow::setupHeader()
  {
      QHBoxLayout *header = new QHBoxLayout();            // Creates horizontal box.
      header-&gt;setAlignment(Qt::AlignHCenter);
  
      this-&gt;title = new QLabel("CONWAY'S GAME OF LIFE",this);             // Creates big, bold, centered label (title): "Conway's Game of Life."
      this-&gt;title-&gt;setAlignment(Qt::AlignHCenter);
      this-&gt;title-&gt;setFont(QFont("Arial", 32, QFont::Bold));
  
      header-&gt;addWidget(this-&gt;title);     // Adds widget to layout.
  
      return header;                      // Returns header to grid window.
  }
  
  // Builds the grid of cells.  This method populates the grid's 2D array of GridCells with MxN cells.
  QGridLayout* GridWindow::setupGrid(int rows,int cols)
  {
      QGridLayout *grid = new QGridLayout();      // Creates grid layout.
  
      grid-&gt;setHorizontalSpacing(0);              // No empty spaces. Cells should be contiguous.
      grid-&gt;setVerticalSpacing(0);
      grid-&gt;setSpacing(0);
      grid-&gt;setAlignment(Qt::AlignHCenter);
  
      for(int i=0; i &lt; rows; i++)                     //Each row is a vector of grid cells.
      {
          std::vector&lt;GridCell*&gt; row;                 // Creates new vector for current row.
          cells.push_back(row);
          for(int j=0; j &lt; cols; j++)
          {
              GridCell *cell = new GridCell();        // Creates and adds new cell to row.
              cells.at(i).push_back(cell);
  
              grid-&gt;addWidget(cell,i,j);              // Adds to cell to grid layout. Column expands vertically.
              grid-&gt;setColumnStretch(j,1);
          }
          grid-&gt;setRowStretch(i,1);                   // Sets row expansion horizontally.
      }
      return grid;                                    // Returns grid.
  }
  
  // Builds footer section of the GUI.  
  QHBoxLayout* GridWindow::setupButtonRow()
  {
      QHBoxLayout *buttonRow = new QHBoxLayout();     // Creates horizontal box for buttons.
      buttonRow-&gt;setAlignment(Qt::AlignHCenter);
  
      // Clear Button - Clears cell; sets them all to DEAD/white.
      QPushButton *clearButton = new QPushButton("CLEAR");
      clearButton-&gt;setFixedSize(100,25); 
      connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear()));     
      buttonRow-&gt;addWidget(clearButton);
  
      // Start Button - Starts game when user clicks. Or, resumes game after being paused.
      QPushButton *startButton = new QPushButton("START/RESUME");
      startButton-&gt;setFixedSize(100,25);              
      connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart()));     
      buttonRow-&gt;addWidget(startButton);
  
      // Pause Button - Pauses simulation of game.
      QPushButton *pauseButton = new QPushButton("PAUSE");
      pauseButton-&gt;setFixedSize(100,25);              
      connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause()));     
      buttonRow-&gt;addWidget(pauseButton);  
  
      // Quit Button - Exits program.
      QPushButton *quitButton = new QPushButton("EXIT");
      quitButton-&gt;setFixedSize(100,25); 
      connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));     
      buttonRow-&gt;addWidget(quitButton);
  
      return buttonRow;               // Returns bottom of layout.
  }
  
  /*
      SLOT method for handling clicks on the "clear" button. 
      Receives "clicked" signals on the "Clear" button and sets all cells to DEAD.
  */
  void GridWindow::handleClear()
  {
      for(unsigned int row=0; row &lt; cells.size(); row++)          // Loops through current rows' cells.
      {
      for(unsigned int col=0; col &lt; cells[row].size(); col++)
          {
              GridCell *cell = cells[row][col];                   // Grab the current cell &amp; set its value to dead.
              cell-&gt;setType(DEAD);
          }
      }
  }
  
  /*
      SLOT method for handling clicks on the "start" button. 
      Receives "clicked" signals on the "start" button and begins game simulation.
  */
  void GridWindow::handleStart()
  {
      this-&gt;timer = new QTimer(this);                                     // Creates new timer.
      connect(this-&gt;timer, SIGNAL(timeout()), this, SLOT(timerFired()));  // Connect "timerFired" method class to the "timeout" signal fired by the timer.
      this-&gt;timer-&gt;start(500);                                            // Timer to fire every 500 milliseconds.
  }
  
  /*
      SLOT method for handling clicks on the "pause" button. 
      Receives "clicked" signals on the "pause" button and stops the game simulation.
  */
  void GridWindow::handlePause()
  {
          this-&gt;timer-&gt;stop();        // Stops the timer.
          delete this-&gt;timer;         // Deletes timer.
  }
  
  // Accessor method - Gets the 2D vector of grid cells.
  std::vector&lt;std::vector&lt;GridCell*&gt; &gt;&amp; GridWindow::getCells()
  {
      return this-&gt;cells;
  }
  
  
  void GridWindow::timerFired()
  {
      // I'm not sure how to write this code.
      // I want to take the original vector-vector, and also make a new, empty vector-vector of the same size.
      // I would then go through the code below with the original vector, and apply the rules to the new vector-vector.
      // Finally, I would make the new vector-vecotr the original vector-vector. (That would be one step in the simulation.)
  
      cout &lt;&lt; cells[1][2];    
      /*
       for (unsigned int m = 0; m &lt; original.size(); m++)
       {
           for (unsigned int n = 0; n &lt; original.at(m).size(); n++)
           {
               unsigned int neighbors = 0;                                //Begin counting number of neighbors.
  
               if (original[m-1][n-1].getType() == LIVE)      // If a cell next to [i][j] is LIVE, add one to the neighbor count.
                  neighbors += 1;
               if (original[m-1][n].getType() == LIVE) 
                  neighbors += 1;
               if (original[m-1][n+1].getType() == LIVE) 
                  neighbors += 1;
               if (original[m][n-1].getType() == LIVE) 
                  neighbors += 1;
               if (original[m][n+1].getType() == LIVE) 
                  neighbors += 1;
               if (original[m+1][n-1].getType() == LIVE) 
                  neighbors += 1;
               if (original[m+1][n].getType() == LIVE) 
                  neighbors += 1;
               if (original[m+1][n+1].getType() == LIVE) 
                  neighbors += 1;
  
               if (original[m][n].getType() == LIVE &amp;&amp; neighbors &lt; 2)             // Apply game rules to cells: Create new, updated grid with the roundtwo vector.
                  roundtwo[m][n].setType(LIVE);
               else if (original[m][n].getType() == LIVE &amp;&amp; neighbors &gt; 3)
                  roundtwo[m][n].setType(DEAD);
               else if (original[m][n].getType() == LIVE &amp;&amp; (neighbors == 2 || neighbors == 3))
                  roundtwo[m][n].setType(LIVE);
               else if (original[m][n].getType() == DEAD &amp;&amp; neighbors == 3)
                  roundtwo[m][n].setType(LIVE);  
           }
      }*/
  }
  </code></pre>