The Game of Life
The Game of Life was invented by the mathematician John Horton Conway around 1970. It isn't a game you play: you set up a pattern and watch what happens. The board is a grid of cells, and each cell is either alive or dead. Every cell has eight neighbors: the cells above, below, to the left, to the right and on the four diagonals. From one generation to the next, every cell follows the same rules at the same time:
- A live cell with 2 or 3 live neighbors stays alive.
- A live cell with fewer than 2 live neighbors dies, as if lonely, and one with more than 3 dies, as if overcrowded.
- A dead cell with exactly 3 live neighbors comes alive.
- Any other dead cell stays dead.
That's all, and yet some patterns blink, some stay still, some die out, and some travel across the board. In this project you write a program that reads a pattern from a file and prints a few generations of it as text, with O for a live cell and . for a dead one.
When it's finished, the program reads three lines: the name of a pattern file, how many generations to show, and wrap or edges (whether the board wraps around at its edges). With this glider.txt, where the lines that start with ! are comments,
!Name: Glider
!It moves one cell down and one to the right every four generations.
.O....
..O...
OOO...
......
......
and the input glider.txt, 4 and wrap, it prints:
Generation 0: 5 alive
.O....
..O...
OOO...
......
......
Generation 1: 5 alive
......
O.O...
.OO...
.O....
......
Generation 2: 5 alive
......
..O...
O.O...
.OO...
......
Generation 3: 5 alive
......
.O....
..OO..
.OO...
......
Generation 4: 5 alive
......
..O...
...O..
.OOO..
......
After four generations the glider has its first shape again, one row lower and one column further right.
What you need
Everything up to the end of part 12. Above all two-dimensional arrays, nested loops and the cells around a cell (module 47), and also classes with a constructor and toString (modules 17 and 18), StringBuilder (module 39), and reading a file with Files.readAllLines and throws IOException (module 42).
How you build it
The program has two classes: Board, which keeps the cells in a boolean[][] and knows the rules, and Main, which reads the pattern and prints the generations. Most of the work is in Board, and the checks of the first milestones call its methods directly.
- A grid of cells: create the board, bring cells to life, and show it as text.
- Counting neighbors: how many live cells are around a cell, and whether it lives on.
- One generation: the whole board takes one step, every cell at the same time.
- Wrapping around: the edges of the board meet, so a glider leaves on one side and comes back on the other.
- Patterns from a file: read a board from a text file of
Oand.. - Generations as text:
mainputs it all together, and stops early when nothing changes.
Milestones
- A grid of cells
- Counting neighbors
- One generation
- Wrapping around
- Patterns from a file
- Generations as text