Game of life issue

Started by
1 comment, last by Psilobe 11 years, 6 months ago
I'm trying to implement the game of life in c++ but I've run in to some trouble where I don't get the correct result.
I think the problem is with memcpy() as it seems to mess up the arrays but I'm not sure why. If I just copy the two different arrays using nested for loops I get a different result which is also wrong.

[source lang="cpp"]#include <iostream>
#include <conio.h>
#include <string>

void update();
void init();
int calcNeighbours(int i, int j);
void draw();

bool run = true;
bool field[20][20];

int main()
{
init();
draw();
getch();
while(run)
{
update();
draw();
getch();
}
return 0;
}

void update()
{
int temp = 0;
int tf[20][20];

memcpy(tf,field,sizeof(tf));

for(int i = 0;i<20;i++)
{
for(int j = 0;j<20;j++)
{
temp = calcNeighbours(i,j);
if(field[j]==true && temp < 2)
{
tf[j] = false;
}
else if(field[j]==true && temp > 3)
{
tf[j] = false;
}
else if(field[j]==true && (temp == 2 || temp == 3))
{
tf[j] = true;
}
else if(field[j]==false && temp == 3)
{
tf[j] = true;
}
}
}

memcpy(field,tf,sizeof(field));

}

void init()
{
for(int i = 0;i<20;i++)
{
for(int j = 0;j<20;j++)
{
field[j] = false;
}
}

field[3][5] = true;
field[4][5] = true;
field[5][5] = true;
field[4][4] = true;
field[4][6] = true;

}

int calcNeighbours(int i, int j)
{
int temp = 0;

for(int a = -1;a<1;a++)
{
for(int b = -1;b<1;b++)
{
if(field[i-a][j-b] == true)
temp+=1;
}
}
return temp;
}

void draw()
{
system("cls");
for(int i = 0;i<20;i++)
{
std::cout<<std::endl;
for(int j = 0;j<20;j++)
{
if(field[j]==true)
std::cout<<"X";
else
std::cout<<" ";
}
}
}[/source]
Advertisement
You have defined field as an array of booleans and tf as an array of integers. They have different types and probably also different sizes.
Thanks, now the copying works. I still got a problem with the figures being wrong. Somewhere I do something wrong with the rules of game of life or calculating the neighbors but I cant find where.

I found what I did wrong, in calcNeighbors when I loop I wrote <1 instead of <=1.

This topic is closed to new replies.

Advertisement