[英]Looking for an algorithm to switch lights in traffic light
给定greenLightDuration和yellowLightDuration,我需要根据持续时间切换灯光(包括红色Light)。 这一切都发生在交通信号灯的run方法内。 运行方法的原因是因为在运行整个模拟时使用它(trafficLight是代理)。
//Run method for agents in Model
public void run(double duration) {
if (disposed)
throw new IllegalStateException();
for (int i=0; i<duration; i++) {
time++;
for (Agent a : agents.toArray(new Agent[0])) {
a.run(time);
}
super.setChanged();
super.notifyObservers();
}
}
在Light中,我有运行方法...
public void run(double runTime){
double check_time = runtime - time;
if(check_time >= yellowLightDuration&& color == Color.RED){
color = Color.GREEN;
time = runtime;
}else if(check_time >= greenLightDuration&& color == Color.GREEN){
color = Color.RED;
time = runtime;
}
...但是我所做的只是愚蠢的事情,我要让灯光从红色/绿色切换,显然不适用于黄色,或者与绿色/黄色光的持续时间不成比例(我不认为)。
对于颜色,我使用java.awt.Color
Color.RED, Color.YELLOW, Color.GREEN
。
public void run(double runtime){
if(this.color == Color.GREEN){
if(time%greenLightDuration==0){
color = Color.YELLOW;
}
}
if(this.color == Color.YELLOW){
if(time%yellowLightDuration == 0){
color = Color.RED;
}
}
else
color = Color.GREEN;
}
尝试了一下,但是三种颜色闪烁着。 我将绿色设置为200,将黄色设置为40。
由于这是一个循环,因此您希望使用模数运算符获得循环的当前相位。 类似于: double phase = (runTime - startTime) % (greenDuration + yellowDuration + redDuration)
。 您可以在Java中采用浮点数的模数。
三种颜色闪烁着。
第一个/主要原因是模拟器/模型,不一定是交通信号灯(尽管您的交通信号灯仍然是一个问题)。 问题是您当前的时间模型只是一些粗略的for循环,无论其运行速度如何,它都将运行...而且显然运行速度比您的眼睛要快得多。
您可以做的是尝试使用Thread.sleep()
暂时延迟程序来控制仿真中的时间。 以下版本大约每毫秒运行一次迭代...
//Run method for agents in Model
public void run(double duration) {
if (disposed)
throw new IllegalStateException();
for (int i=0; i<duration; i++) {
time++;
try{ Thread.sleep(1); } //wait 1ms
catch(Exception e){} //just resume after interruption
for (Agent a : agents.toArray(new Agent[0])) {
a.run(time);
}
super.setChanged();
super.notifyObservers();
}
}
现在,绿灯的持续时间为300,大约需要0.3秒,这很短暂,但并非不可观察。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.