-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameOfLife.java
More file actions
73 lines (71 loc) · 3.23 KB
/
Copy pathGameOfLife.java
File metadata and controls
73 lines (71 loc) · 3.23 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
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class GameOfLife {
private static int height, width, cellSize;
public static void main(String[] args) {
width = Integer.parseInt(args[0]);
height = Integer.parseInt(args[1]);
cellSize = Integer.parseInt(args[2]);
StdDraw.setCanvasSize(width, height);
StdDraw.setXscale(0, width);
StdDraw.setYscale(0, height);
Queue<Integer> rowOfaliveCells = new Queue<Integer>();
Queue<Integer> colOfalivecells = new Queue<Integer>();
while (!StdIn.isEmpty()) {
int row = StdIn.readInt();
int col = StdIn.readInt();
rowOfaliveCells.enqueue(row);
colOfalivecells.enqueue(col);
}
drawCells(rowOfaliveCells, colOfalivecells);
}
private static void drawCells(Queue<Integer> r, Queue<Integer> c) {
if (r.isEmpty() || c.isEmpty()) return;
for (int i = 0; i * cellSize < width; i++) {
StdDraw.line(i * cellSize, 0, i * cellSize, height);
}
for (int i = 0; i * cellSize < height; i++) {
StdDraw.line(0, i * cellSize, width, i * cellSize);
}
Queue<Integer> rowOfaliveCells = new Queue<Integer>();
Queue<Integer> colOfalivecells = new Queue<Integer>();
boolean[][] isAlive = new boolean[height / cellSize][width / cellSize];
boolean[][] ac = new boolean[height / cellSize][width / cellSize];
while (!r.isEmpty()) {
int row = r.dequeue();
int col = c.dequeue();
isAlive[row][col] = true;
ac[row][col] = true;
StdDraw.filledSquare(col * cellSize - 0.5 * cellSize,
height - row * cellSize + 0.5 * cellSize,
cellSize * 0.5);
}
for (int i = 0; i < height / cellSize; i++) {
for (int j = 0; j < width / cellSize; j++) {
int count = 0;
if (j < width / cellSize - 1 && isAlive[i][j + 1]) count++;
if (j > 0 && isAlive[i][j - 1]) count++;
if (i < height / cellSize - 1 && isAlive[i + 1][j]) count++;
if (i > 0 && isAlive[i - 1][j]) count++;
if (i < height / cellSize - 1 && j < width / cellSize - 1 && isAlive[i + 1][j + 1])
count++;
if (i > 0 && j < width / cellSize - 1 && isAlive[i - 1][j + 1]) count++;
if (i < height / cellSize - 1 && j > 0 && isAlive[i + 1][j - 1]) count++;
if (i > 0 && j > 0 && isAlive[i - 1][j - 1]) count++;
if (count == 3) ac[i][j] = true;
else if (count > 3) ac[i][j] = false;
else if (count == 0 || count == 1) ac[i][j] = false;
if (ac[i][j]) {
colOfalivecells.enqueue(j);
rowOfaliveCells.enqueue(i);
}
}
}
StdDraw.show(100);
StdDraw.clear();
drawCells(rowOfaliveCells, colOfalivecells);
}
}