MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / PercolationVisualizer

Class PercolationVisualizer

LabEnv/01Lab/PercolationVisualizer.java:24–85  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

22import java.awt.Font;
23
24public class PercolationVisualizer {
25
26 // delay in milliseconds (controls animation speed)
27 private static final int DELAY = 50;
28
29 // draw n-by-n percolation system
30 public static void draw(Percolation perc, int n) {
31 StdDraw.clear();
32 StdDraw.setPenColor(StdDraw.BLACK);
33 StdDraw.setXscale(-0.05 * n, 1.05 * n);
34 StdDraw.setYscale(-0.05 * n, 1.05 * n); // leave a border to write text
35 StdDraw.filledSquare(n / 2.0, n / 2.0, n / 2.0);
36
37 // draw n-by-n grid
38 int opened = 0;
39 for (int row = 1; row <= n; row++) {
40 for (int col = 1; col <= n; col++) {
41 if (perc.isFull(row, col)) {
42 StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);
43 opened++;
44 }
45 else if (perc.isOpen(row, col)) {
46 StdDraw.setPenColor(StdDraw.WHITE);
47 opened++;
48 }
49 else
50 StdDraw.setPenColor(StdDraw.BLACK);
51 StdDraw.filledSquare(col - 0.5, n - row + 0.5, 0.45);
52 }
53 }
54
55 // write status text
56 StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12));
57 StdDraw.setPenColor(StdDraw.BLACK);
58 StdDraw.text(0.25 * n, -0.025 * n, opened + " open sites");
59 if (perc.percolates()) StdDraw.text(0.75 * n, -0.025 * n, "percolates");
60 else StdDraw.text(0.75 * n, -0.025 * n, "does not percolate");
61
62 }
63
64 public static void main(String[] args) {
65 In in = new In(args[0]); // input file
66 int n = in.readInt(); // n-by-n percolation system
67
68 // turn on animation mode
69 StdDraw.enableDoubleBuffering();
70
71 // repeatedly read in sites to open and draw resulting system
72 Percolation perc = new Percolation(n);
73 draw(perc, n);
74 StdDraw.show();
75 StdDraw.pause(DELAY);
76 while (!in.isEmpty()) {
77 int i = in.readInt();
78 int j = in.readInt();
79 perc.open(i, j);
80 draw(perc, n);
81 StdDraw.show();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected