Thanks to Julie Zelenski for the idea and Jerry Cain, Keith Schwarz, Cynthia Lee and Marty Stepp for revisions.
January 6th, 2016
A still image of the Game of Life
For your first assignment... We make the Game of Life!
The purpose of this assignment is to gain familiarity with basic C++ features such as functions, strings, and I/O streams, using provided libraries, and decomposing a large problem into smaller functions. This is an individual assignment. You should write your own solution and not work in a pair on this program.
The Game of Life is a simulation originally conceived by the British mathematician J. H. Conway in 1970 and popularized by Martin Gardner in his Scientific American column. The game models the life cycle of bacteria using a two-dimensional grid of cells. Given an initial pattern, the game simulates the birth and death of future generations of cells using a set of simple rules. In this assignment you will implement a simplified version of Conway's simulation and a basic user interface for watching the bacteria grow over time.
The starter code for this project is availible as a ZIP archive:
Your Game of Life program should begin by prompting the user for a file name and using that file's contents to set the initial state of your bacterial colony grid. Then it will allow the user to advance the colony through generations of growth. The user can type t to "tick" forward the bacteria simulation by one generation, or a to begin an animation loop that ticks forward the simulation by several generations, once every 50 milliseconds; or q to quit. Your menu should be case-insensitive; for example, an uppercase or lowercase A, T, or Q should work.
Here is an example log of interaction between your program and the user (with console input in blue).
Of course there are many other interactions you could have. Here is a bunch more examples. They show what to do in many cases, for example bad input filenames.
You will turn in only the following files:
life.cpp
, the C++ code for the Game of Life simulationmycolony.txt
, your own unique Game of Life input file representing a bacterial colony's starting stateThe ZIP archive contains other files and libraries; you should not modify these. When grading/testing your code, we will run your life.cpp with our own original versions of the support files, so your code must work with them.
Each grid location is either empty or occupied by a single living cell (X). A location's neighbors are any cells in the surrounding eight adjacent locations. In the example at right, the shaded middle location has three neighbors containing living cells. A square that is on the border of the grid has fewer than eight neighbors. For example, the top-right X square in the example at right has only three neighboring squares, and only one of them contains a living cell (the shaded square), so it has one living neighbor.
The simulation starts with an initial pattern of cells on the grid and computes successive generations of cells according to the following rules:
The births and deaths that transform one generation to the next all take effect simultaneously. When you are computing a new generation, new births/deaths in that generation don't impact other cells in that generation. Any changes (births or deaths) in a given generation k start to have effect on other neighboring cells in generation k+1.
Check your understanding of the game rules by looking at the following example. The two patterns should alternate forever:
Here is a second example. The pattern at right does not change on each iteration, because each cell has exactly three living neighbors. This is called a "stable" pattern or a "still life".
The grid of bacteria in your program gets its initial state from one of a set of provided input text files, which follow a particular format. When your program reads the grid file, you should re-prompt the user if the file specified does not exist. If it does exist, you may assume that all of its contents are valid. You do not need to write any code to handle a misformatted file. The behavior of your program in such a case is not defined in this spec; it can crash, it can terminate, etc. You may also assume that the input file name typed by the user does not contain any spaces.
In each input file, the first two lines will contain integers r and c representing the number of rows and columns in the grid, respectively. The next lines of the file will contain the grid itself, a set of characters of size r x c with a line break (\n) after each row. Each grid character will be either a '-' (minus sign) for an empty dead cell, or an 'X' (uppercase X) for a living cell. The input file might contain additional lines of information after the grid lines, such as comments by its author or even junk/garbage data; any such content should be ignored by your program.
The input files will exist in the same working directory as your program. For example, the following text might be the contents of a file simple.txt, a 5x9 grid with 3 initially live cells:
5 ← number of rows tall 9 ← number of columns wide --------- --------- ← - is a dead cell ---XXX--- ← X is a living cell --------- ---------
Grid: The grid of bacterial cells could be stored in a 2-dimensional array, but arrays in C++ lack some features and are generally difficult for new students to use. They do not know their own length, they cause strange bugs if you try to index out of the bounds of the array, and they require understanding C++ topics such as pointers and memory allocation. So instead of using an array to represent your grid, you will use an object of the Grid class, which is part of the provided Stanford C++ library.
A Grid object offers a cleaner abstraction of a 2-dimensional data set, with several useful methods and features. See the course lecture examples and/or section 5.1 of the Programming Abstractions in C++ textbook for a list of members of the Grid class. You can also use the = assignment operator to copy the state of one Grid object to another.
Your main function should create your Grid and pass it to the other functions. Since it is expensive to make copies of a Grid, if your code passes a Grid object as a parameter from one function to another, it should always do so by reference (Grid&, not Grid). See the lecture notes for examples. Since you don't know the size of the grid until you read the input file, you can call resize on the Grid object once you know the proper size.
I/O: Your program has a console-based user interface. You can produce console output using cout and read console input using cin. You may use the Stanford C++ library's console-related functions such as getLine (uppercase L) to read from the console. See the Stanford C++ library documentation on the class web site.
You will also write code for reading input files. Read a file using an ifstream object, along with functions such as getline (lowercase L) to read lines from the file. Here are some useful ifstream-related functions from filelib and strlib:
Command | Description |
---|---|
openFile(ifstream & stream, string filename);
|
Opens the file with the given filename/path and stores it into the given ifstream output parameter. |
getline(ifstream & stream, string & line);
|
Reads a line from the given stream and stores it into the given string variable by reference. |
fileExists(string & fileName);
|
Checks if a file with the corresponding fileName exists. Returns a bool. |
stringToInteger(str)
|
Returns an int value equivalent to the given string; for example,"42" → 42 |
integerToString(n)
|
Returns a string value equivalent to the given integer; for example,42 → "42" |
Make sure to close your input file streams when you are done reading the given file: stream.close().
Checking for valid input: Note that your program needs to check for valid user input in a few places. When the user types the grid input file name, you must ensure that the file exists, and if not, you must re-prompt the user to enter a new file name. If the user is prompted to enter an action such as 't' for tick or 'a' for animate, if the user types anything other than the three predefined commands of a, t, or q (case-insensitively), you should re-prompt the user to enter a new command. If the user is prompted to enter an integer such as the number of frames of animation for the 'a' command, your code should re-prompt the user if they type a non-integer token of input. (If they do type an integer, you may assume that it is a valid value greater than 0; you don't need to explicitly test or check its value.) See the expected output files on the class web site for examples of this output. There are several functions from the Stanford C++ library that can help you with this functionality, such as fileExists and getInteger.
Animation: When the user selects the animation option, the console output should look like the following:
a)nimate, t)ick, q)uit? a How many frames? xyz Illegal integer format. Try again. How many frames? 5 (five new generations are shown, with screen clear and 50ms pause before each)
It is hard to show an example of animation output in this handout because the output does not translate well to a plain-paper format. The screen is supposed to clear between each generation of cells, leading to what looks like a smooth animation effect. Run the Sample Solution from the class web site to see how animation should work.
To help you perform animation, use the following global functions from the Stanford C++ library:
Command | Description |
---|---|
pause(ms);
|
Causes the program to halt execution for the given number of milliseconds |
clearConsole();
|
Erases all currently visible text from the output console (call this between frames) |
Along with your program, submit a file mycolony.txt that contains a valid initial colony that can be used as input. This can be anything you want, as long as it is in the input grid file format described in this document, and should be your own work (not just a copy of an existing colony input file). This is worth a small part of your grade.
Development strategy: It is tempting to try to write your entire program and then try to compile and run it; we do not recommend that strategy. Instead, you should develop your program incrementally: Write a small piece of functionality, then test/debug it until it works, then move on to another small piece. This way you are always making small consistent improvements to a base of working code. Here is a possible list of steps to develop a solution:
Updating from one generation to the next: When you are trying to advance the bacteria from one generation to the next, you cannot do this "in place" by modifying your grid as you loop over it. Doing so will change the cells and their neighbors and break the neighbor counts for nearby cells. So you will need to create a temporary second grid. Your existing grid represents the current generation of bacteria, and you can create a second temporary second grid that allows you to compute and store the next generation without changing the current one. Once you have filled the second grid with the next generation's cell information, you can copy its contents back into the original grid and discard the temporary copy. Copying one Grid to another is easy; just assign one to the other using the = assignment operator, which makes a copy of its contents.
Output: We want your output to match ours exactly. This includes identical spacing, such as the extra spaces after the phrase, "Grid input file name? " Some students lose points for minor output formatting errors. Please run the web Output Comparison Tool on several test cases to make sure it matches without any differences.
Hints: Here are some other miscellaneous tips that may help you:
Thats all! You are done. Consider adding extra features.