I'm a beginner in C++, and I'd like you to review the class I wrote for the Game Of Life.
GameOfLife.h
#include <vector>
#include <iostream>
using namespace std;
class GameOfLife{
public:
GameOfLife(void);
GameOfLife(const unsigned &, const unsigned &);
~GameOfLife(void);
void display(void);
void swapCell(const unsigned &,const unsigned &);
void updateField();
private:
unsigned Xmax, Ymax;
unsigned XSize, YSize;
vector< vector<unsigned> > field;
unsigned newValCell(const unsigned &, const unsigned &);
};
GameOfLife.cpp
#include "GameOfLife.h"
GameOfLife::GameOfLife(void) {
Xmax = 10;
Ymax = 10;
XSize = Xmax + 2;
YSize = Ymax + 2;
for (unsigned i = 0; i != XSize; i++)
{
vector<unsigned> inter;
for (unsigned j = 0; j != YSize; j++)
{
inter.push_back(0);
}
field.push_back(inter);
}
}
GameOfLife::GameOfLife(const unsigned &x, const unsigned &y) {
Xmax = x;
Ymax = y;
XSize = Xmax + 2;
YSize = Ymax + 2;
for (unsigned i = 0; i != XSize; i++)
{
vector<unsigned> inter;
for (unsigned j = 0; j != YSize; j++)
{
inter.push_back(0);
}
field.push_back(inter);
}
}
GameOfLife::~GameOfLife(void)
{
return;
}
void GameOfLife::swapCell(const unsigned &x, const unsigned &y)
{
field[x][y] = !field[x][y];
return;
}
// return the new value of a cell depending on the surrounding values
unsigned GameOfLife::newValCell(const unsigned &x, const unsigned &y)
{
unsigned stok;
stok = field[x-1][y-1]
+ field[x-1][y]
+ field[x-1][y+1]
+ field[x][y-1]
+ field[x][y+1]
+ field[x+1][y-1]
+ field[x+1][y]
+ field[x+1][y+1];
switch(stok)
{
case 3: return 1;
case 2: return field[x][y];
default: return 0;
}
}
void GameOfLife::updateField(void)
{
vector< vector<unsigned> > stockField = field;
for (unsigned i = 1; i != Xmax + 1; i++)
{
for (unsigned j = 1; j != Ymax + 1; j++)
{
stockField[i][j] = newValCell(i,j);
}
}
field = stockField;
return;
}
void GameOfLife::display(void)
{
for (int i = 1; i != Xmax + 1; i++)
{
for (int j = 1; j != Ymax + 1; j++)
{
cout << field[i][j] << " ";
}
cout << "\n";
}
return;
}
main()
#include "GameOfLife.h"
int main()
{
GameOfLife a = GameOfLife(7,7);
a.swapCell(1,5);
a.swapCell(2,5);
a.swapCell(3,5);
a.swapCell(3,6);
a.swapCell(2,7);
a.display();
cout << "-------\n";
a.updateField();
a.display();
cout << "-------\n";
a.updateField();
a.display();
cout << "-------\n";
a.updateField();
a.display();
cout << "-------\n";
a.updateField();
a.display();
cout << "-------\n";
a.updateField();
a.display();
return 0;
}
void
in the( )
parameter list if the function takes 0 arguments, that's just useless boilerplate. Also, keeping the parameter names in function prototypes helps documenting the code. \$\endgroup\$GameOfLife::GameOfLife(void) {
is really the same asGameOfLife(10,10);
. Avoid copy-pasted code. \$\endgroup\$