Skip to content

Commit 192f1e7

Browse files
committed
Suggestions in Conway
1 parent 096ebdd commit 192f1e7

2 files changed

Lines changed: 14 additions & 20 deletions

File tree

ch15/Conway.java

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,13 @@ public Conway(String path, int margin) {
8787
*/
8888
private int countAlive(int r, int c) {
8989
int count = 0;
90-
count += grid.test(r - 1, c - 1);
91-
count += grid.test(r - 1, c);
92-
count += grid.test(r - 1, c + 1);
93-
count += grid.test(r, c - 1);
94-
count += grid.test(r, c + 1);
95-
count += grid.test(r + 1, c - 1);
96-
count += grid.test(r + 1, c);
97-
count += grid.test(r + 1, c + 1);
90+
for (int i=-1; i<=1; i++) {
91+
for (int j=-1; j<=1; j++) {
92+
if (i!=0 || j!=0) {
93+
count += grid.test(r+i, c+j);
94+
}
95+
}
96+
}
9897
return count;
9998
}
10099

@@ -106,18 +105,12 @@ private int countAlive(int r, int c) {
106105
*/
107106
private static void updateCell(Cell cell, int count) {
108107
if (cell.isOn()) {
109-
if (count < 2) {
108+
if (count < 2 || count > 3) {
110109
// Any live cell with fewer than two live neighbors dies,
111110
// as if by underpopulation.
112-
cell.turnOff();
113-
} else if (count > 3) {
114-
// Any live cell with more than three live neighbors dies,
111+
// Any live cell with more than three live neighbors dies,
115112
// as if by overpopulation.
116113
cell.turnOff();
117-
} else {
118-
// Any live cell with two or three live neighbors lives on
119-
// to the next generation.
120-
cell.turnOn();
121114
}
122115
} else {
123116
if (count == 3) {
@@ -146,7 +139,8 @@ public void update() {
146139
// update each cell based on neighbor counts
147140
for (int r = 0; r < rows; r++) {
148141
for (int c = 0; c < cols; c++) {
149-
updateCell(grid.getCell(r, c), counts[r][c]);
142+
final Cell cell = grid.getCell(r, c);
143+
updateCell(cell, counts[r][c]);
150144
}
151145
}
152146

ch15/Main.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ public class Main {
1313
*/
1414
public static void main(String[] args) {
1515
String title = "Conway's Game of Life";
16-
Automaton game = new Conway();
17-
// Automaton game = new Conway("pulsar.cells", 2);
16+
//Automaton game = new Conway();
17+
Automaton game = new Conway("pulsar.cells", 2);
1818
runSimulation(title, game, 500);
1919
}
2020

@@ -40,7 +40,7 @@ public static void runSimulation(String title, Automaton game, int delay) {
4040

4141
// update the drawing
4242
game.update();
43-
toolkit.sync();
43+
//toolkit.sync();
4444

4545
// delay the simulation
4646
try {

0 commit comments

Comments
 (0)