Jump to content

Hey guys, I'm writing Conway's Game of Life in Java. I'm working on a method that returns the number of live cells around the cell in question. I'm having trouble making the board wrap though. Here's what I have: 

public int neighbours(int row, int column){		int neighbours = 0;				for(int x = (row - 1); x < (row + 2); x++){			for(int y = (column - 1); y < (column + 2); y++){				if(isAlive(x, y)){					neighbours++;				}			}		}		if(isAlive(row, column)){			neighbours--;		}						return neighbours;	

Basically, if the cell has coordinate 0,0 , it will obviously trigger an out of bounds exception. So, for example, if I pass 0,0 into this method, I want it to check the other side of the board when it checks for a live cell to the left of the cell in question. Any help would be appreciated! Thanks!

Link to comment
https://linustechtips.com/topic/353446-game-of-life-java/
Share on other sites

Link to post
Share on other sites

you could use a method that validates the coordinates of a certain cell in the map. the method would return the correct coordinates

 

so for instance, if we have a board of 15x10 cells and the origin is (0, 0)

private int validateX(int x);private int validateY(int y);validateX(5); // returns 5validateX(15); // returns 0validateX(-1); // returns 14validateY(10); // returns 0
Link to comment
https://linustechtips.com/topic/353446-game-of-life-java/#findComment-4803956
Share on other sites

Link to post
Share on other sites

If performance is a concern, set your grid dimensions to powers of two and use an AND mask (&) to accomplish wrapping.  And-ing is two orders of magnitude faster than modulo... crazy slow!

// This assumes familiarity with bit manipulating operators <<, &, |private static final int MAP_SHIFT = 8, MAP_SCALE = 1 << MAP_SHIFT, MAP_MASK = MAP_SCALE - 1;private static final int MAP_SIZE = MAP_SCALE * MAP_SCALE;// Store two-dimensional grid in one-dimensional array, so we can avoid slowness of "pointer chasing"private static final boolean[] values = new boolean[MAP_SIZE];boolean valueAt(int x, int y){    return values[(y & MAP_MASK) << MAP_SHIFT | (x & MAP_MASK)];}

Determining "MAP_MASK" is a little tricky - basically, because our scale is a power of two, we can obtain a mask of full ones by subtracting one from it.  E.g., "0x10000 - 1 == 0xffff"

Link to comment
https://linustechtips.com/topic/353446-game-of-life-java/#findComment-4811277
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×