Skip to content

Instantly share code, notes, and snippets.

@toutantic
Created December 5, 2011 12:24
Show Gist options
  • Save toutantic/1433426 to your computer and use it in GitHub Desktop.
Save toutantic/1433426 to your computer and use it in GitHub Desktop.
Game of live
package gol;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class World {
Set<String> world = new HashSet<String>();
public void addLiveCell(int x, int y) {
world.add(getkey(x, y));
}
private String getkey(int x, int y) {
return x + ":" + y;
}
private int getX(String key) {
return Integer.valueOf(key.split(":")[0]);
}
private int getY(String key) {
return Integer.valueOf(key.split(":")[1]);
}
public int getNumberOfNeighbour(int x, int y) {
int numberOfNb = 0;
List<String> neighbour = getNeighbour(x,y);
for (String key : neighbour) {
if (world.contains(key)) {
numberOfNb++;
}
}
return numberOfNb;
}
public int getNumberOfNeighbour(String key) {
return getNumberOfNeighbour(getX(key), getY(key));
}
private List<String> getNeighbour(String key) {
return getNeighbour(getX(key), getY(key));
}
private java.util.List<String> getNeighbour(int x, int y) {
List<String> nb = new ArrayList<String>();
nb.add(getkey(x-1, y-1));
nb.add(getkey(x-1, y));
nb.add(getkey(x-1, y+1));
nb.add(getkey(x, y-1));
nb.add(getkey(x, y+1));
nb.add(getkey(x+1, y-1));
nb.add(getkey(x+1, y));
nb.add(getkey(x+1, y+1));
return nb;
}
public void tick() {
Set<String> newWorld = new HashSet<String>();
Set<String> neighbourCells = new HashSet<String>();
for(String key : world) {
if (ifThreeOrTwoNeighbour(key)) {
newWorld.add(key);
}
neighbourCells.addAll(getNeighbour(key));
}
for(String key : neighbourCells) {
if (ifThreeNeighbour(key)) {
newWorld.add(key);
}
}
world = newWorld;
}
private boolean ifThreeOrTwoNeighbour(String key) {
int numberOfNeighbour = getNumberOfNeighbour(key);
return numberOfNeighbour == 3 || numberOfNeighbour == 2;
}
private boolean ifThreeNeighbour(String key) {
int numberOfNeighbour = getNumberOfNeighbour(key);
return numberOfNeighbour == 3;
}
public boolean isAlive(int x, int y) {
return world.contains(getkey(x, y));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment