forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGridCanvas.java
More file actions
120 lines (106 loc) · 2.59 KB
/
GridCanvas.java
File metadata and controls
120 lines (106 loc) · 2.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.awt.Canvas;
import java.awt.Graphics;
/**
* 2D array of cells representing a rectangular grid.
*/
public class GridCanvas extends Canvas {
/** Cells stored in row-major order. */
private Cell[][] array;
/**
* Constructs a grid of given size.
*
* @param rows number of rows
* @param cols number of columns
* @param size pixels per cell
*/
public GridCanvas(int rows, int cols, int size) {
// build 2D array of cells
array = new Cell[rows][cols];
for (int r = 0; r < rows; r++) {
int y = r * size;
for (int c = 0; c < cols; c++) {
int x = c * size;
array[r][c] = new Cell(x, y, size);
}
}
// set the canvas size
setSize(cols * size, rows * size);
}
/**
* @return number of rows
*/
public int numRows() {
return array.length;
}
/**
* @return number of columns
*/
public int numCols() {
return array[0].length;
}
/**
* @param r row index
* @param c column index
* @return the cell
*/
public Cell getCell(int r, int c) {
return array[r][c];
}
/**
* Convenience method that turns on the cell at (r, c).
*
* @param r row index
* @param c column index
*/
public void turnCellOn(int r, int c) {
array[r][c].turnOn();
}
/**
* Returns 1 if the cell at (r, c) exists and is on. Returns 0 if the cell
* doesn't exist or is off.
*
* @param r row index
* @param c column index
* @return 1 or 0
*/
public int test(int r, int c) {
try {
if (array[r][c].isOn()) {
return 1;
}
} catch (ArrayIndexOutOfBoundsException e) {
// cell doesn't exist
}
return 0;
}
/**
* Draws the grid, cell by cell.
*
* @param g graphics context
*/
public void draw(Graphics g) {
for (Cell[] row : array) {
for (Cell cell : row) {
cell.draw(g);
}
}
}
/**
* Paints the grid on the screen.
*
* @param g graphics context
*/
public void paint(Graphics g) {
draw(g);
}
/**
* Overriding this method helps the simulation run more smoothly. Normally
* the Canvas is cleared before painting, but there is no need to clear it
* since the paint method draws the entire grid.
*
* @param g graphics context
*/
public void update(Graphics g) {
draw(g);
}
}