Skip to content

Commit 561ca41

Browse files
committed
Refactoring Main and Main2
1 parent b10cd8e commit 561ca41

3 files changed

Lines changed: 37 additions & 15 deletions

File tree

ch15/Langton.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ public class Langton extends Automaton {
88
private int head; // 0=North, 1=East, 2=South, 3=West
99

1010
/**
11-
* Creates an 11x11 grid with the ant in the center.
11+
* Creates a grid with the ant in the center.
1212
*/
13-
public Langton() {
14-
grid = new GridCanvas(11, 11, SIZE);
15-
xpos = 5;
16-
ypos = 5;
13+
public Langton(int nrows, int ncols) {
14+
grid = new GridCanvas(nrows, ncols, 10);
15+
xpos = nrows / 2;
16+
ypos = ncols / 2;
1717
head = 0;
1818
}
1919

ch15/Main.java

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,25 @@
77
public class Main {
88

99
/**
10-
* Sets up the grid, creates the frame, and plays the game.
10+
* Creates an automaton and runs it.
1111
*
1212
* @param args command-line arguments
1313
*/
1414
public static void main(String[] args) {
15-
1615
String title = "Conway's Game of Life";
1716
Automaton game = new Conway("pulsar.cells", 2);
17+
runSimulation(title, game, 500);
18+
}
1819

19-
// String title = "Langton's Ant";
20-
// Automaton game = new Langton();
21-
22-
// set up the window frame
20+
/**
21+
* Creates a JFrame and runs the simulation.
22+
*
23+
* @param title
24+
* @param game
25+
* @param delay
26+
*/
27+
public static void runSimulation(String title, Automaton game, int delay) {
28+
// set up the window frame
2329
JFrame frame = new JFrame(title);
2430
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
2531
frame.setResizable(false);
@@ -32,16 +38,15 @@ public static void main(String[] args) {
3238
while (true) {
3339

3440
// update the drawing
35-
toolkit.sync();
3641
game.update();
42+
toolkit.sync();
3743

3844
// delay the simulation
3945
try {
40-
Thread.sleep(500);
46+
Thread.sleep(delay);
4147
} catch (InterruptedException e) {
4248
// do nothing
4349
}
4450
}
45-
}
46-
51+
}
4752
}

ch15/Main2.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Application that runs a cellular automaton.
3+
*/
4+
public class Main2 {
5+
6+
/**
7+
* Creates an automaton and runs it.
8+
*
9+
* @param args command-line arguments
10+
*/
11+
public static void main(String[] args) {
12+
String title = "Langton's Ant";
13+
Automaton game = new Langton(61, 61);
14+
Main.runSimulation(title, game, 1);
15+
}
16+
17+
}

0 commit comments

Comments
 (0)