-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficLight.java
More file actions
88 lines (77 loc) · 2.91 KB
/
TrafficLight.java
File metadata and controls
88 lines (77 loc) · 2.91 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
package Model;
import java.awt.*;
import java.util.Random;
public class TrafficLight {
private static final double CHANGE = 0.4; // more often red
private static final String GREEN = "green";
private static final String RED = "red";
private String id;
private String state;
private int position;
private Road roadAttachedTo;
public TrafficLight(String id, Road road) {
this.id = "light_" + id;
state = RED;
this.roadAttachedTo = road;
position = this.roadAttachedTo.getLength(); // always places the traffic light at the end of the roadAttachedTo.
this.roadAttachedTo.getLightsOnRoad().add(this); // adds this light to the road it belongs to.
}
public void operate(int seed) {
Random random = new Random(seed);
double probability = random.nextDouble();
//only changes if vehicles are present:
if (probability > CHANGE && !getRoadAttachedTo().getVehiclesOnRoad().isEmpty()) {
setState(RED);
} else {
setState(GREEN);
}
}
public void printLightStatus() {
System.out.printf("%s is:%s on %s at position:%s%n", getId(), getState(), this.getRoadAttachedTo().getId(), this.getPosition());
}
public String getState() {
return state;
}
private void setState(String state) {
this.state = state;
}
public Road getRoadAttachedTo() {
return roadAttachedTo;
}
public int getPosition() {
return position;
}
public String getId() {
return id;
}
public void draw(Graphics g, int scale) {
if (roadAttachedTo.getOrientation() == Road.Orientation.HORIZONTAL) {
switch (state) {
case "red":
g.setColor(Color.red);
break;
case "green":
g.setColor(Color.green);
}
int[] startLocation = getRoadAttachedTo().getStartLocation();
int x = (getPosition() + startLocation[0]) * scale;
int y = startLocation[1] * scale;
int height = (getRoadAttachedTo().getWidth() / 2) * scale;
g.fillRect(x, y, scale, height);
}
if (roadAttachedTo.getOrientation() == Road.Orientation.VERTICAL) {
switch (state) {
case "red":
g.setColor(Color.red);
break;
case "green":
g.setColor(Color.green);
}
int[] startLocation = getRoadAttachedTo().getStartLocation();
int x = (startLocation[0] + (getRoadAttachedTo().getWidth() / 2)) * scale;
int y = (getPosition() + startLocation[1]) * scale;
int width = (getRoadAttachedTo().getWidth() / 2) * scale;
g.fillRect(x, y, width, scale);
}
}
}