CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2012
    Posts
    12

    Game of Life program

    Hi, I'm fairly new to programming and have been given this assignment:
    Conway's Game of Life usesthese rules:
    -Each cell is either alive or dead
    -Cells are represented on a rectangular grid, each cell has 8 neighboring spaces
    -A live cell with fewer than 2 or more than 3 live neighbors dies on the next iteration
    -A dead cell with exactly 3 live neighbors becomes alive on the next iteration
    -Otherwise the cell's state is unchanged on the next iteration

    Your task is to write a C++ program that runs the game on a grid that is 24 rows by 79 columns. The easiest way to do this is to maintain two two-dimensional arrays of int, one for the current state, one for the next state. Represent live cells with a 1, dead cells with a 0. Pass them to a function that calculates the next state from the current one, and alternate the order of the arguments on each call. Clear the screen, display the state array (space for dead, X for alive), pause for a short time, then repeat.
    My teacher gave us the main function and the function called neighbors, but we need to write the other functions listed in the header. Here's what I have so far:

    Code:
    int main(int argc, char** argv)
    {
    	ifstream fin;
    	string fileName = "";
    	if (argc > 1)
    		fin.open(argv[1]);
    	else
    	{
    		cerr << "Name of input file? ";
    		cin >> fileName;
    		fin.open(fileName.c_str());
    	}
    	if (!fin)
    	{
    		if (fileName == "")
    			perror(argv[1]);
    		else
    			perror(fileName.c_str());
    		exit(1);
    	}
    	int current[ROWS][COLUMNS] = {0};
    	int next[ROWS][COLUMNS] = {0};
    	int r, c;
    	while (fin >> r >> c)
    	{
    		current[r][c] = 1;
    	}
    	while(!equal(current, next))
    	{
    		print(current);
    		nextstate(current, next);
    		print(next);
    		nextstate(next,current);
    	}
    }
    
    bool equal(int current[ROWS][COLUMNS], int next[ROWS][COLUMNS])
    {
    	int magicNumber = (24 * 79);
    	int count =0;
    	bool same = false;
    
    	for (int r=0; r<ROWS; r++)
    	{
    		for (int c=0; c<COLUMNS; c++)
    		{
    			if (current[r][c] == next[ROWS][COLUMNS])
    				count++;
    		}
    	}
    	if (count == magicNumber)
    		same = true;
    	else 
    		same = false;
    	return(same);
    }
    
    void print(int current[ROWS][COLUMNS])
    {
    	system("cls");
    	for (int r=0; r<ROWS; r++)
    	{
    		for (int c=0; c<COLUMNS; c++)
    		{
    			if (current[r][c] == 1)
    				cout << "X";
    			else
    				cout << ".";
    		}
    		cout << endl;
    	}
    	Sleep(500);
    }
    
    void nextstate(int current[ROWS][COLUMNS], int next[ROWS][COLUMNS])
    {
    	int sum;
    	for (int r=0; r<ROWS; r++)
    	{
    		for (int c=0; c<COLUMNS; c++)
    		{
    			sum = neighbors(current, r, c);
    			if(current[r][c] == 1)
    			{
    				if (sum < 2 || sum > 3)
    					next[r][c] = 0;
    				else
    					next[r][c] = 1;
    			}
    			else 
    			{
    				if (sum == 3)
    					next[r][c] = 1;
    				else
    					next[r][c] = 0;
    			}
    
    		}
    
    	}
    }
    
    //*******************************************************************
    //  Return number of neighbors of cell current[i][j]
    int neighbors(int current[ROWS][COLUMNS], int i, int j)
    {
    	int r, c;
    	int sum = 0;
    	for (r = i-1; r<=i+1; r++)
    	{
    		for (c = j-1; c<=j+1; c++)
    		{
    			if ((r >= 0) && (r < ROWS) && (c >=0) && (c<COLUMNS))
    			{
    				sum += current[r][c];
    			}
    		}
    	}
    	sum -= current[i][j];
    	return sum;
    }
    First off, I'm not even sure if I've done this correctly at all. My problem right now is that every time I run the program, I can't get it to print anything but 1s and 0s, when it's supposed to print Xs for 1s and blanks for 0s (he gave us a .exe file to see what the end product should look like, and it's various patterns formed by Xs). How can I get it to print something other than the numeric values of each cell?

    Unless I'm totally off base with this assignment and have done it completely wrong. All the other codes for this program that I've found online seem much more complicated than mine, so I feel like I must have done something wrong.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Game of Life program

    Quote Originally Posted by taymaxi View Post
    First off, I'm not even sure if I've done this correctly at all. My problem right now is that every time I run the program, I can't get it to print anything but 1s and 0s, when it's supposed to print Xs for 1s and blanks for 0s
    Did you debug your program? Step through your program with the debugger and see where it goes wrong.

    Programming isn't about writing code and running the program. You must learn how to debug the code that you've written.
    Unless I'm totally off base with this assignment and have done it completely wrong.
    When you finally write a program, you must know what you had in mind, what you wrote on paper, the logical flow of what you want done, etc. Then you write the code with this knowledge. There really is no such thing as writing a program and not knowing what you're doing -- if you don't know what you're doing, then you're not ready to write the program.

    Once you have written the program, if the program doesn't do what you expect, then you debug the program and see where it deviates from your plan. Then you make changes to fix where the logical flow breaks down.
    All the other codes for this program that I've found online
    Don't do that -- write the program yourself, starting out by putting on paper a plan, an algorithm, discrete steps that can be followed, etc. Once you do that, then it becomes time to write the program. Taking code that is done online doesn't teach you anything, unless you are already an experienced C++ programmer who is looking for a function, library, etc. that does a specific (and complex) task.

    Having said this, this is not right, and you don't even need to know what the program is supposed to do:
    Code:
    if (current[r][c] == next[ROWS][COLUMNS])
    You are accessing an invalid entry in the "next" array. Array indices are numbered from 0 to n-1. If the array is declared as next[ROWS][COLUMNS], then the highest index is next[ROWS-1][COLUMNS-1], since array indices start at 0.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; October 10th, 2012 at 03:32 AM.

  3. #3
    Join Date
    Sep 2012
    Posts
    12

    Re: Game of Life program

    Okay. Thanks.

    That error in my code was a mistype which somehow didn't register when I was looking it over. I understand that it's supposed to compare to next[r][c], not next[ROWS][COLUMNS]. As soon as that was changed, it works fine.

    Again, thanks.

  4. #4
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Game of Life program

    The game of life is a program that has a simple set of rules and that you can write with a small amount of knowledge.
    But. a simple straightforward implementation will be slow. The simpel solution will have 2 for loops, 8 tests per cell (involving more hidden address calculations) + a counter, and 2 or 3 more tests to decide if the new cell state.

    On a 24*79 grid you won't really notice much, but it isn't uncommon to find grids into the hundreds. On a 1000x1000 grid, we're talking 1 million cells, needing several hundred CPU cycles to test each cell. Computing a new generation then starts be be noticable.

    This is where optimisations kick in. It is quite easy to make more complex "calculate next generation" routines that are considerably faster than the simple approach. Even minor changes can make this several times (yes, times, not percentages) faster.

    I use this particular problem as a case in a class on optimisation because it is both fun (especially once you get generation times fast enough that you can start talking about 'smooth animation') and it is an excellent example of how far you can take things (and at what extremes you need to go in code to achieve that).

    This is why you find such vast different bits of code to do this, they're all using some form of 'trickery' to make the program go faster, but that comes at added complexity of course.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured