Conway’s Game of Life

This is just a simple demonstration of lambdas to implement the Cell but the code may not be complete.

package com.game.test;

import java.util.ArrayList;
import java.util.List;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.runner.RunWith;

import com.game.conway.Cell;

@RunWith(JMock.class)

public class Game {

    Mockery context = new JUnit4Mockery();
    
    @SuppressWarnings("deprecation")
	@Test 
    public void mocksurvive() {
        // set up
    	context = new Mockery() {  
    		  {  
    		    setImposteriser(ClassImposteriser.INSTANCE);  
    		  }  
    		};
    	Cell cell = context.mock(Cell.class);
    	final List<Cell> cells = new ArrayList<Cell>();
		cells.add(new Cell(1,1));
		cells.add(new Cell(8,2));
		cells.add(new Cell(2,2));
		

        
        // expectations
        context.checking(new Expectations() {
             {
                 oneOf(cell).setX(1);
                 oneOf(cell).setY(1);
                 oneOf(cell).survive(cells);
                 will(returnValue(false));
             }
         });
    	cell.setX(1);
    	cell.setY(1);
         final boolean result = cell.survive(cells);

    }
}


package com.game.conway;

import java.util.List;

public class Cell implements Comparable<Cell>{
	
	public Cell(int x, int y) {
		this.x = x;
		this.y = y;
	}

	int x,y;

	public Object getX() {
		return x;
	}

	public Object getY() {
		return y;
	}

	public boolean neighbour(Cell neighbour) {
		return Math.abs(x - neighbour.x) <= 1 && 
			   Math.abs(y - neighbour.y) <= 1 &&
			   !(this.compareTo(neighbour) == 0);
	}

	public long countNeighbours(List<Cell> cells) {
		return cells.stream().filter( c -> neighbour(c)).count();
	}

	public boolean survive(List<Cell> cells) {
		long count = countNeighbours(cells);
		if(cells.stream().anyMatch( c -> (this.compareTo(c) == 0) )){
			return count == 2 || count == 3;
		}
		
		return count == 3;
	}


	@Override
	public int compareTo(Cell o) {
		if( x == o.x && y == o.y)
			return 0;
		else
			return -1;
	}
	
    
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: