Tuesday, September 6, 2016

JAVA 18 - Conway's Game Of Life example

Conway's Game Of Life is an algorithm used to simulate complex patterns - you can read more here.

We're going to build a class to enable us to reproduce the following logic for a single cell,

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

  • Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  • Any live cell with two or three live neighbours lives on to the next generation.
  • Any live cell with more than three live neighbours dies, as if by over-population.
  • Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Attributes

For just a cell (all we're modelling at this point) there are two obvious attributes
  • isAlive - whether the cell is alive or not
  • numLiveNeighbours - the number of live neighbours the cell has


Methods - basic

I decided not to bother with complicated constructors and just use the basic one.  However I decided to "getter and setter" my attributes (make get and set methods for each).  This would allow me to configure a cell as I needed it configured.



Conway's Rules Method

This applies the above Conway's rules to the cell, and change the status.



Test it

The following are 3 @Test methods for my class - it really needs a lot more ...



I set up my cell, then assert it's in the state I expect.

The code is available in Github here.



Extension material

Create some more @Tests for this class.

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete