Skip to content

Instantly share code, notes, and snippets.

@rdammkoehler
Created January 30, 2011 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdammkoehler/802500 to your computer and use it in GitHub Desktop.
Save rdammkoehler/802500 to your computer and use it in GitHub Desktop.
Part of Conway's Game of Life in Java pushing on the OO boundary
protected Map<Cell, State> captureStateTransitions(Ecosystem ecosystem) {
Map<Cell, State> stateTransitions = createSelfMinimizingMap();
for (Cell cell : ecosystem.getCells()) {
stateTransitions.put(cell, getRules().evaluate(ecosystem, cell));
}
return stateTransitions;
}
package gol.impl;
import gol.Cell;
import gol.Rules;
import gol.Ecosystem;
import gol.Rule;
import gol.Cell.State;
import java.util.Arrays;
import java.util.List;
public class DefaultRules implements Rules {
private List<Rule> rules;
public DefaultRules(Rule[] rules) {
setRules(Arrays.asList(rules));
}
@Override
public State evaluate(Ecosystem ecosystem, Cell cell) {
State state = cell.getState();
int liveNeighborCount = ecosystem.getNeighborCount(cell);
for (int index = 0; state.equals(cell.getState()) && index < rules.size(); index++) {
state = rules.get(index).evaluate(cell.getState(), liveNeighborCount);
}
return state;
}
@Override
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
package gol.impl;
import static gol.Cell.State.DEAD;
import gol.Rule;
import gol.Cell.State;
public class ResurectableRule implements Rule {
@Override
public State evaluate(State state, int neighborCount) {
return (DEAD == state && 3 == neighborCount) ? State.ALIVE : state;
}
}
package gol.impl;
import static gol.Cell.State.ALIVE;
import gol.Rule;
import gol.Cell.State;
public class OverPopulatedRule implements Rule {
@Override
public State evaluate(State state, int neighborCount) {
return (ALIVE == state && 3 < neighborCount) ? State.DEAD : state;
}
}
package gol.impl;
import static gol.Cell.State.ALIVE;
import gol.Rule;
import gol.Cell.State;
public class UnderPopulatedRule implements Rule {
@Override
public State evaluate(State state, int neighborCount) {
return (ALIVE == state && 2 > neighborCount) ? State.DEAD : state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment