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]
Game of life issue
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement