寻找一种在交通信号灯中切换灯光的算法

时间:2015-11-17 02:22:26

标签: java

给定greenLightDuration和yellowLightDuration,我需要根据持续时间切换灯光(包括红灯)。这一切都发生在交通灯的运行方法中。运行方法的原因是因为它在运行整个模拟时使用(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();
            }
        }

在光中我有跑步方法......

 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;
        }

...但是我只是做了一些愚蠢的事情,让灯光从红色/绿色切换,显然不适用于黄色或与绿色/黄色灯光持续时间不成比例(我不认为)。

我使用的颜色 来自Color.RED, Color.YELLOW, Color.GREEN的{​​{1}}。

java.awt.Color

试过这个,但三种颜色都在疯狂地闪烁。我将绿色设置为200,将黄色设置为40。

2 个答案:

答案 0 :(得分:1)

由于这是一个循环,您希望使用模数运算符获取循环的当前阶段。类似于:double phase = (runTime - startTime) % (greenDuration + yellowDuration + redDuration)。您可以在Java中获取浮点数的模数。

答案 1 :(得分:0)

  这三种颜色正在疯狂地闪烁。

第一个/主要原因是模拟器/模型,而不一定是红绿灯(虽然你的红绿灯仍然是一个问题)。问题在于,你当前的时间模型只是一些粗略的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秒,这是活跃但不可观察的。