Hi this is an example of my C++
program. Game of life is one of the assignments from the class that I did
demonstrating.
The Game of Life is a mathematical
“game” played on a square board. The board is a grid of squares each of which
may be occupied by a cell, or unoccupied. The game progresses through a
series of generations. In each generation cells live, die and are born
according to a set of rules. A new cell is born on an empty square if it is
surrounded by exactly three neighbor cells. A cell dies from loneliness if it
is surrounded by zero or one neighbor cells. It dies from overcrowding if it
surrounded by four or more neighbor cells.
As an added challenge, extend this program so that it can
simulate the behavior of two types of cell:
• normal
cell: Behavior as described above.
• extrovert
cell: This cell dies of overcrowding only if it is surrounded by six or more neighbor
cells. It dies of loneliness if it is surrounded by less than four neighbor
cells.
A new cell is an extrovert only if most of its neighbor
cells are extroverts.
In the code, there are
three classes. Board class controls the game, i.e., drawing cells and the
board, etc. Game class controls cell types and rule in the game. The design
allows Board to accept many types of Game. For example, EGame
class is the inheritance of Game. By using polymorphism, players can choose
to play Game or EGame or even write their own game
class for the same Board.
Board class contains two
matrices. Each point of matrix represents each point on the board. A is for
before updated while B is for after updated according to the rule function
from Game. Actually, we can have these matrices contain pointer to drawing
objects (normal or extrovert or different types of cells) so that plot
function can draw cells directly (using polymorphism). However, the memory
required for pointer is pointer is larger than char. So for the better use of
memory, I decide to use char matrices. Of course, it has no effect for a
small program like this. Alive function is constant because the function does
not change any data in the class.
Game and EGame classes contain a vector of cells. Every function
and data in the classes are declared as public
because they are needed to be accessed by Board class. Rule functions are
constant.
This program has been
run and tested using eclipse on window.
Download
|