Flying LinesThe next example is harder to describe than it is to code. Like Mondrian it runs in an infinite loop but it's a little more than random images. Compile the following code, run it and then look over the code to see if you can understand the algorithm.//Bounce lines around in a box import java.applet.Applet; import java.awt.*; public class FlyingLines extends Applet { int NUM_LINES = 25; int gDeltaTop=3, gDelta=3; int gDeltaLeft=2, gDeltaRight=6; int Applet, Applet; int gLines[][] = new int[NUM_LINES][4]; public void init() { Applet = size().; Applet = size().; } public void start() { gLines[0][0] = Randomize(Applet); gLines[0][1] = Randomize(Applet); gLines[0][2] = Randomize(Applet); gLines[0][3] = Randomize(Applet); for (int i=1; i < NUM_LINES; i++ ) { LineCopy(i, i-1); RecalcLine(i); } repaint(); } public void paint(Graphics g) { while (true) { for (int i=NUM_LINES - 1; i 0; i--) { LineCopy(i, i-1); } RecalcLine(0); g.setColor(Color.black); g.drawLine(gLines[0][0], gLines[0][1], gLines[0][2], gLines[0][3]); g.setColor(getBackground()); g.drawLine(gLines[NUM_LINES-1][0], gLines[NUM_LINES-1][1], gLines[NUM_LINES-1][2], gLines[NUM_LINES-1][3]); } } private void LineCopy (int to, int from) { for (int i = 0; i < 4; i++) { gLines[to][i] = gLines[from][i]; } } public int Randomize( int range ) { double rawResult; rawResult = Math.random(); return (int) (rawResult * range); } private void RecalcLine( int i ) { gLines[i][1] += gDeltaTop; if ((gLines[i][1] < 0) || (gLines[i][1] Applet)) { gDeltaTop *= -1; gLines[i][1] += 2*gDeltaTop; } gLines[i][3] += gDelta; if ( (gLines[i][3] < 0) || (gLines[i][3] Applet) ) { gDelta *= -1; gLines[i][3] += 2*gDelta; } gLines[i][0] += gDeltaLeft; if ( (gLines[i][0] < 0) || (gLines[i][0] Applet) ) { gDeltaLeft *= -1; gLines[i][0] += 2*gDeltaLeft; } gLines[i][2] += gDeltaRight; if ( (gLines[i][2] < 0) || (gLines[i][2] Applet) ) { gDeltaRight *= -1; gLines[i][2] += 2*gDeltaRight; } } //RecalcLine ends here } // FlyingLines ends here
|
Bhopal news
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