-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoadComponent.java
More file actions
108 lines (96 loc) · 3.07 KB
/
RoadComponent.java
File metadata and controls
108 lines (96 loc) · 3.07 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
package RoadApplet;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class RoadComponent extends JComponent {
private Road freeway;
private BufferedImage buffer;
private int row;
private int x_size;
private int y_size;
public RoadComponent() {
freeway = new Road();
row = 0;
}
public void update(double slowdown, double arrival) {
freeway.update(slowdown, arrival);
Graphics g;
if (buffer == null) {
x_size = getWidth();
y_size = getHeight();
if (x_size == 0 || y_size == 0) return;
buffer = new BufferedImage(x_size, y_size, BufferedImage.TYPE_INT_ARGB);
g = buffer.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, x_size, y_size);
} else
g = buffer.getGraphics();
int DOT_SIZE = 2;
if (row < y_size - 2 * DOT_SIZE)
row += DOT_SIZE;
else {
g.copyArea(0, DOT_SIZE, x_size, y_size - DOT_SIZE, 0, -DOT_SIZE);
}
int x_DOT_DIST = 1;
freeway.paint(g, row, x_DOT_DIST, DOT_SIZE);
g.dispose();
repaint();
}
public void paintComponent(Graphics g) {
if (buffer != null)
g.drawImage(buffer, 0, 0, null);
}
}
class Road {
public static final int LENGTH = 400;
public static final int MAX_SPEED = 5;
private int[] speed;
private Color[] colors;
private int count;
public Road() {
speed = new int[LENGTH];
colors = new Color[LENGTH];
for (int i = 0; i < LENGTH; i++) speed[i] = -1;
}
public void update(double prob_slowdown, double prob_create) {
int i = 0;
while (i < LENGTH && speed[i] == -1)
i++;
while (i < LENGTH) {
if (Math.random() <= prob_slowdown && speed[i] > 0)
speed[i]--;
else if (speed[i] < MAX_SPEED)
speed[i]++;
int i_next = i + 1;
while (i_next < LENGTH && speed[i_next] == -1)
i_next++;
if (i_next < LENGTH) {
if (speed[i] >= i_next - i)
speed[i] = i_next - i - 1;
}
if (speed[i] > 0) {
if (i + speed[i] < LENGTH) {
int ni = i + speed[i];
speed[ni] = speed[i];
colors[ni] = colors[i];
}
speed[i] = -1;
}
i = i_next;
}
if (Math.random() <= prob_create && speed[0] == -1) {
speed[0] = (int) (5.99 * Math.random());
colors[0] = ++count % 10 == 0 ? Color.red : Color.black;
}
}
public void paint(Graphics g, int row, int dotdist, int dotsize) {
g.setColor(Color.WHITE);
g.fillRect(0, row, LENGTH * dotsize, dotsize);
for (int i = 0; i < LENGTH; i++) {
if (speed[i] >= 0) {
g.setColor(colors[i]);
g.fillRect(i * dotdist, row, dotsize, dotsize);
}
}
}
}