forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLangton.java
More file actions
73 lines (66 loc) · 1.59 KB
/
Langton.java
File metadata and controls
73 lines (66 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Langton's Ant.
*/
public class Langton extends Automaton {
private int xpos;
private int ypos;
private int head; // 0=North, 1=East, 2=South, 3=West
/**
* Creates a grid with the ant in the center.
*
* @param rows number of rows
* @param cols number of columns
*/
public Langton(int rows, int cols) {
grid = new GridCanvas(rows, cols, 10);
xpos = rows / 2;
ypos = cols / 2;
head = 0;
}
/**
* Flip the color of the current cell.
*/
private void flipCell() {
Cell cell = grid.getCell(xpos, ypos);
if (cell.isOff()) {
// at a white square; turn right and flip color
head = (head + 1) % 4;
cell.turnOn();
} else {
// at a black square; turn left and flip color
head = (head + 3) % 4;
cell.turnOff();
}
}
/**
* Move the ant forward one unit.
*/
private void moveAnt() {
if (head == 0) {
ypos -= 1;
} else if (head == 1) {
xpos += 1;
} else if (head == 2) {
ypos += 1;
} else {
xpos -= 1;
}
}
/**
* Simulates one round of Langton's Ant.
*/
public void update() {
flipCell();
moveAnt();
}
/**
* Creates and runs the simulation.
*
* @param args command-line arguments
*/
public static void main(String[] args) {
String title = "Langton's Ant";
Langton game = new Langton(61, 61);
game.run(title, 750);
}
}